prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>sending_img_through_links.py<|end_file_name|><|fim▁begin|># coding: utf-8"
"""
Example demonstrating how to use the ``input_label`` to send images between
blocks.<|fim▁hole|>
Required hardware:
- Any camera
"""
import crappy
if __name__ == "__main__":
cam1 = crappy.blocks.Camera('Webcam')
dis = crappy.blocks.DISCorrel('', input_label='frame')
crappy.link(cam1, dis)
graph = crappy.blocks.Grapher(('t(s)', 'x(pix)'))
crappy.link(dis, graph)
crappy.start()<|fim▁end|> |
This mechanism is useful to perform fake tests by using using generated images
instead of cameras to read images. |
<|file_name|>soccer_ball.py<|end_file_name|><|fim▁begin|># Copyright 2019 The dm_control 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.
# ============================================================================
"""A soccer ball that keeps track of ball-player contacts."""
import os
from dm_control import mjcf
from dm_control.entities import props
import numpy as np
from dm_control.utils import io as resources
_ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'soccer_ball')
# FIFA regulation parameters for a size 5 ball.
_REGULATION_RADIUS = 0.117 # Meters.
_REGULATION_MASS = 0.45 # Kilograms.
_DEFAULT_FRICTION = (0.7, 0.05, 0.04) # (slide, spin, roll).
_DEFAULT_DAMP_RATIO = 0.4
def _get_texture(name):
contents = resources.GetResource(
os.path.join(_ASSETS_PATH, '{}.png'.format(name)))
return mjcf.Asset(contents, '.png')
def regulation_soccer_ball():
return SoccerBall(
radius=_REGULATION_RADIUS,
mass=_REGULATION_MASS,
friction=_DEFAULT_FRICTION,
damp_ratio=_DEFAULT_DAMP_RATIO)
<|fim▁hole|> """A soccer ball that keeps track of entities that come into contact."""
def _build(self,
radius=0.35,
mass=0.045,
friction=(0.7, 0.075, 0.075),
damp_ratio=1.0,
name='soccer_ball'):
"""Builds this soccer ball.
Args:
radius: The radius (in meters) of this target sphere.
mass: Mass (in kilograms) of the ball.
friction: Friction parameters of the ball geom with the three dimensions
corresponding to (slide, spin, roll) frictions.
damp_ratio: A real positive number. Lower implies less dampening upon
contacts.
name: The name of this entity.
"""
super()._build(geom_type='sphere', size=(radius,), name=name)
texture = self._mjcf_root.asset.add(
'texture',
name='soccer_ball',
type='cube',
fileup=_get_texture('up'),
filedown=_get_texture('down'),
filefront=_get_texture('front'),
fileback=_get_texture('back'),
fileleft=_get_texture('left'),
fileright=_get_texture('right'))
material = self._mjcf_root.asset.add(
'material', name='soccer_ball', texture=texture)
if damp_ratio < 0.0:
raise ValueError(
f'Invalid `damp_ratio` parameter ({damp_ratio} is not positive).')
self._geom.set_attributes(
pos=[0, 0, radius],
size=[radius],
condim=6,
priority=1,
mass=mass,
friction=friction,
solref=[0.02, damp_ratio],
material=material)
# Add some tracking cameras for visualization and logging.
self._mjcf_root.worldbody.add(
'camera',
name='ball_cam_near',
pos=[0, -2, 2],
zaxis=[0, -1, 1],
fovy=70,
mode='trackcom')
self._mjcf_root.worldbody.add(
'camera',
name='ball_cam',
pos=[0, -7, 7],
zaxis=[0, -1, 1],
fovy=70,
mode='trackcom')
self._mjcf_root.worldbody.add(
'camera',
name='ball_cam_far',
pos=[0, -10, 10],
zaxis=[0, -1, 1],
fovy=70,
mode='trackcom')
# Keep track of entities to team mapping.
self._players = []
# Initialize tracker attributes.
self.initialize_entity_trackers()
def register_player(self, player):
self._players.append(player)
def initialize_entity_trackers(self):
self._last_hit = None
self._hit = False
self._repossessed = False
self._intercepted = False
# Tracks distance traveled by the ball in between consecutive hits.
self._pos_at_last_step = None
self._dist_since_last_hit = None
self._dist_between_last_hits = None
def initialize_episode(self, physics, unused_random_state):
self._geom_id = physics.model.name2id(self._geom.full_identifier, 'geom')
self._geom_id_to_player = {}
for player in self._players:
geoms = player.walker.mjcf_model.find_all('geom')
for geom in geoms:
geom_id = physics.model.name2id(geom.full_identifier, 'geom')
self._geom_id_to_player[geom_id] = player
self.initialize_entity_trackers()
def after_substep(self, physics, unused_random_state):
"""Resolve contacts and update ball-player contact trackers."""
if self._hit:
# Ball has already registered a valid contact within step (during one of
# previous after_substep calls).
return
# Iterate through all contacts to find the first contact between the ball
# and one of the registered entities.
for contact in physics.data.contact:
# Keep contacts that involve the ball and one of the registered entities.
has_self = False
for geom_id in (contact.geom1, contact.geom2):
if geom_id == self._geom_id:
has_self = True
else:
player = self._geom_id_to_player.get(geom_id)
if has_self and player:
# Detected a contact between the ball and an registered player.
if self._last_hit is not None:
self._intercepted = player.team != self._last_hit.team
else:
self._intercepted = True
# Register repossessed before updating last_hit player.
self._repossessed = player is not self._last_hit
self._last_hit = player
# Register hit event.
self._hit = True
break
def before_step(self, physics, random_state):
super().before_step(physics, random_state)
# Reset per simulation step indicator.
self._hit = False
self._repossessed = False
self._intercepted = False
def after_step(self, physics, random_state):
super().after_step(physics, random_state)
pos = physics.bind(self._geom).xpos
if self._hit:
# SoccerBall is hit on this step. Update dist_between_last_hits
# to dist_since_last_hit before resetting dist_since_last_hit.
self._dist_between_last_hits = self._dist_since_last_hit
self._dist_since_last_hit = 0.
self._pos_at_last_step = pos.copy()
if self._dist_since_last_hit is not None:
# Accumulate distance traveled since last hit event.
self._dist_since_last_hit += np.linalg.norm(pos - self._pos_at_last_step)
self._pos_at_last_step = pos.copy()
@property
def last_hit(self):
"""The player that last came in contact with the ball or `None`."""
return self._last_hit
@property
def hit(self):
"""Indicates if the ball is hit during the last simulation step.
For a timeline shown below:
..., agent.step, simulation, agent.step, ...
Returns:
True: if the ball is hit by a registered player during simulation step.
False: if not.
"""
return self._hit
@property
def repossessed(self):
"""Indicates if the ball has been repossessed by a different player.
For a timeline shown below:
..., agent.step, simulation, agent.step, ...
Returns:
True if the ball is hit by a registered player during simulation step
and that player is different from `last_hit`.
False: if the ball is not hit, or the ball is hit by `last_hit` player.
"""
return self._repossessed
@property
def intercepted(self):
"""Indicates if the ball has been intercepted by a different team.
For a timeline shown below:
..., agent.step, simulation, agent.step, ...
Returns:
True: if the ball is hit for the first time, or repossessed by an player
from a different team.
False: if the ball is not hit, not repossessed, or repossessed by a
teammate to `last_hit`.
"""
return self._intercepted
@property
def dist_between_last_hits(self):
"""Distance between last consecutive hits.
Returns:
Distance between last two consecutive hit events or `None` if there has
not been two consecutive hits on the ball.
"""
return self._dist_between_last_hits<|fim▁end|> |
class SoccerBall(props.Primitive): |
<|file_name|>grpc_error_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tabletconn
<|fim▁hole|>import (
"testing"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
"github.com/youtube/vitess/go/vt/vterrors"
)
func TestTabletErrorFromRPCError(t *testing.T) {
testcases := []struct {
in *vtrpcpb.RPCError
want vtrpcpb.Code
}{{
in: &vtrpcpb.RPCError{
LegacyCode: vtrpcpb.LegacyErrorCode_BAD_INPUT_LEGACY,
Message: "bad input",
},
want: vtrpcpb.Code_INVALID_ARGUMENT,
}, {
in: &vtrpcpb.RPCError{
LegacyCode: vtrpcpb.LegacyErrorCode_BAD_INPUT_LEGACY,
Message: "bad input",
Code: vtrpcpb.Code_INVALID_ARGUMENT,
},
want: vtrpcpb.Code_INVALID_ARGUMENT,
}, {
in: &vtrpcpb.RPCError{
Message: "bad input",
Code: vtrpcpb.Code_INVALID_ARGUMENT,
},
want: vtrpcpb.Code_INVALID_ARGUMENT,
}}
for _, tcase := range testcases {
got := vterrors.Code(ErrorFromVTRPC(tcase.in))
if got != tcase.want {
t.Errorf("FromVtRPCError(%v):\n%v, want\n%v", tcase.in, got, tcase.want)
}
}
}<|fim▁end|> | |
<|file_name|>address_gateway.py<|end_file_name|><|fim▁begin|>import re
import braintree
from braintree.address import Address
from braintree.error_result import ErrorResult
from braintree.exceptions.not_found_error import NotFoundError
from braintree.resource import Resource
from braintree.successful_result import SuccessfulResult
class AddressGateway(object):
def __init__(self, gateway):
self.gateway = gateway
self.config = gateway.config
def create(self, params={}):
Resource.verify_keys(params, Address.create_signature())
if not "customer_id" in params:
raise KeyError("customer_id must be provided")
if not re.search("\A[0-9A-Za-z_-]+\Z", params["customer_id"]):
raise KeyError("customer_id contains invalid characters")
response = self.config.http().post("/customers/" + params.pop("customer_id") + "/addresses", {"address": params})
if "address" in response:
return SuccessfulResult({"address": Address(self.gateway, response["address"])})
elif "api_error_response" in response:
return ErrorResult(self.gateway, response["api_error_response"])
def delete(self, customer_id, address_id):
self.config.http().delete("/customers/" + customer_id + "/addresses/" + address_id)
return SuccessfulResult()
def find(self, customer_id, address_id):
try:
response = self.config.http().get("/customers/" + customer_id + "/addresses/" + address_id)
return Address(self.gateway, response["address"])
except NotFoundError:
raise NotFoundError("address for customer " + customer_id + " with id " + address_id + " not found")
def update(self, customer_id, address_id, params={}):
Resource.verify_keys(params, Address.update_signature())
response = self.config.http().put(
"/customers/" + customer_id + "/addresses/" + address_id,
{"address": params}
)
if "address" in response:<|fim▁hole|><|fim▁end|> | return SuccessfulResult({"address": Address(self.gateway, response["address"])})
elif "api_error_response" in response:
return ErrorResult(self.gateway, response["api_error_response"]) |
<|file_name|>qa_flysky_dumpsync.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2012 <+YOU OR YOUR COMPANY+>.
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software 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 software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
#
from gnuradio import gr, gr_unittest
import flysky_swig
class qa_dumpsync (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_t (self):
# set up fg
self.tb.run ()
# check data
if __name__ == '__main__':<|fim▁hole|> gr_unittest.main ()<|fim▁end|> | |
<|file_name|>app.module.ts<|end_file_name|><|fim▁begin|>import { Store, StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { AppComponent } from './components/app/app.component';
import { PagesComponent } from './components/pages/pages.component';
import { SelectedPageComponent } from './components/selectedPage/selectedPage.component';
import { PileComponent } from './components/pile/pile.component';
import { PileListComponent } from './components/pileList/pileList.component';
import { rootReducer } from './store/pageSorterStore';
import { pageSorterStoreReducer } from './reducers/pageSorterStoreReducer';
import { PagesService } from './services/pagesService';
import { PageBuilder } from './models/Page';
@NgModule({
imports: [
BrowserModule,
HttpModule,
StoreModule.provideStore(pageSorterStoreReducer),<|fim▁hole|> StoreDevtoolsModule.instrumentOnlyWithExtension()
],
declarations: [ AppComponent, PagesComponent, PileComponent, PileListComponent, SelectedPageComponent ],
providers: [ PagesService, PageBuilder ],
bootstrap: [ AppComponent ]
})
export class AppModule { }<|fim▁end|> | |
<|file_name|>interstitial_page_impl.cc<|end_file_name|><|fim▁begin|>// Copyright 2013 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 "content/browser/frame_host/interstitial_page_impl.h"
#include <vector>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
#include "content/browser/dom_storage/session_storage_namespace_impl.h"
#include "content/browser/frame_host/interstitial_page_navigator_impl.h"
#include "content/browser/frame_host/navigation_controller_impl.h"
#include "content/browser/frame_host/navigation_entry_impl.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_view_host_factory.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_view.h"
#include "content/common/frame_messages.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/dom_operation_notification_details.h"
#include "content/public/browser/interstitial_page_delegate.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/bindings_policy.h"
#include "net/base/escape.h"
#include "net/url_request/url_request_context_getter.h"
#include "ui/base/page_transition_types.h"
using blink::WebDragOperation;
using blink::WebDragOperationsMask;
namespace content {
namespace {
void ResourceRequestHelper(ResourceDispatcherHostImpl* rdh,
int process_id,
int render_view_host_id,
ResourceRequestAction action) {
switch (action) {
case BLOCK:
rdh->BlockRequestsForRoute(process_id, render_view_host_id);
break;
case RESUME:
rdh->ResumeBlockedRequestsForRoute(process_id, render_view_host_id);
break;
case CANCEL:
rdh->CancelBlockedRequestsForRoute(process_id, render_view_host_id);
break;
default:
NOTREACHED();
}
}
} // namespace
class InterstitialPageImpl::InterstitialPageRVHDelegateView
: public RenderViewHostDelegateView {
public:
explicit InterstitialPageRVHDelegateView(InterstitialPageImpl* page);
// RenderViewHostDelegateView implementation:
#if defined(OS_MACOSX) || defined(OS_ANDROID)
void ShowPopupMenu(RenderFrameHost* render_frame_host,
const gfx::Rect& bounds,
int item_height,
double item_font_size,
int selected_item,
const std::vector<MenuItem>& items,
bool right_aligned,
bool allow_multiple_selection) override;
void HidePopupMenu() override;
#endif
void StartDragging(const DropData& drop_data,
WebDragOperationsMask operations_allowed,
const gfx::ImageSkia& image,
const gfx::Vector2d& image_offset,
const DragEventSourceInfo& event_info) override;
void UpdateDragCursor(WebDragOperation operation) override;
void GotFocus() override;
void TakeFocus(bool reverse) override;
virtual void OnFindReply(int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update);
private:
InterstitialPageImpl* interstitial_page_;
DISALLOW_COPY_AND_ASSIGN(InterstitialPageRVHDelegateView);
};
// We keep a map of the various blocking pages shown as the UI tests need to
// be able to retrieve them.
typedef std::map<WebContents*, InterstitialPageImpl*> InterstitialPageMap;
static InterstitialPageMap* g_web_contents_to_interstitial_page;
// Initializes g_web_contents_to_interstitial_page in a thread-safe manner.
// Should be called before accessing g_web_contents_to_interstitial_page.
static void InitInterstitialPageMap() {
if (!g_web_contents_to_interstitial_page)
g_web_contents_to_interstitial_page = new InterstitialPageMap;
}
InterstitialPage* InterstitialPage::Create(WebContents* web_contents,
bool new_navigation,
const GURL& url,
InterstitialPageDelegate* delegate) {
return new InterstitialPageImpl(
web_contents,
static_cast<RenderWidgetHostDelegate*>(
static_cast<WebContentsImpl*>(web_contents)),
new_navigation, url, delegate);
}
InterstitialPage* InterstitialPage::GetInterstitialPage(
WebContents* web_contents) {
InitInterstitialPageMap();
InterstitialPageMap::const_iterator iter =
g_web_contents_to_interstitial_page->find(web_contents);
if (iter == g_web_contents_to_interstitial_page->end())
return NULL;
return iter->second;
}
InterstitialPageImpl::InterstitialPageImpl(
WebContents* web_contents,
RenderWidgetHostDelegate* render_widget_host_delegate,
bool new_navigation,
const GURL& url,
InterstitialPageDelegate* delegate)
: underlying_content_observer_(web_contents, this),
web_contents_(web_contents),
controller_(static_cast<NavigationControllerImpl*>(
&web_contents->GetController())),
render_widget_host_delegate_(render_widget_host_delegate),
url_(url),
new_navigation_(new_navigation),
should_discard_pending_nav_entry_(new_navigation),
reload_on_dont_proceed_(false),
enabled_(true),
action_taken_(NO_ACTION),
render_view_host_(NULL),
// TODO(nasko): The InterstitialPageImpl will need to provide its own
// NavigationControllerImpl to the Navigator, which is separate from
// the WebContents one, so we can enforce no navigation policy here.
// While we get the code to a point to do this, pass NULL for it.
// TODO(creis): We will also need to pass delegates for the RVHM as we
// start to use it.
frame_tree_(new InterstitialPageNavigatorImpl(this, controller_),
this, this, this,
static_cast<WebContentsImpl*>(web_contents)),
original_child_id_(web_contents->GetRenderProcessHost()->GetID()),
original_rvh_id_(web_contents->GetRenderViewHost()->GetRoutingID()),
should_revert_web_contents_title_(false),
web_contents_was_loading_(false),
resource_dispatcher_host_notified_(false),
rvh_delegate_view_(new InterstitialPageRVHDelegateView(this)),
create_view_(true),
delegate_(delegate),
weak_ptr_factory_(this) {
InitInterstitialPageMap();
// It would be inconsistent to create an interstitial with no new navigation
// (which is the case when the interstitial was triggered by a sub-resource on
// a page) when we have a pending entry (in the process of loading a new top
// frame).
DCHECK(new_navigation || !web_contents->GetController().GetPendingEntry());
}
InterstitialPageImpl::~InterstitialPageImpl() {
}
void InterstitialPageImpl::Show() {
if (!enabled())
return;
// If an interstitial is already showing or about to be shown, close it before
// showing the new one.
// Be careful not to take an action on the old interstitial more than once.
InterstitialPageMap::const_iterator iter =
g_web_contents_to_interstitial_page->find(web_contents_);
if (iter != g_web_contents_to_interstitial_page->end()) {
InterstitialPageImpl* interstitial = iter->second;
if (interstitial->action_taken_ != NO_ACTION) {
interstitial->Hide();
} else {
// If we are currently showing an interstitial page for which we created
// a transient entry and a new interstitial is shown as the result of a
// new browser initiated navigation, then that transient entry has already
// been discarded and a new pending navigation entry created.
// So we should not discard that new pending navigation entry.
// See http://crbug.com/9791
if (new_navigation_ && interstitial->new_navigation_)
interstitial->should_discard_pending_nav_entry_= false;
interstitial->DontProceed();
}
}
// Block the resource requests for the render view host while it is hidden.
TakeActionOnResourceDispatcher(BLOCK);
// We need to be notified when the RenderViewHost is destroyed so we can
// cancel the blocked requests. We cannot do that on
// NOTIFY_WEB_CONTENTS_DESTROYED as at that point the RenderViewHost has
// already been destroyed.
notification_registrar_.Add(
this, NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
Source<RenderWidgetHost>(controller_->delegate()->GetRenderViewHost()));
// Update the g_web_contents_to_interstitial_page map.
iter = g_web_contents_to_interstitial_page->find(web_contents_);
DCHECK(iter == g_web_contents_to_interstitial_page->end());
(*g_web_contents_to_interstitial_page)[web_contents_] = this;
if (new_navigation_) {
NavigationEntryImpl* entry = new NavigationEntryImpl;
entry->SetURL(url_);
entry->SetVirtualURL(url_);
entry->set_page_type(PAGE_TYPE_INTERSTITIAL);
// Give delegates a chance to set some states on the navigation entry.
delegate_->OverrideEntry(entry);
controller_->SetTransientEntry(entry);
}
DCHECK(!render_view_host_);
render_view_host_ = CreateRenderViewHost();
render_view_host_->AttachToFrameTree();
CreateWebContentsView();
std::string data_url = "data:text/html;charset=utf-8," +
net::EscapePath(delegate_->GetHTMLContents());
frame_tree_.root()->current_frame_host()->NavigateToURL(GURL(data_url));
notification_registrar_.Add(this, NOTIFICATION_NAV_ENTRY_PENDING,
Source<NavigationController>(controller_));
}
void InterstitialPageImpl::Hide() {
// We may have already been hidden, and are just waiting to be deleted.
// We can't check for enabled() here, because some callers have already
// called Disable.
if (!render_view_host_)
return;
Disable();
RenderWidgetHostView* old_view =
controller_->delegate()->GetRenderViewHost()->GetView();
if (controller_->delegate()->GetInterstitialPage() == this &&
old_view &&
!old_view->IsShowing() &&
!controller_->delegate()->IsHidden()) {
// Show the original RVH since we're going away. Note it might not exist if
// the renderer crashed while the interstitial was showing.
// Note that it is important that we don't call Show() if the view is
// already showing. That would result in bad things (unparented HWND on
// Windows for example) happening.
old_view->Show();
}
// If the focus was on the interstitial, let's keep it to the page.
// (Note that in unit-tests the RVH may not have a view).
if (render_view_host_->GetView() &&
render_view_host_->GetView()->HasFocus() &&
controller_->delegate()->GetRenderViewHost()->GetView()) {
controller_->delegate()->GetRenderViewHost()->GetView()->Focus();
}
// Delete this and call Shutdown on the RVH asynchronously, as we may have
// been called from a RVH delegate method, and we can't delete the RVH out
// from under itself.
base::MessageLoop::current()->PostNonNestableTask(
FROM_HERE,
base::Bind(&InterstitialPageImpl::Shutdown,
weak_ptr_factory_.GetWeakPtr()));
render_view_host_ = NULL;
frame_tree_.ResetForMainFrameSwap();
controller_->delegate()->DetachInterstitialPage();
// Let's revert to the original title if necessary.
NavigationEntry* entry = controller_->GetVisibleEntry();
if (entry && !new_navigation_ && should_revert_web_contents_title_) {
entry->SetTitle(original_web_contents_title_);
controller_->delegate()->NotifyNavigationStateChanged(
INVALIDATE_TYPE_TITLE);
}
InterstitialPageMap::iterator iter =
g_web_contents_to_interstitial_page->find(web_contents_);
DCHECK(iter != g_web_contents_to_interstitial_page->end());
if (iter != g_web_contents_to_interstitial_page->end())
g_web_contents_to_interstitial_page->erase(iter);
// Clear the WebContents pointer, because it may now be deleted.
// This signifies that we are in the process of shutting down.
web_contents_ = NULL;
}
void InterstitialPageImpl::Observe(
int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case NOTIFICATION_NAV_ENTRY_PENDING:
// We are navigating away from the interstitial (the user has typed a URL
// in the location bar or clicked a bookmark). Make sure clicking on the
// interstitial will have no effect. Also cancel any blocked requests
// on the ResourceDispatcherHost. Note that when we get this notification
// the RenderViewHost has not yet navigated so we'll unblock the
// RenderViewHost before the resource request for the new page we are
// navigating arrives in the ResourceDispatcherHost. This ensures that
// request won't be blocked if the same RenderViewHost was used for the
// new navigation.
Disable();
TakeActionOnResourceDispatcher(CANCEL);
break;
case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED:
if (action_taken_ == NO_ACTION) {
// The RenderViewHost is being destroyed (as part of the tab being
// closed); make sure we clear the blocked requests.
RenderViewHost* rvh = static_cast<RenderViewHost*>(
static_cast<RenderViewHostImpl*>(
RenderWidgetHostImpl::From(
Source<RenderWidgetHost>(source).ptr())));
DCHECK(rvh->GetProcess()->GetID() == original_child_id_ &&
rvh->GetRoutingID() == original_rvh_id_);
TakeActionOnResourceDispatcher(CANCEL);
}
break;
default:
NOTREACHED();
}
}
bool InterstitialPageImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
const IPC::Message& message) {
if (render_frame_host->GetRenderViewHost() != render_view_host_) {
DCHECK(!render_view_host_)
<< "We expect an interstitial page to have only a single RVH";
return false;
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(InterstitialPageImpl, message)
IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
OnDomOperationResponse)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool InterstitialPageImpl::OnMessageReceived(RenderViewHost* render_view_host,
const IPC::Message& message) {
return false;
}
void InterstitialPageImpl::RenderFrameCreated(
RenderFrameHost* render_frame_host) {
// Note this is only for subframes in the interstitial, the notification for
// the main frame happens in RenderViewCreated.
controller_->delegate()->RenderFrameForInterstitialPageCreated(
render_frame_host);
}
void InterstitialPageImpl::UpdateTitle(
RenderFrameHost* render_frame_host,
int32 page_id,
const base::string16& title,
base::i18n::TextDirection title_direction) {
if (!enabled())
return;
RenderViewHost* render_view_host = render_frame_host->GetRenderViewHost();
DCHECK(render_view_host == render_view_host_);
NavigationEntry* entry = controller_->GetVisibleEntry();
if (!entry) {
// There may be no visible entry if no URL has committed (e.g., after
// window.open("")). InterstitialPages with the new_navigation flag create
// a transient NavigationEntry and thus have a visible entry. However,
// interstitials can still be created when there is no visible entry. For
// example, the opener window may inject content into the initial blank
// page, which might trigger a SafeBrowsingBlockingPage.
return;
}
// If this interstitial is shown on an existing navigation entry, we'll need
// to remember its title so we can revert to it when hidden.
if (!new_navigation_ && !should_revert_web_contents_title_) {
original_web_contents_title_ = entry->GetTitle();
should_revert_web_contents_title_ = true;
}
// TODO(evan): make use of title_direction.
// http://code.google.com/p/chromium/issues/detail?id=27094
entry->SetTitle(title);
controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
}
AccessibilityMode InterstitialPageImpl::GetAccessibilityMode() const {
if (web_contents_)
return static_cast<WebContentsImpl*>(web_contents_)->GetAccessibilityMode();
else
return AccessibilityModeOff;
}
RenderViewHostDelegateView* InterstitialPageImpl::GetDelegateView() {
return rvh_delegate_view_.get();
}
const GURL& InterstitialPageImpl::GetMainFrameLastCommittedURL() const {
return url_;
}
void InterstitialPageImpl::RenderViewTerminated(
RenderViewHost* render_view_host,
base::TerminationStatus status,
int error_code) {
// Our renderer died. This should not happen in normal cases.
// If we haven't already started shutdown, just dismiss the interstitial.
// We cannot check for enabled() here, because we may have called Disable
// without calling Hide.
if (render_view_host_)
DontProceed();
}
void InterstitialPageImpl::DidNavigate(
RenderViewHost* render_view_host,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
// A fast user could have navigated away from the page that triggered the
// interstitial while the interstitial was loading, that would have disabled
// us. In that case we can dismiss ourselves.
if (!enabled()) {
DontProceed();
return;
}
if (ui::PageTransitionCoreTypeIs(params.transition,
ui::PAGE_TRANSITION_AUTO_SUBFRAME)) {
// No need to handle navigate message from iframe in the interstitial page.
return;
}
// The RenderViewHost has loaded its contents, we can show it now.
if (!controller_->delegate()->IsHidden())
render_view_host_->GetView()->Show();
controller_->delegate()->AttachInterstitialPage(this);
RenderWidgetHostView* rwh_view =
controller_->delegate()->GetRenderViewHost()->GetView();
// The RenderViewHost may already have crashed before we even get here.
if (rwh_view) {
// If the page has focus, focus the interstitial.
if (rwh_view->HasFocus())
Focus();
// Hide the original RVH since we're showing the interstitial instead.
rwh_view->Hide();
}
// Notify the tab we are not loading so the throbber is stopped. It also
// causes a WebContentsObserver::DidStopLoading callback that the
// AutomationProvider (used by the UI tests) expects to consider a navigation
// as complete. Without this, navigating in a UI test to a URL that triggers
// an interstitial would hang.
web_contents_was_loading_ = controller_->delegate()->IsLoading();
controller_->delegate()->SetIsLoading(false, true, NULL);
}
RendererPreferences InterstitialPageImpl::GetRendererPrefs(
BrowserContext* browser_context) const {
delegate_->OverrideRendererPrefs(&renderer_preferences_);
return renderer_preferences_;
}
void InterstitialPageImpl::RenderWidgetDeleted(
RenderWidgetHostImpl* render_widget_host) {
// TODO(creis): Remove this method once we verify the shutdown path is sane.
CHECK(!web_contents_);
}
bool InterstitialPageImpl::PreHandleKeyboardEvent(
const NativeWebKeyboardEvent& event,
bool* is_keyboard_shortcut) {
if (!enabled())
return false;
return render_widget_host_delegate_->PreHandleKeyboardEvent(
event, is_keyboard_shortcut);
}
void InterstitialPageImpl::HandleKeyboardEvent(
const NativeWebKeyboardEvent& event) {
if (enabled())
render_widget_host_delegate_->HandleKeyboardEvent(event);
}
#if defined(OS_WIN)
gfx::NativeViewAccessible
InterstitialPageImpl::GetParentNativeViewAccessible() {
if (web_contents_) {
WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents_);
return wci->GetParentNativeViewAccessible();
}
return NULL;
}
#endif
WebContents* InterstitialPageImpl::web_contents() const {
return web_contents_;
}
RenderViewHostImpl* InterstitialPageImpl::CreateRenderViewHost() {
if (!enabled())
return NULL;
// Interstitial pages don't want to share the session storage so we mint a
// new one.
BrowserContext* browser_context = web_contents()->GetBrowserContext();
scoped_refptr<SiteInstance> site_instance =
SiteInstance::Create(browser_context);
DOMStorageContextWrapper* dom_storage_context =
static_cast<DOMStorageContextWrapper*>(
BrowserContext::GetStoragePartition(
browser_context, site_instance.get())->GetDOMStorageContext());
session_storage_namespace_ =
new SessionStorageNamespaceImpl(dom_storage_context);
// Use the RenderViewHost from our FrameTree.
frame_tree_.root()->render_manager()->Init(
browser_context, site_instance.get(), MSG_ROUTING_NONE, MSG_ROUTING_NONE);
return frame_tree_.root()->current_frame_host()->render_view_host();
}
WebContentsView* InterstitialPageImpl::CreateWebContentsView() {
if (!enabled() || !create_view_)
return NULL;
WebContentsView* wcv =
static_cast<WebContentsImpl*>(web_contents())->GetView();
RenderWidgetHostViewBase* view =
wcv->CreateViewForWidget(render_view_host_, false);
render_view_host_->SetView(view);
render_view_host_->AllowBindings(BINDINGS_POLICY_DOM_AUTOMATION);
int32 max_page_id = web_contents()->
GetMaxPageIDForSiteInstance(render_view_host_->GetSiteInstance());
render_view_host_->CreateRenderView(base::string16(),
MSG_ROUTING_NONE,
MSG_ROUTING_NONE,
max_page_id,
false);
controller_->delegate()->RenderFrameForInterstitialPageCreated(
frame_tree_.root()->current_frame_host());
view->SetSize(web_contents()->GetContainerBounds().size());
// Don't show the interstitial until we have navigated to it.
view->Hide();
return wcv;
}
void InterstitialPageImpl::Proceed() {
// Don't repeat this if we are already shutting down. We cannot check for
// enabled() here, because we may have called Disable without calling Hide.
if (!render_view_host_)
return;
if (action_taken_ != NO_ACTION) {
NOTREACHED();
return;
}
Disable();
action_taken_ = PROCEED_ACTION;
// Resumes the throbber, if applicable.
if (web_contents_was_loading_)
controller_->delegate()->SetIsLoading(true, true, NULL);
// If this is a new navigation, the old page is going away, so we cancel any
// blocked requests for it. If it is not a new navigation, then it means the
// interstitial was shown as a result of a resource loading in the page.
// Since the user wants to proceed, we'll let any blocked request go through.
if (new_navigation_)
TakeActionOnResourceDispatcher(CANCEL);
else
TakeActionOnResourceDispatcher(RESUME);
// No need to hide if we are a new navigation, we'll get hidden when the
// navigation is committed.
if (!new_navigation_) {
Hide();
delegate_->OnProceed();
return;
}
delegate_->OnProceed();
}
void InterstitialPageImpl::DontProceed() {
// Don't repeat this if we are already shutting down. We cannot check for
// enabled() here, because we may have called Disable without calling Hide.
if (!render_view_host_)
return;
DCHECK(action_taken_ != DONT_PROCEED_ACTION);
Disable();
action_taken_ = DONT_PROCEED_ACTION;
// If this is a new navigation, we are returning to the original page, so we
// resume blocked requests for it. If it is not a new navigation, then it
// means the interstitial was shown as a result of a resource loading in the
// page and we won't return to the original page, so we cancel blocked
// requests in that case.
if (new_navigation_)
TakeActionOnResourceDispatcher(RESUME);
else
TakeActionOnResourceDispatcher(CANCEL);
if (should_discard_pending_nav_entry_) {
// Since no navigation happens we have to discard the transient entry
// explicitely. Note that by calling DiscardNonCommittedEntries() we also
// discard the pending entry, which is what we want, since the navigation is
// cancelled.
controller_->DiscardNonCommittedEntries();
}
if (reload_on_dont_proceed_)
controller_->Reload(true);
Hide();
delegate_->OnDontProceed();
}
void InterstitialPageImpl::CancelForNavigation() {
// The user is trying to navigate away. We should unblock the renderer and
// disable the interstitial, but keep it visible until the navigation
// completes.
Disable();
// If this interstitial was shown for a new navigation, allow any navigations
// on the original page to resume (e.g., subresource requests, XHRs, etc).
// Otherwise, cancel the pending, possibly dangerous navigations.
if (new_navigation_)
TakeActionOnResourceDispatcher(RESUME);
else
TakeActionOnResourceDispatcher(CANCEL);
}
void InterstitialPageImpl::SetSize(const gfx::Size& size) {
if (!enabled())
return;
#if !defined(OS_MACOSX)
// When a tab is closed, we might be resized after our view was NULLed
// (typically if there was an info-bar).
if (render_view_host_->GetView())
render_view_host_->GetView()->SetSize(size);
#else
// TODO(port): Does Mac need to SetSize?
NOTIMPLEMENTED();
#endif
}
void InterstitialPageImpl::Focus() {
// Focus the native window.
if (!enabled())
return;
render_view_host_->GetView()->Focus();
}
void InterstitialPageImpl::FocusThroughTabTraversal(bool reverse) {
if (!enabled())
return;
render_view_host_->SetInitialFocus(reverse);
}
RenderWidgetHostView* InterstitialPageImpl::GetView() {
return render_view_host_->GetView();
}
RenderFrameHost* InterstitialPageImpl::GetMainFrame() const {
return render_view_host_->GetMainFrame();
}
InterstitialPageDelegate* InterstitialPageImpl::GetDelegateForTesting() {
return delegate_.get();
}
void InterstitialPageImpl::DontCreateViewForTesting() {
create_view_ = false;
}
gfx::Rect InterstitialPageImpl::GetRootWindowResizerRect() const {
return gfx::Rect();
}
void InterstitialPageImpl::CreateNewWindow(
int render_process_id,
int route_id,
int main_frame_route_id,
const ViewHostMsg_CreateWindow_Params& params,
SessionStorageNamespace* session_storage_namespace) {
NOTREACHED() << "InterstitialPage does not support showing popups yet.";
}
void InterstitialPageImpl::CreateNewWidget(int render_process_id,
int route_id,
blink::WebPopupType popup_type) {
NOTREACHED() << "InterstitialPage does not support showing drop-downs yet.";
}
void InterstitialPageImpl::CreateNewFullscreenWidget(int render_process_id,
int route_id) {
NOTREACHED()
<< "InterstitialPage does not support showing full screen popups.";
}
void InterstitialPageImpl::ShowCreatedWindow(int route_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture) {
NOTREACHED() << "InterstitialPage does not support showing popups yet.";
}
void InterstitialPageImpl::ShowCreatedWidget(int route_id,
const gfx::Rect& initial_rect) {
NOTREACHED() << "InterstitialPage does not support showing drop-downs yet.";
}
void InterstitialPageImpl::ShowCreatedFullscreenWidget(int route_id) {
NOTREACHED()
<< "InterstitialPage does not support showing full screen popups.";
}
SessionStorageNamespace* InterstitialPageImpl::GetSessionStorageNamespace(
SiteInstance* instance) {
return session_storage_namespace_.get();
}
FrameTree* InterstitialPageImpl::GetFrameTree() {
return &frame_tree_;
}
void InterstitialPageImpl::Disable() {
enabled_ = false;
}
void InterstitialPageImpl::Shutdown() {
delete this;
}
void InterstitialPageImpl::OnNavigatingAwayOrTabClosing() {
if (action_taken_ == NO_ACTION) {
// We are navigating away from the interstitial or closing a tab with an
// interstitial. Default to DontProceed(). We don't just call Hide as
// subclasses will almost certainly override DontProceed to do some work
// (ex: close pending connections).
DontProceed();
} else {
// User decided to proceed and either the navigation was committed or
// the tab was closed before that.
Hide();
}
}
void InterstitialPageImpl::TakeActionOnResourceDispatcher(
ResourceRequestAction action) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (action == CANCEL || action == RESUME) {
if (resource_dispatcher_host_notified_)
return;
resource_dispatcher_host_notified_ = true;
}
// The tab might not have a render_view_host if it was closed (in which case,
// we have taken care of the blocked requests when processing
// NOTIFY_RENDER_WIDGET_HOST_DESTROYED.
// Also we need to test there is a ResourceDispatcherHostImpl, as when unit-
// tests we don't have one.
RenderViewHostImpl* rvh = RenderViewHostImpl::FromID(original_child_id_,
original_rvh_id_);
if (!rvh || !ResourceDispatcherHostImpl::Get())
return;
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(
&ResourceRequestHelper,
ResourceDispatcherHostImpl::Get(),
original_child_id_,
original_rvh_id_,
action));
}
void InterstitialPageImpl::OnDomOperationResponse(
const std::string& json_string,
int automation_id) {
// Needed by test code.
DomOperationNotificationDetails details(json_string, automation_id);
NotificationService::current()->Notify(
NOTIFICATION_DOM_OPERATION_RESPONSE,
Source<WebContents>(web_contents()),
Details<DomOperationNotificationDetails>(&details));
if (!enabled())
return;
delegate_->CommandReceived(details.json);
}
InterstitialPageImpl::InterstitialPageRVHDelegateView::
InterstitialPageRVHDelegateView(InterstitialPageImpl* page)
: interstitial_page_(page) {
}
#if defined(OS_MACOSX) || defined(OS_ANDROID)
void InterstitialPageImpl::InterstitialPageRVHDelegateView::ShowPopupMenu(
RenderFrameHost* render_frame_host,
const gfx::Rect& bounds,
int item_height,
double item_font_size,
int selected_item,
const std::vector<MenuItem>& items,
bool right_aligned,
bool allow_multiple_selection) {
NOTREACHED() << "InterstitialPage does not support showing popup menus.";
}
void InterstitialPageImpl::InterstitialPageRVHDelegateView::HidePopupMenu() {
NOTREACHED() << "InterstitialPage does not support showing popup menus.";
}
#endif
void InterstitialPageImpl::InterstitialPageRVHDelegateView::StartDragging(
const DropData& drop_data,
WebDragOperationsMask allowed_operations,
const gfx::ImageSkia& image,
const gfx::Vector2d& image_offset,
const DragEventSourceInfo& event_info) {
interstitial_page_->render_view_host_->DragSourceSystemDragEnded();
DVLOG(1) << "InterstitialPage does not support dragging yet.";
}
void InterstitialPageImpl::InterstitialPageRVHDelegateView::UpdateDragCursor(
WebDragOperation) {
NOTREACHED() << "InterstitialPage does not support dragging yet.";
}
void InterstitialPageImpl::InterstitialPageRVHDelegateView::GotFocus() {
WebContents* web_contents = interstitial_page_->web_contents();
if (web_contents)
static_cast<WebContentsImpl*>(web_contents)->NotifyWebContentsFocused();
}
void InterstitialPageImpl::InterstitialPageRVHDelegateView::TakeFocus(
bool reverse) {
if (!interstitial_page_->web_contents())
return;
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(interstitial_page_->web_contents());
if (!web_contents->GetDelegateView())
return;
web_contents->GetDelegateView()->TakeFocus(reverse);
}
void InterstitialPageImpl::InterstitialPageRVHDelegateView::OnFindReply(
int request_id, int number_of_matches, const gfx::Rect& selection_rect,
int active_match_ordinal, bool final_update) {
}
<|fim▁hole|> : WebContentsObserver(web_contents), interstitial_(interstitial) {
}
void InterstitialPageImpl::UnderlyingContentObserver::NavigationEntryCommitted(
const LoadCommittedDetails& load_details) {
interstitial_->OnNavigatingAwayOrTabClosing();
}
void InterstitialPageImpl::UnderlyingContentObserver::WebContentsDestroyed() {
interstitial_->OnNavigatingAwayOrTabClosing();
}
} // namespace content<|fim▁end|> | InterstitialPageImpl::UnderlyingContentObserver::UnderlyingContentObserver(
WebContents* web_contents,
InterstitialPageImpl* interstitial) |
<|file_name|>suite_teardown.py<|end_file_name|><|fim▁begin|>'''
Integration Test Teardown case
@author: Youyk
'''
import zstacklib.utils.linux as linux
import zstacklib.utils.http as http
import zstackwoodpecker.setup_actions as setup_actions
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.clean_util as clean_util
import zstackwoodpecker.test_lib as test_lib
import zstacktestagent.plugins.host as host_plugin
import zstacktestagent.testagent as testagent
def test():
clean_util.cleanup_all_vms_violently()
clean_util.cleanup_none_vm_volumes_violently()
clean_util.umount_all_primary_storages_violently()
clean_util.cleanup_backup_storage()
#linux.remove_vlan_eth("eth0", 10)
#linux.remove_vlan_eth("eth0", 11)
cmd = host_plugin.DeleteVlanDeviceCmd()
cmd.vlan_ethname = 'eth0.10'
hosts = test_lib.lib_get_all_hosts_from_plan()
if type(hosts) != type([]):
hosts = [hosts]
for host in hosts:
http.json_dump_post(testagent.build_http_path(host.managementIp_, host_plugin.DELETE_VLAN_DEVICE_PATH), cmd)
cmd.vlan_ethname = 'eth0.11'
for host in hosts:<|fim▁hole|> test_lib.setup_plan.stop_node()
test_lib.lib_cleanup_host_ip_dict()
test_util.test_pass('VPC Teardown Success')<|fim▁end|> | http.json_dump_post(testagent.build_http_path(host.managementIp_, host_plugin.DELETE_VLAN_DEVICE_PATH), cmd)
|
<|file_name|>plot-util.ts<|end_file_name|><|fim▁begin|>/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {isNullOrUndefined, toNumber} from '../../../../../shared/utils/common.utils';
export function createRange(values: number[]): [number, number] {
let min = null;
let max = null;
values.forEach(value => {
const numberValue = toNumber(value);
if (isNullOrUndefined(min) || min > numberValue) {
min = numberValue;
}
if (isNullOrUndefined(max) || max < numberValue) {<|fim▁hole|>
if (isNullOrUndefined(min) || isNullOrUndefined(max)) {
return null;
}
const range = Math.abs(max - min);
const step = Math.log10(range) * 10;
const bottomRange = min < 0 ? Math.min(min * 1.1, min - step) : Math.min(min * 0.9, min - step);
const upperRange = max < 0 ? Math.max(max * 0.9, max + step) : Math.max(max * 1.1, max + step);
return [bottomRange, upperRange];
}<|fim▁end|> | max = numberValue;
}
}); |
<|file_name|>unmount_linux.go<|end_file_name|><|fim▁begin|>package bazilfuse
import (
"bytes"
"errors"
"os/exec"
)
func unmount(dir string) error {
cmd := exec.Command("fusermount", "-u", dir)
output, err := cmd.CombinedOutput()<|fim▁hole|> if err != nil {
if len(output) > 0 {
output = bytes.TrimRight(output, "\n")
msg := err.Error() + ": " + string(output)
err = errors.New(msg)
}
return err
}
return nil
}<|fim▁end|> | |
<|file_name|>sync_provider.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation of SyncProvider.
use std::collections::BTreeMap;
use bigint::hash::H256;<|fim▁hole|>pub struct Config {
/// Protocol version.
pub network_id: u64,
/// Number of peers.
pub num_peers: usize,
}
/// Test sync provider.
pub struct TestSyncProvider {
/// Sync status.
pub status: RwLock<SyncStatus>,
}
impl TestSyncProvider {
/// Creates new sync provider.
pub fn new(config: Config) -> Self {
TestSyncProvider {
status: RwLock::new(SyncStatus {
state: SyncState::Idle,
network_id: config.network_id,
protocol_version: 63,
start_block_number: 0,
last_imported_block_number: None,
highest_block_number: None,
blocks_total: 0,
blocks_received: 0,
num_peers: config.num_peers,
num_active_peers: 0,
mem_used: 0,
num_snapshot_chunks: 0,
snapshot_chunks_done: 0,
last_imported_old_block_number: None,
}),
}
}
/// Simulate importing blocks.
pub fn increase_imported_block_number(&self, count: u64) {
let mut status = self.status.write();
let current_number = status.last_imported_block_number.unwrap_or(0);
status.last_imported_block_number = Some(current_number + count);
}
}
impl SyncProvider for TestSyncProvider {
fn status(&self) -> SyncStatus {
self.status.read().clone()
}
fn peers(&self) -> Vec<PeerInfo> {
vec![
PeerInfo {
id: Some("node1".to_owned()),
client_version: "Parity/1".to_owned(),
capabilities: vec!["eth/62".to_owned(), "eth/63".to_owned()],
remote_address: "127.0.0.1:7777".to_owned(),
local_address: "127.0.0.1:8888".to_owned(),
eth_info: Some(EthProtocolInfo {
version: 62,
difficulty: Some(40.into()),
head: 50.into(),
}),
pip_info: None,
},
PeerInfo {
id: None,
client_version: "Parity/2".to_owned(),
capabilities: vec!["eth/63".to_owned(), "eth/64".to_owned()],
remote_address: "Handshake".to_owned(),
local_address: "127.0.0.1:3333".to_owned(),
eth_info: Some(EthProtocolInfo {
version: 64,
difficulty: None,
head: 60.into()
}),
pip_info: None,
}
]
}
fn enode(&self) -> Option<String> {
None
}
fn transactions_stats(&self) -> BTreeMap<H256, TransactionStats> {
map![
1.into() => TransactionStats {
first_seen: 10,
propagated_to: map![
128.into() => 16
],
},
5.into() => TransactionStats {
first_seen: 16,
propagated_to: map![
16.into() => 1
],
}
]
}
}<|fim▁end|> | use parking_lot::RwLock;
use ethsync::{SyncProvider, EthProtocolInfo, SyncStatus, SyncState, PeerInfo, TransactionStats};
/// TestSyncProvider config. |
<|file_name|>editMapTestScene.py<|end_file_name|><|fim▁begin|>import os
import os.path
import sys
import pygame
from buffalo import utils
from buffalo.scene import Scene
from buffalo.label import Label
from buffalo.button import Button
from buffalo.input import Input
from buffalo.tray import Tray
from camera import Camera
from mapManager import MapManager
from pluginManager import PluginManager
from toolManager import ToolManager
class CameraController:
def __init__(self):
self.fPos = (0.0, 0.0)
self.pos = (int(self.fPos[0]), int(self.fPos[1]))
self.xv, self.yv = 0.0, 0.0
self.speed = 1.2
self.shift_speed = self.speed * 5.0
def update(self, keys):
w, a, s, d, shift = (
keys[pygame.K_w],
keys[pygame.K_a],
keys[pygame.K_s],
keys[pygame.K_d],
keys[pygame.K_LSHIFT],
)
if shift:
speed = self.shift_speed
else:
speed = self.speed
speed *= utils.delta / 16.0
self.xv = 0.0
self.yv = 0.0
if w:
self.yv -= speed
if a:
self.xv -= speed
if s:
self.yv += speed
if d:
self.xv += speed
x, y = self.fPos
x += self.xv
y += self.yv
self.fPos = x, y
self.pos = (int(self.fPos[0]), int(self.fPos[1]))
class EditMapTestScene(Scene):
def on_escape(self):
sys.exit()
def blit(self):
Camera.blitView()
def update(self):
super(EditMapTestScene, self).update()
keys = pygame.key.get_pressed()
self.camera_controller.update(keys)
Camera.update()
MapManager.soft_load_writer()
def __init__(self):
Scene.__init__(self)
self.BACKGROUND_COLOR = (0, 0, 0, 255)
PluginManager.loadPlugins()
self.camera_controller = CameraController()
Camera.lock(self.camera_controller, initial_update=True)
Button.DEFAULT_SEL_COLOR = (50, 50, 100, 255)
self.tool_tray = Tray(
(utils.SCREEN_W - 270, 20),
(250, 800),
min_width=250, max_width=250,
min_height=250, max_height=800,
color=(100, 50, 50, 100),
)
self.tool_tray.labels.add(
Label(
(int(self.tool_tray.width / 2), 10),
"Tool Tray",
color=(255,255,255,255),
x_centered=True,
font="default24",
)
)
self.tool_tray.labels.add(
Label(
(int(self.tool_tray.width / 2), 25),
"________________",
color=(255,255,255,255),
x_centered=True,
font="default18",
)
)
self.tool_tray.labels.add(
Label(
(int(self.tool_tray.width / 2), 50),
"Function",
color=(255,255,255,255),
x_centered=True,
font="default18",
)
)
def set_func_state_to_select():
ToolManager.set_func_state(ToolManager.FUNC_SELECT)
self.tool_tray.render()
self.button_select_mode = Button(
(15, 80),
" Select Mode ",
color=(255,255,255,255),
bg_color=(100,100,200,255),
font="default12",
func=set_func_state_to_select,
)
self.tool_tray.buttons.add(self.button_select_mode)
def set_func_state_to_fill():
ToolManager.set_func_state(ToolManager.FUNC_FILL)
self.tool_tray.render()
self.button_fill_mode = Button(
(self.tool_tray.width - 15, 80),
" Fill Mode ",
color=(255,255,255,255),
bg_color=(100,100,200,255),
invert_x_pos=True,
font="default12",
func=set_func_state_to_fill,
)
self.tool_tray.buttons.add(self.button_fill_mode)
self.tool_tray.labels.add(
Label(
(int(self.tool_tray.width / 2), 120),
"________________",
color=(255,255,255,255),
x_centered=True,
font="default18",
)
)
self.tool_tray.labels.add(
Label(
(int(self.tool_tray.width / 2), 150),
"Area of Effect",
color=(255,255,255,255),
x_centered=True,
font="default18",
)
)
def set_effect_state_to_draw():
ToolManager.set_effect_state(ToolManager.EFFECT_DRAW)
self.tool_tray.render()
self.button_draw_mode = Button(
(15, 180),
" Draw Mode ",
color=(255,255,255,255),
bg_color=(100,100,200,255),
font="default12",
func=set_effect_state_to_draw,
)
self.tool_tray.buttons.add(self.button_draw_mode)
def set_effect_state_to_area():
ToolManager.set_effect_state(ToolManager.EFFECT_AREA)
self.tool_tray.render()
self.button_area_mode = Button(
(self.tool_tray.width - 15, 180),
" Area Mode ",
color=(255,255,255,255),
bg_color=(100,100,200,255),
invert_x_pos=True,
font="default12",
func=set_effect_state_to_area,
)
self.tool_tray.buttons.add(self.button_area_mode)
ToolManager.initialize_states(
ToolManager.FUNC_SELECT, ToolManager.EFFECT_DRAW,
(
self.button_fill_mode,
self.button_select_mode,
self.button_draw_mode,
self.button_area_mode,<|fim▁hole|> self.trays.add(self.tool_tray)<|fim▁end|> | ),
)
self.tool_tray.render() |
<|file_name|>core.module.ts<|end_file_name|><|fim▁begin|>'use strict';
namespace dogsrus.virtdog {
(() => {
angular.module('app.core', [
/*
* Angular modules
*/
'ngRoute'
/*
* Our reusable cross app code modules
*/
// exception service, logger service
/*
* 3rd Party modules
*/
]);
})();
export function getModuleCore(): ng.IModule {
return angular.module('app.core');<|fim▁hole|><|fim▁end|> | }
} |
<|file_name|>BaseController__query_values.go<|end_file_name|><|fim▁begin|>package controllers
import (
"net/url"
"strconv"
"strings"
)
func (this *BaseController) GetOptionalQueryValueBoolean(queryKey string, defaultVal bool) (hadQueryValue bool, boolVal bool) {
escapedQueryValue := this.Ctx.Input.Query(queryKey)
if escapedQueryValue == "" {
return false, defaultVal
}
unescapedQueryValue, err := url.QueryUnescape(escapedQueryValue)
this.PanicIfError(err)
unescapedQueryValue = strings.ToLower(strings.Trim(unescapedQueryValue, " "))
if unescapedQueryValue != "true" && unescapedQueryValue != "1" &&
unescapedQueryValue != "false" && unescapedQueryValue != "0" {
panic("Unsupported value for Boolean query key: " + unescapedQueryValue)
}
return true, (unescapedQueryValue == "true" || unescapedQueryValue == "1")
}
func (this *BaseController) GetRequiredQueryValueBoolean(queryKey string) bool {
hadVal, boolVal := this.GetOptionalQueryValueBoolean(queryKey, false)
if !hadVal {
panic("Required query key is empty/missing: " + queryKey)
}
return boolVal
}
<|fim▁hole|> }
unescapedQueryValue, err := url.QueryUnescape(escapedQueryValue)
this.PanicIfError(err)
return true, unescapedQueryValue
}
func (this *BaseController) GetRequiredQueryValueString(queryKey string) string {
hadVal, unescapedQueryValue := this.GetOptionalQueryValueString(queryKey, "")
if !hadVal {
panic("Required query key is empty/missing: " + queryKey)
}
return unescapedQueryValue
}
func (this *BaseController) GetOptionalQueryInt64(queryName string, defaultVal int64) (bool, int64) {
escapedQuery := this.Ctx.Input.Query(queryName)
if escapedQuery == "" {
return false, defaultVal
}
unescapedQuery, err := url.QueryUnescape(escapedQuery)
this.PanicIfError(err)
intVal, err := strconv.ParseInt(unescapedQuery, 10, 64)
this.PanicIfError(err)
return true, intVal
}
func (this *BaseController) GetRequiredQueryInt64(queryName string) int64 {
hadVal, int64Val := this.GetOptionalQueryInt64(queryName, -1)
if !hadVal {
panic("Required query is empty/missing: " + queryName)
}
return int64Val
}
func (this *BaseController) GetOptionalQueryInt64CsvArray(queryName string, defaultVal []int64) (bool, []int64) {
escapedQuery := this.Ctx.Input.Query(queryName)
if escapedQuery == "" {
return false, defaultVal
}
unescapedQuery, err := url.QueryUnescape(escapedQuery)
this.PanicIfError(err)
intSlice := []int64{}
intStrings := strings.Split(unescapedQuery, ",")
for _, intStr := range intStrings {
intVal, err := strconv.ParseInt(intStr, 10, 64)
this.PanicIfError(err)
intSlice = append(intSlice, intVal)
}
return true, intSlice
}
func (this *BaseController) GetRequiredQueryInt64CsvArray(queryName string) []int64 {
hadVal, int64Slice := this.GetOptionalQueryInt64CsvArray(queryName, []int64{})
if !hadVal {
panic("Required query is empty/missing: " + queryName)
}
return int64Slice
}<|fim▁end|> | func (this *BaseController) GetOptionalQueryValueString(queryKey, defaultVal string) (bool, string) {
escapedQueryValue := this.Ctx.Input.Query(queryKey)
if escapedQueryValue == "" {
return false, defaultVal |
<|file_name|>pie.rs<|end_file_name|><|fim▁begin|>use std::f32::consts;
use graph::{Graph, Tools, Coord, Padding, HTML, Size};
use entry::Entry;
pub struct PieBuilder {
width: f32,
height: f32,
entries: Option<Vec<Entry>>,
}
impl PieBuilder {
pub fn new() -> PieBuilder {
PieBuilder {
width: 500.0,
height: 500.0,
entries: None,
}
}
pub fn width(mut self, width: f32) -> PieBuilder {
self.width = width;
self
}
pub fn height(mut self, height: f32) -> PieBuilder {
self.height = height;
self
}
pub fn entries(mut self, entries: Vec<Entry>) -> PieBuilder {
self.entries = Some(entries);
self
}
pub fn build(self) -> Pie {
let padding = Padding::with_same(15.0);
let Padding { top, right, bottom, left } = padding;
let (width, height) = (self.width, self.height);
let entries = match self.entries {
Some(e) => e,
None => Vec::with_capacity(0),
};
let label_width = 100.0; // TODO: calculate dynamically
let label_padding_left = 20.0;
let label_padding_top = 30.0;
let body = Coord {
x: left,
y: top,
width: width - label_width - label_padding_left - left - right,
height: height - top - bottom,
};
let labels_body = Coord {
x: body.x + body.width + label_padding_left,
y: top + label_padding_top,
width: label_width,
height: body.height - label_padding_top,
};
Pie {
size: Size { width: width, height: height },
body: body,
labels_body: labels_body,
sum: entries
.iter()
.fold(0, |acc, e| acc + e.value),
entries: entries,
}
}
}
pub struct Pie {
size: Size,
entries: Vec<Entry>,
labels_body: Coord,
body: Coord,
sum: i32,
}
impl Pie {
fn angle(&self, v: i32) -> f32 {
(v as f32) / (self.sum as f32) * 2.0 * consts::PI
}
fn color(i: usize) -> String {
let colors = vec![
//"rgba(0,0,0,0.5)",
//"rgba(0,94,255,0.5)",
//"rgba(255,165,0,0.5)",
//"rgba(10,199,0,0.5)",
//"rgba(220,232,0,0.5)",
//"rgba(232,0,162,0.5)"
//
"rgb(237,10,63)",
"rgb(231,114,0)",
"rgb(254,216,93)",
"rgb(1,120,111)",
"rgb(165,7,44)",
"rgb(243,184,127)",
"rgb(66,75,77)",
"rgb(203,172,74)",
"rgb(153,201,197)",
"rgb(129,135,136)",<|fim▁hole|> Pie::color(i - colors.len())
} else {
colors[i].to_string()
}
}
fn arcs(&self) -> Vec<Arc> {
let r = if self.body.height > self.body.width {
self.body.width / 2.0
} else {
self.body.height / 2.0
};
let text_r = r * 0.85;
let mut prev_angle = 0.0;
self.entries
.iter()
.enumerate()
.map(|(i, e)| {
let d_angle = self.angle(e.value);
let next_angle = prev_angle + d_angle;
let a = (-r * prev_angle.cos(), r * prev_angle.sin());
let b = (-r * next_angle.cos(), r * next_angle.sin());
let text_angle = prev_angle + (d_angle / 2.0);
let (text_x, text_y) = (
-text_r * text_angle.cos(),
text_r * text_angle.sin()
);
prev_angle = next_angle;
let text = format!("{} ({})", e.label, e.value);
Arc {
path: format!("M{},{}A{},{},0,0,0,{},{}L0,0Z", a.0, a.1, r, r, b.0, b.1),
fill: Pie::color(i),
text_dx: -(text.len() as f32 * 2.0),
text: text,
text_x: text_x,
text_y: text_y,
}
})
.collect()
}
fn labels(&self) -> Vec<Label> {
self.entries
.iter()
.enumerate()
.map(|(i, e)| {
Label {
fill: Pie::color(i),
text: e.label.clone(),
x: 0.0,
y: (i as f32) * 20.0,
}
})
.collect()
}
}
impl Graph for Pie {
fn into_html(&self) -> HTML {
let center = self.body.center();
let labels = self.labels();
let arcs = self.arcs();
html! {
svg width=(self.size.width) height=(self.size.height) xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" {
g.labels transform=(Tools::tr(self.labels_body.x, self.labels_body.y)) {
@for Label { fill, text, x, y } in labels {
g.label transform=(Tools::tr(x, y)) {
rect fill=(fill) x="0" y="-11" width="12" height="12" {}
text anchor="start" dx="18" (text)
}
}
}
g.content transform=(Tools::tr(center.0, center.1)) {
@for Arc { path, fill, text, text_x, text_y, text_dx } in arcs {
g.arc {
path stroke="rgba(245,245,245,0.8)" fill=(fill) d=(path) {}
text transform=(Tools::tr(text_x, text_y)) dx=(text_dx) anchor="middle" (text)
}
}
}
}
}
}
}
struct Arc {
path: String,
fill: String,
text: String,
text_x: f32,
text_y: f32,
text_dx: f32,
}
struct Label {
fill: String,
text: String,
x: f32,
y: f32,
}<|fim▁end|> | ];
if i >= colors.len() { |
<|file_name|>background_datastore.rs<|end_file_name|><|fim▁begin|>use rand;
use rand::distributions::*;
use structures;
use constants::*;
use GameUpdateArgs;
pub struct BackgroundDatastore<'a>
{
buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT],
instance_data: &'a mut [u32; MAX_BK_COUNT]
}
impl <'a> BackgroundDatastore<'a>
{
pub fn new(buffer_data_ref: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data_ref: &'a mut [u32; MAX_BK_COUNT]) -> Self
{
BackgroundDatastore
{
buffer_data: buffer_data_ref,
instance_data: instance_data_ref
}
}
pub fn update(&mut self, update_args: &mut GameUpdateArgs, appear: bool)
{
let mut require_appear = appear;
let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32);
let mut count_range = rand::distributions::Range::new(2, 10);
let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32);
for (i, m) in self.instance_data.iter_mut().enumerate()
{
if *m == 0
{
// instantiate randomly
if require_appear
{
let scale = scale_range.sample(&mut update_args.randomizer);
*m = 1;
self.buffer_data[i].offset = [left_range.sample(&mut update_args.randomizer), -20.0f32, -20.0f32,
count_range.sample(&mut update_args.randomizer) as f32];<|fim▁hole|> require_appear = false;
}
}
else
{
self.buffer_data[i].offset[1] += update_args.delta_time * 22.0f32;
*m = if self.buffer_data[i].offset[1] >= 20.0f32 { 0 } else { 1 };
}
}
}
}<|fim▁end|> | self.buffer_data[i].scale = [scale, scale, 1.0f32, 1.0f32]; |
<|file_name|>_ualib_imageCarousel.js<|end_file_name|><|fim▁begin|>angular.module('ualib.imageCarousel', ['angular-carousel'])
.constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active')
.factory('imageCarouselFactory', ['$http', 'VIEW_IMAGES_URL', function imageCarouselFactory($http, url){
return {
getData: function(){
return $http({method: 'GET', url: url, params: {}});
}
};
}])
.controller('imageCarouselCtrl', ['$scope', '$q', 'imageCarouselFactory',
function imageCarouselCtrl($scope, $q, imageCarouselFactory){
$scope.slides = null;
function loadImages(slides, i, len, deferred){
i = i ? i : 0;
len = len ? len : slides.length;
deferred = deferred ? deferred : $q.defer();
if (len < 1){
deferred.resolve(slides);
}
else{
var image = new Image();
image.onload = function(){
slides[i].styles = 'url('+this.src+')';
slides[i].image = this;
if (i+1 === len){
deferred.resolve(slides);
}
else {
i++;
loadImages(slides, i, len, deferred);
}
};
image.src = slides[i].image;
}
return deferred.promise;
}
imageCarouselFactory.getData()
.success(function(data) {
loadImages(data.slides).then(function(slides){
$scope.slides = slides;
});
})
.error(function(data, status, headers, config) {
console.log(data);
});
}])
.directive('ualibImageCarousel', [ function() {
return {
restrict: 'AC',
controller: 'imageCarouselCtrl',
link: function(scope, elm, attrs, Ctrl){
var toggleLock = false;
scope.isLocked = false;
scope.pause = function(){
toggleLock = true;
scope.isLocked = true;
};
scope.play = function(){
toggleLock = false;
scope.isLocked = false;
};
scope.mouseToggle = function(){
if (!toggleLock){
scope.isLocked = !scope.isLocked;
}
};
}<|fim▁hole|> };
}]);<|fim▁end|> | |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from math import sqrt
from datetime import datetime
from dexter.models import db, Document, Person
from sqlalchemy.sql import func<|fim▁hole|>
class BaseAnalyser(object):
"""
Base for analyser objects that handles a collection of
documents to analyse, based on either document ids
or start and end dates.
"""
TREND_UP = 0.5
TREND_DOWN = -0.5
def __init__(self, doc_ids=None, start_date=None, end_date=None):
self.doc_ids = doc_ids
self.start_date = start_date
self.end_date = end_date
# we need either a date range or document ids, fill in
# whichever is missing
self._calculate_date_range()
self._fetch_doc_ids()
self.n_documents = len(self.doc_ids)
def _calculate_date_range(self):
"""
The date range is the range of publication dates for the given
documents.
"""
if not self.start_date or not self.end_date:
if self.doc_ids is None:
raise ValueError("Need either doc_ids, or both start_date and end_date")
row = db.session.query(
func.min(Document.published_at),
func.max(Document.published_at))\
.filter(Document.id.in_(self.doc_ids))\
.first()
if row and row[0]:
self.start_date = row[0].date()
self.end_date = row[1].date()
else:
self.start_date = self.end_date = datetime.utcnow()
self.days = max((self.end_date - self.start_date).days, 1)
def _fetch_doc_ids(self):
if self.doc_ids is None:
rows = db.session.query(Document.id)\
.filter(Document.published_at >= self.start_date.strftime('%Y-%m-%d 00:00:00'))\
.filter(Document.published_at <= self.end_date.strftime('%Y-%m-%d 23:59:59'))\
.all()
self.doc_ids = [r[0] for r in rows]
def _lookup_people(self, ids):
query = Person.query \
.options(joinedload(Person.affiliation)) \
.filter(Person.id.in_(ids))
return dict([p.id, p] for p in query.all())
def moving_weighted_avg_zscore(obs, decay=0.8):
"""
Calculate a moving-weighted average z-score, based on +obs+,
a list of observations, and +decay+, the rate at which
observations decay.
See http://stackoverflow.com/questions/787496/what-is-the-best-way-to-compute-trending-topics-or-tags
See http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ewma.html#pandas.ewma
"""
avg = 0.0
sq_avg = 0.0
last = len(obs)-1
for i, x in enumerate(obs):
if i == 0:
# first item
avg = float(x)
sq_avg = float(x ** 2)
elif i == last:
# basic std deviation
std = sqrt(sq_avg - avg ** 2)
if std == 0:
return x - avg
else:
return (x - avg) / std
else:
# fold it in
avg = avg * decay + (1.0-decay) * x
sq_avg = sq_avg * decay + (1.0-decay) * (x ** 2)<|fim▁end|> | from sqlalchemy.orm import joinedload |
<|file_name|>tutorial03-curved_polys.py<|end_file_name|><|fim▁begin|>#!PYRTIST:VERSION:0:0:1
from pyrtist.lib2d import Point, Tri
#!PYRTIST:REFPOINTS:BEGIN
bbox1 = Point(0.0, 50.0); bbox2 = Point(100.0, 12.5838926174)
p1 = Point(3.15540458874, 46.942241204)
p2 = Point(3.23537580547, 42.1395946309)
p4 = Point(28.5119375629, 38.1285583893)
q1 = Point(73.1545885714, 21.8120805369)
q3 = Point(93.6244457143, 38.4228187919)
q5 = Point(66.4133738602, 33.8755592617)
q6 = Point(94.2249240122, 24.9089847651)
q7 = Point(84.8024316109, 26.7326948322)
q2 = Tri(q5, Point(70.1344457143, 37.2483221477))
q4 = Tri(q6, Point(90.4365171429, 20.1342281879), q7)
#!PYRTIST:REFPOINTS:END
# TUTORIAL EXAMPLE N.3
# How to create a closed figure using bezier curves.
from pyrtist.lib2d import *
w = Window()
s = " "
font = Font(2, "Helvetica")
w << Args(
Text(p1, font, Offset(0, 1), Color.red,
"Pyrtist allows creating curves (cubic Bezier splines)."
"\nThis example explains how."),
Text(p2, font, Offset(0, 1),
"STEP 1: launch Pyrtist or create a new document (CTRL+N)\n",
"STEP 2: click on the button to create a new curved polygon\n",
"STEP 3: move the mouse where you want to create the first vertex.\n",<|fim▁hole|> s, "key and the left mouse button, simultaneously. Keep them\n",
s, "pressed while moving the mouse out of the vertex. A round\n",
s, "reference point appears and the polygon edge is rounded.\n",
"STEP 6: you can repeat step 5 for the same vertex or for other\n",
s, "vertices. You should obtain something similar to what shown on\n",
s, "the left")
)
# The line below is what draws the curved polygon.
w << Curve(q1, q2, q3, q4)
w << Image("curve.png", p4, 2.5)
w << BBox(bbox1, bbox2)
gui(w)<|fim▁end|> | s, "Click on the left button of the mouse\n",
"STEP 4: repeat step 3 to create other 3 vertices. You should see\n",
s, "a black polygon with straight boundaries\n",
"STEP 5: move the mouse over one of the vertices. Press the CTRL\n", |
<|file_name|>SymbolLoader.java<|end_file_name|><|fim▁begin|>package oo.Prototype;
/*
* A Symbol Loader to register all prototype instance<|fim▁hole|>import java.util.*;
public class SymbolLoader {
private Hashtable symbols = new Hashtable();
public SymbolLoader() {
symbols.put("Line", new LineSymbol());
symbols.put("Note", new NoteSymbol());
}
public Hashtable getSymbols() {
return symbols;
}
}<|fim▁end|> | */ |
<|file_name|>foreign.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::{abi, link};
use llvm::{ValueRef, CallConv, get_param};
use llvm;
use middle::weak_lang_items;
use rustc::ast_map;
use trans::attributes;
use trans::base::{llvm_linkage_by_name, push_ctxt};
use trans::base;
use trans::build::*;
use trans::cabi;
use trans::common::*;
use trans::debuginfo::DebugLoc;
use trans::declare;
use trans::expr;
use trans::machine;
use trans::monomorphize;
use trans::type_::Type;
use trans::type_of::*;
use trans::type_of;
use middle::ty::{self, Ty};
use middle::subst::Substs;
use std::cmp;
use libc::c_uint;
use syntax::abi::{Cdecl, Aapcs, C, Win64, Abi};
use syntax::abi::{RustIntrinsic, Rust, RustCall, Stdcall, Fastcall, System};
use syntax::codemap::Span;
use syntax::parse::token::{InternedString, special_idents};
use syntax::ast;
use syntax::attr;
use syntax::print::pprust;
///////////////////////////////////////////////////////////////////////////
// Type definitions
struct ForeignTypes<'tcx> {
/// Rust signature of the function
fn_sig: ty::FnSig<'tcx>,
/// Adapter object for handling native ABI rules (trust me, you
/// don't want to know)
fn_ty: cabi::FnType,
/// LLVM types that will appear on the foreign function
llsig: LlvmSignature,
}
struct LlvmSignature {
// LLVM versions of the types of this function's arguments.
llarg_tys: Vec<Type> ,
// LLVM version of the type that this function returns. Note that
// this *may not be* the declared return type of the foreign
// function, because the foreign function may opt to return via an
// out pointer.
llret_ty: Type,
/// True if there is a return value (not bottom, not unit)
ret_def: bool,
}
///////////////////////////////////////////////////////////////////////////
// Calls to external functions
pub fn llvm_calling_convention(ccx: &CrateContext,
abi: Abi) -> CallConv {
match ccx.sess().target.target.adjust_abi(abi) {
RustIntrinsic => {
// Intrinsics are emitted at the call site
ccx.sess().bug("asked to register intrinsic fn");
}
Rust => {
// FIXME(#3678) Implement linking to foreign fns with Rust ABI
ccx.sess().unimpl("foreign functions with Rust ABI");
}
RustCall => {
// FIXME(#3678) Implement linking to foreign fns with Rust ABI
ccx.sess().unimpl("foreign functions with RustCall ABI");
}
// It's the ABI's job to select this, not us.
System => ccx.sess().bug("system abi should be selected elsewhere"),
Stdcall => llvm::X86StdcallCallConv,
Fastcall => llvm::X86FastcallCallConv,
C => llvm::CCallConv,
Win64 => llvm::X86_64_Win64,
// These API constants ought to be more specific...
Cdecl => llvm::CCallConv,
Aapcs => llvm::CCallConv,
}
}
pub fn register_static(ccx: &CrateContext,
foreign_item: &ast::ForeignItem) -> ValueRef {
let ty = ccx.tcx().node_id_to_type(foreign_item.id);
let llty = type_of::type_of(ccx, ty);
let ident = link_name(foreign_item);
match attr::first_attr_value_str_by_name(&foreign_item.attrs,
"linkage") {
// If this is a static with a linkage specified, then we need to handle
// it a little specially. The typesystem prevents things like &T and
// extern "C" fn() from being non-null, so we can't just declare a
// static and call it a day. Some linkages (like weak) will make it such
// that the static actually has a null value.
Some(name) => {
let linkage = match llvm_linkage_by_name(&name) {
Some(linkage) => linkage,
None => {
ccx.sess().span_fatal(foreign_item.span,
"invalid linkage specified");
}
};
let llty2 = match ty.sty {
ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
_ => {
ccx.sess().span_fatal(foreign_item.span,
"must have type `*T` or `*mut T`");
}
};
unsafe {
// Declare a symbol `foo` with the desired linkage.
let g1 = declare::declare_global(ccx, &ident[..], llty2);
llvm::SetLinkage(g1, linkage);
// Declare an internal global `extern_with_linkage_foo` which
// is initialized with the address of `foo`. If `foo` is
// discarded during linking (for example, if `foo` has weak
// linkage and there are no definitions), then
// `extern_with_linkage_foo` will instead be initialized to
// zero.
let mut real_name = "_rust_extern_with_linkage_".to_string();
real_name.push_str(&ident);
let g2 = declare::define_global(ccx, &real_name[..], llty).unwrap_or_else(||{
ccx.sess().span_fatal(foreign_item.span,
&format!("symbol `{}` is already defined", ident))
});
llvm::SetLinkage(g2, llvm::InternalLinkage);
llvm::LLVMSetInitializer(g2, g1);
g2
}
}
None => // Generate an external declaration.
declare::declare_global(ccx, &ident[..], llty),
}
}
// only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
pub fn get_extern_fn(ccx: &CrateContext,
externs: &mut ExternMap,
name: &str,
cc: llvm::CallConv,
ty: Type,
output: Ty)
-> ValueRef {
match externs.get(name) {
Some(n) => return *n,
None => {}
}
let f = declare::declare_fn(ccx, name, cc, ty, ty::FnConverging(output));
externs.insert(name.to_string(), f);
f
}
/// Registers a foreign function found in a library. Just adds a LLVM global.
pub fn register_foreign_item_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
abi: Abi, fty: Ty<'tcx>,
name: &str) -> ValueRef {
debug!("register_foreign_item_fn(abi={:?}, \
ty={:?}, \
name={})",
abi,
fty,
name);
let cc = llvm_calling_convention(ccx, abi);
// Register the function as a C extern fn
let tys = foreign_types_for_fn_ty(ccx, fty);
// Make sure the calling convention is right for variadic functions
// (should've been caught if not in typeck)
if tys.fn_sig.variadic {
assert!(cc == llvm::CCallConv);
}
// Create the LLVM value for the C extern fn
let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys);
let llfn = get_extern_fn(ccx, &mut *ccx.externs().borrow_mut(), name, cc, llfn_ty, fty);
add_argument_attributes(&tys, llfn);
llfn
}
/// Prepares a call to a native function. This requires adapting
/// from the Rust argument passing rules to the native rules.
///
/// # Parameters
///
/// - `callee_ty`: Rust type for the function we are calling
/// - `llfn`: the function pointer we are calling
/// - `llretptr`: where to store the return value of the function
/// - `llargs_rust`: a list of the argument values, prepared
/// as they would be if calling a Rust function
/// - `passed_arg_tys`: Rust type for the arguments. Normally we
/// can derive these from callee_ty but in the case of variadic
/// functions passed_arg_tys will include the Rust type of all
/// the arguments including the ones not specified in the fn's signature.
pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
callee_ty: Ty<'tcx>,
llfn: ValueRef,
llretptr: ValueRef,
llargs_rust: &[ValueRef],
passed_arg_tys: Vec<Ty<'tcx>>,
call_debug_loc: DebugLoc)
-> Block<'blk, 'tcx>
{
let ccx = bcx.ccx();
debug!("trans_native_call(callee_ty={:?}, \
llfn={}, \
llretptr={})",
callee_ty,
ccx.tn().val_to_string(llfn),
ccx.tn().val_to_string(llretptr));
let (fn_abi, fn_sig) = match callee_ty.sty {
ty::TyBareFn(_, ref fn_ty) => (fn_ty.abi, &fn_ty.sig),
_ => ccx.sess().bug("trans_native_call called on non-function type")
};
let fn_sig = ccx.tcx().erase_late_bound_regions(fn_sig);
let llsig = foreign_signature(ccx, &fn_sig, &passed_arg_tys[..]);
let fn_type = cabi::compute_abi_info(ccx,
&llsig.llarg_tys,
llsig.llret_ty,
llsig.ret_def);
let arg_tys: &[cabi::ArgType] = &fn_type.arg_tys;
let mut llargs_foreign = Vec::new();
// If the foreign ABI expects return value by pointer, supply the
// pointer that Rust gave us. Sometimes we have to bitcast
// because foreign fns return slightly different (but equivalent)
// views on the same type (e.g., i64 in place of {i32,i32}).
if fn_type.ret_ty.is_indirect() {
match fn_type.ret_ty.cast {
Some(ty) => {
let llcastedretptr =
BitCast(bcx, llretptr, ty.ptr_to());
llargs_foreign.push(llcastedretptr);
}
None => {
llargs_foreign.push(llretptr);
}
}
}
let mut offset = 0;
for (i, arg_ty) in arg_tys.iter().enumerate() {
let mut llarg_rust = llargs_rust[i + offset];
if arg_ty.is_ignore() {
continue;
}
// Does Rust pass this argument by pointer?
let rust_indirect = type_of::arg_is_indirect(ccx, passed_arg_tys[i]);
debug!("argument {}, llarg_rust={}, rust_indirect={}, arg_ty={}",
i,
ccx.tn().val_to_string(llarg_rust),
rust_indirect,
ccx.tn().type_to_string(arg_ty.ty));
// Ensure that we always have the Rust value indirectly,
// because it makes bitcasting easier.
if !rust_indirect {
let scratch =
base::alloca(bcx,
type_of::type_of(ccx, passed_arg_tys[i]),
"__arg");
if type_is_fat_ptr(ccx.tcx(), passed_arg_tys[i]) {
Store(bcx, llargs_rust[i + offset], expr::get_dataptr(bcx, scratch));
Store(bcx, llargs_rust[i + offset + 1], expr::get_len(bcx, scratch));
offset += 1;
} else {
base::store_ty(bcx, llarg_rust, scratch, passed_arg_tys[i]);
}
llarg_rust = scratch;
}
debug!("llarg_rust={} (after indirection)",
ccx.tn().val_to_string(llarg_rust));
// Check whether we need to do any casting
match arg_ty.cast {
Some(ty) => llarg_rust = BitCast(bcx, llarg_rust, ty.ptr_to()),
None => ()
}
debug!("llarg_rust={} (after casting)",
ccx.tn().val_to_string(llarg_rust));
// Finally, load the value if needed for the foreign ABI
let foreign_indirect = arg_ty.is_indirect();
let llarg_foreign = if foreign_indirect {
llarg_rust
} else {
if passed_arg_tys[i].is_bool() {
let val = LoadRangeAssert(bcx, llarg_rust, 0, 2, llvm::False);
Trunc(bcx, val, Type::i1(bcx.ccx()))
} else {
Load(bcx, llarg_rust)
}
};
debug!("argument {}, llarg_foreign={}",
i, ccx.tn().val_to_string(llarg_foreign));
// fill padding with undef value
match arg_ty.pad {
Some(ty) => llargs_foreign.push(C_undef(ty)),
None => ()
}
llargs_foreign.push(llarg_foreign);
}
let cc = llvm_calling_convention(ccx, fn_abi);
// A function pointer is called without the declaration available, so we have to apply
// any attributes with ABI implications directly to the call instruction.
let mut attrs = llvm::AttrBuilder::new();
// Add attributes that are always applicable, independent of the concrete foreign ABI
if fn_type.ret_ty.is_indirect() {
let llret_sz = machine::llsize_of_real(ccx, fn_type.ret_ty.ty);
// The outptr can be noalias and nocapture because it's entirely
// invisible to the program. We also know it's nonnull as well
// as how many bytes we can dereference
attrs.arg(1, llvm::Attribute::NoAlias)
.arg(1, llvm::Attribute::NoCapture)
.arg(1, llvm::DereferenceableAttribute(llret_sz));
};
// Add attributes that depend on the concrete foreign ABI
let mut arg_idx = if fn_type.ret_ty.is_indirect() { 1 } else { 0 };
match fn_type.ret_ty.attr {
Some(attr) => { attrs.arg(arg_idx, attr); },
_ => ()
}
arg_idx += 1;
for arg_ty in &fn_type.arg_tys {
if arg_ty.is_ignore() {
continue;
}
// skip padding
if arg_ty.pad.is_some() { arg_idx += 1; }
if let Some(attr) = arg_ty.attr {
attrs.arg(arg_idx, attr);
}
arg_idx += 1;
}
let llforeign_retval = CallWithConv(bcx,
llfn,
&llargs_foreign[..],
cc,
Some(attrs),
call_debug_loc);
// If the function we just called does not use an outpointer,
// store the result into the rust outpointer. Cast the outpointer
// type to match because some ABIs will use a different type than
// the Rust type. e.g., a {u32,u32} struct could be returned as
// u64.
if llsig.ret_def && !fn_type.ret_ty.is_indirect() {
let llrust_ret_ty = llsig.llret_ty;
let llforeign_ret_ty = match fn_type.ret_ty.cast {
Some(ty) => ty,
None => fn_type.ret_ty.ty
};
debug!("llretptr={}", ccx.tn().val_to_string(llretptr));
debug!("llforeign_retval={}", ccx.tn().val_to_string(llforeign_retval));
debug!("llrust_ret_ty={}", ccx.tn().type_to_string(llrust_ret_ty));
debug!("llforeign_ret_ty={}", ccx.tn().type_to_string(llforeign_ret_ty));
if llrust_ret_ty == llforeign_ret_ty {
match fn_sig.output {
ty::FnConverging(result_ty) => {
base::store_ty(bcx, llforeign_retval, llretptr, result_ty)
}
ty::FnDiverging => {}
}
} else {
// The actual return type is a struct, but the ABI
// adaptation code has cast it into some scalar type. The
// code that follows is the only reliable way I have
// found to do a transform like i64 -> {i32,i32}.
// Basically we dump the data onto the stack then memcpy it.
//
// Other approaches I tried:
// - Casting rust ret pointer to the foreign type and using Store
// is (a) unsafe if size of foreign type > size of rust type and
// (b) runs afoul of strict aliasing rules, yielding invalid
// assembly under -O (specifically, the store gets removed).
// - Truncating foreign type to correct integral type and then
// bitcasting to the struct type yields invalid cast errors.
let llscratch = base::alloca(bcx, llforeign_ret_ty, "__cast");
Store(bcx, llforeign_retval, llscratch);
let llscratch_i8 = BitCast(bcx, llscratch, Type::i8(ccx).ptr_to());
let llretptr_i8 = BitCast(bcx, llretptr, Type::i8(ccx).ptr_to());
let llrust_size = machine::llsize_of_store(ccx, llrust_ret_ty);
let llforeign_align = machine::llalign_of_min(ccx, llforeign_ret_ty);
let llrust_align = machine::llalign_of_min(ccx, llrust_ret_ty);
let llalign = cmp::min(llforeign_align, llrust_align);
debug!("llrust_size={}", llrust_size);
base::call_memcpy(bcx, llretptr_i8, llscratch_i8,
C_uint(ccx, llrust_size), llalign as u32);
}
}
return bcx;
}
// feature gate SIMD types in FFI, since I (huonw) am not sure the
// ABIs are handled at all correctly.
fn gate_simd_ffi(tcx: &ty::ctxt, decl: &ast::FnDecl, ty: &ty::BareFnTy) {
if !tcx.sess.features.borrow().simd_ffi {
let check = |ast_ty: &ast::Ty, ty: ty::Ty| {
if ty.is_simd() {
tcx.sess.span_err(ast_ty.span,
&format!("use of SIMD type `{}` in FFI is highly experimental and \
may result in invalid code",
pprust::ty_to_string(ast_ty)));
tcx.sess.fileline_help(ast_ty.span,
"add #![feature(simd_ffi)] to the crate attributes to enable");
}
};
let sig = &ty.sig.0;
for (input, ty) in decl.inputs.iter().zip(&sig.inputs) {
check(&*input.ty, *ty)
}
if let ast::Return(ref ty) = decl.output {
check(&**ty, sig.output.unwrap())
}
}
}
pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) {
let _icx = push_ctxt("foreign::trans_foreign_mod");
for foreign_item in &foreign_mod.items {
let lname = link_name(&**foreign_item);
if let ast::ForeignItemFn(ref decl, _) = foreign_item.node {
match foreign_mod.abi {
Rust | RustIntrinsic => {}
abi => {
let ty = ccx.tcx().node_id_to_type(foreign_item.id);
match ty.sty {
ty::TyBareFn(_, bft) => gate_simd_ffi(ccx.tcx(), &**decl, bft),
_ => ccx.tcx().sess.span_bug(foreign_item.span,
"foreign fn's sty isn't a bare_fn_ty?")
}
let llfn = register_foreign_item_fn(ccx, abi, ty, &lname);
attributes::from_fn_attrs(ccx, &foreign_item.attrs, llfn);
// Unlike for other items, we shouldn't call
// `base::update_linkage` here. Foreign items have
// special linkage requirements, which are handled
// inside `foreign::register_*`.
}
}
}
ccx.item_symbols().borrow_mut().insert(foreign_item.id,
lname.to_string());
}
}
///////////////////////////////////////////////////////////////////////////
// Rust functions with foreign ABIs
//
// These are normal Rust functions defined with foreign ABIs. For
// now, and perhaps forever, we translate these using a "layer of
// indirection". That is, given a Rust declaration like:
//
// extern "C" fn foo(i: u32) -> u32 { ... }
//
// we will generate a function like:
//
// S foo(T i) {
// S r;
// foo0(&r, NULL, i);
// return r;
// }
//
// #[inline_always]
// void foo0(uint32_t *r, void *env, uint32_t i) { ... }
//
// Here the (internal) `foo0` function follows the Rust ABI as normal,
// where the `foo` function follows the C ABI. We rely on LLVM to
// inline the one into the other. Of course we could just generate the
// correct code in the first place, but this is much simpler.
pub fn decl_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
t: Ty<'tcx>,
name: &str)
-> ValueRef {
let tys = foreign_types_for_fn_ty(ccx, t);
let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys);
let cconv = match t.sty {
ty::TyBareFn(_, ref fn_ty) => {
llvm_calling_convention(ccx, fn_ty.abi)
}
_ => panic!("expected bare fn in decl_rust_fn_with_foreign_abi")
};
let llfn = declare::declare_fn(ccx, name, cconv, llfn_ty,
ty::FnConverging(ccx.tcx().mk_nil()));
add_argument_attributes(&tys, llfn);
debug!("decl_rust_fn_with_foreign_abi(llfn_ty={}, llfn={})",
ccx.tn().type_to_string(llfn_ty), ccx.tn().val_to_string(llfn));
llfn
}
pub fn register_rust_fn_with_foreign_abi(ccx: &CrateContext,
sp: Span,
sym: String,
node_id: ast::NodeId)
-> ValueRef {
let _icx = push_ctxt("foreign::register_foreign_fn");
let tys = foreign_types_for_id(ccx, node_id);
let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys);
let t = ccx.tcx().node_id_to_type(node_id);
let cconv = match t.sty {
ty::TyBareFn(_, ref fn_ty) => {
llvm_calling_convention(ccx, fn_ty.abi)
}
_ => panic!("expected bare fn in register_rust_fn_with_foreign_abi")
};
let llfn = base::register_fn_llvmty(ccx, sp, sym, node_id, cconv, llfn_ty);
add_argument_attributes(&tys, llfn);
debug!("register_rust_fn_with_foreign_abi(node_id={}, llfn_ty={}, llfn={})",
node_id, ccx.tn().type_to_string(llfn_ty), ccx.tn().val_to_string(llfn));
llfn
}
pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
decl: &ast::FnDecl,
body: &ast::Block,
attrs: &[ast::Attribute],
llwrapfn: ValueRef,
param_substs: &'tcx Substs<'tcx>,
id: ast::NodeId,
hash: Option<&str>) {
let _icx = push_ctxt("foreign::build_foreign_fn");
let fnty = ccx.tcx().node_id_to_type(id);
let mty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &fnty);
let tys = foreign_types_for_fn_ty(ccx, mty);
unsafe { // unsafe because we call LLVM operations
// Build up the Rust function (`foo0` above).
let llrustfn = build_rust_fn(ccx, decl, body, param_substs, attrs, id, hash);
// Build up the foreign wrapper (`foo` above).
return build_wrap_fn(ccx, llrustfn, llwrapfn, &tys, mty);
}
fn build_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
decl: &ast::FnDecl,
body: &ast::Block,
param_substs: &'tcx Substs<'tcx>,
attrs: &[ast::Attribute],
id: ast::NodeId,
hash: Option<&str>)
-> ValueRef
{
let _icx = push_ctxt("foreign::foreign::build_rust_fn");
let tcx = ccx.tcx();
let t = tcx.node_id_to_type(id);
let t = monomorphize::apply_param_substs(tcx, param_substs, &t);
let ps = ccx.tcx().map.with_path(id, |path| {
let abi = Some(ast_map::PathName(special_idents::clownshoe_abi.name));
link::mangle(path.chain(abi), hash)
});
// Compute the type that the function would have if it were just a
// normal Rust function. This will be the type of the wrappee fn.
match t.sty {
ty::TyBareFn(_, ref f) => {
assert!(f.abi != Rust && f.abi != RustIntrinsic);
}
_ => {
ccx.sess().bug(&format!("build_rust_fn: extern fn {} has ty {:?}, \
expected a bare fn ty",
ccx.tcx().map.path_to_string(id),
t));
}
};
debug!("build_rust_fn: path={} id={} t={:?}",
ccx.tcx().map.path_to_string(id),
id, t);
let llfn = declare::define_internal_rust_fn(ccx, &ps, t);
attributes::from_fn_attrs(ccx, attrs, llfn);
base::trans_fn(ccx, decl, body, llfn, param_substs, id, &[]);
llfn
}
unsafe fn build_wrap_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
llrustfn: ValueRef,
llwrapfn: ValueRef,
tys: &ForeignTypes<'tcx>,
t: Ty<'tcx>) {
let _icx = push_ctxt(
"foreign::trans_rust_fn_with_foreign_abi::build_wrap_fn");
debug!("build_wrap_fn(llrustfn={}, llwrapfn={}, t={:?})",
ccx.tn().val_to_string(llrustfn),
ccx.tn().val_to_string(llwrapfn),
t);
// Avoid all the Rust generation stuff and just generate raw
// LLVM here.
//
// We want to generate code like this:
//
// S foo(T i) {
// S r;
// foo0(&r, NULL, i);
// return r;
// }
if llvm::LLVMCountBasicBlocks(llwrapfn) != 0 {
ccx.sess().bug("wrapping a function inside non-empty wrapper, most likely cause is \
multiple functions being wrapped");
}
let ptr = "the block\0".as_ptr();
let the_block = llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llwrapfn,
ptr as *const _);
let builder = ccx.builder();
builder.position_at_end(the_block);
// Array for the arguments we will pass to the rust function.
let mut llrust_args = Vec::new();
let mut next_foreign_arg_counter: c_uint = 0;
let mut next_foreign_arg = |pad: bool| -> c_uint {
next_foreign_arg_counter += if pad {
2
} else {
1
};
next_foreign_arg_counter - 1
};
// If there is an out pointer on the foreign function
let foreign_outptr = {
if tys.fn_ty.ret_ty.is_indirect() {
Some(get_param(llwrapfn, next_foreign_arg(false)))
} else {
None
}
};
let rustfn_ty = Type::from_ref(llvm::LLVMTypeOf(llrustfn)).element_type();
let mut rust_param_tys = rustfn_ty.func_params().into_iter();
// Push Rust return pointer, using null if it will be unused.
let rust_uses_outptr = match tys.fn_sig.output {
ty::FnConverging(ret_ty) => type_of::return_uses_outptr(ccx, ret_ty),
ty::FnDiverging => false
};
let return_alloca: Option<ValueRef>;
let llrust_ret_ty = if rust_uses_outptr {
rust_param_tys.next().expect("Missing return type!").element_type()
} else {
rustfn_ty.return_type()
};
if rust_uses_outptr {
// Rust expects to use an outpointer. If the foreign fn
// also uses an outpointer, we can reuse it, but the types
// may vary, so cast first to the Rust type. If the
// foreign fn does NOT use an outpointer, we will have to
// alloca some scratch space on the stack.
match foreign_outptr {
Some(llforeign_outptr) => {
debug!("out pointer, foreign={}",
ccx.tn().val_to_string(llforeign_outptr));
let llrust_retptr =
builder.bitcast(llforeign_outptr, llrust_ret_ty.ptr_to());
debug!("out pointer, foreign={} (casted)",
ccx.tn().val_to_string(llrust_retptr));
llrust_args.push(llrust_retptr);
return_alloca = None;
}
None => {
let slot = builder.alloca(llrust_ret_ty, "return_alloca");
debug!("out pointer, \
allocad={}, \
llrust_ret_ty={}, \
return_ty={:?}",
ccx.tn().val_to_string(slot),
ccx.tn().type_to_string(llrust_ret_ty),
tys.fn_sig.output);
llrust_args.push(slot);
return_alloca = Some(slot);
}
}
} else {
// Rust does not expect an outpointer. If the foreign fn
// does use an outpointer, then we will do a store of the
// value that the Rust fn returns.
return_alloca = None;
};
// Build up the arguments to the call to the rust function.
// Careful to adapt for cases where the native convention uses
// a pointer and Rust does not or vice versa.
for i in 0..tys.fn_sig.inputs.len() {
let rust_ty = tys.fn_sig.inputs[i];
let rust_indirect = type_of::arg_is_indirect(ccx, rust_ty);
let llty = rust_param_tys.next().expect("Not enough parameter types!");
let llrust_ty = if rust_indirect {
llty.element_type()
} else {
llty
};
let llforeign_arg_ty = tys.fn_ty.arg_tys[i];
let foreign_indirect = llforeign_arg_ty.is_indirect();
if llforeign_arg_ty.is_ignore() {
debug!("skipping ignored arg #{}", i);
llrust_args.push(C_undef(llrust_ty));
continue;
}
// skip padding
let foreign_index = next_foreign_arg(llforeign_arg_ty.pad.is_some());
let mut llforeign_arg = get_param(llwrapfn, foreign_index);
debug!("llforeign_arg {}{}: {}", "#",
i, ccx.tn().val_to_string(llforeign_arg));
debug!("rust_indirect = {}, foreign_indirect = {}",
rust_indirect, foreign_indirect);
// Ensure that the foreign argument is indirect (by
// pointer). It makes adapting types easier, since we can
// always just bitcast pointers.
if !foreign_indirect {
llforeign_arg = if rust_ty.is_bool() {
let lltemp = builder.alloca(Type::bool(ccx), "");
builder.store(builder.zext(llforeign_arg, Type::bool(ccx)), lltemp);
lltemp
} else {
let lltemp = builder.alloca(val_ty(llforeign_arg), "");
builder.store(llforeign_arg, lltemp);
lltemp
}
}
// If the types in the ABI and the Rust types don't match,
// bitcast the llforeign_arg pointer so it matches the types
// Rust expects.
if llforeign_arg_ty.cast.is_some() && !type_is_fat_ptr(ccx.tcx(), rust_ty){
assert!(!foreign_indirect);
llforeign_arg = builder.bitcast(llforeign_arg, llrust_ty.ptr_to());
}
let llrust_arg = if rust_indirect || type_is_fat_ptr(ccx.tcx(), rust_ty) {
llforeign_arg
} else {
if rust_ty.is_bool() {
let tmp = builder.load_range_assert(llforeign_arg, 0, 2, llvm::False);
builder.trunc(tmp, Type::i1(ccx))
} else if type_of::type_of(ccx, rust_ty).is_aggregate() {
// We want to pass small aggregates as immediate values, but using an aggregate
// LLVM type for this leads to bad optimizations, so its arg type is an
// appropriately sized integer and we have to convert it
let tmp = builder.bitcast(llforeign_arg,
type_of::arg_type_of(ccx, rust_ty).ptr_to());
let load = builder.load(tmp);
llvm::LLVMSetAlignment(load, type_of::align_of(ccx, rust_ty));
load
} else {
builder.load(llforeign_arg)
}
};
debug!("llrust_arg {}{}: {}", "#",
i, ccx.tn().val_to_string(llrust_arg));
if type_is_fat_ptr(ccx.tcx(), rust_ty) {
let next_llrust_ty = rust_param_tys.next().expect("Not enough parameter types!");
llrust_args.push(builder.load(builder.bitcast(builder.gepi(
llrust_arg, &[0, abi::FAT_PTR_ADDR]), llrust_ty.ptr_to())));
llrust_args.push(builder.load(builder.bitcast(builder.gepi(
llrust_arg, &[0, abi::FAT_PTR_EXTRA]), next_llrust_ty.ptr_to())));
} else {
llrust_args.push(llrust_arg);
}
}
// Perform the call itself
debug!("calling llrustfn = {}, t = {:?}",
ccx.tn().val_to_string(llrustfn), t);
let attributes = attributes::from_fn_type(ccx, t);
let llrust_ret_val = builder.call(llrustfn, &llrust_args, Some(attributes));
// Get the return value where the foreign fn expects it.
let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {
Some(ty) => ty,
None => tys.fn_ty.ret_ty.ty
};
match foreign_outptr {
None if !tys.llsig.ret_def => {
// Function returns `()` or `bot`, which in Rust is the LLVM
// type "{}" but in foreign ABIs is "Void".
builder.ret_void();
}
None if rust_uses_outptr => {
// Rust uses an outpointer, but the foreign ABI does not. Load.
let llrust_outptr = return_alloca.unwrap();
let llforeign_outptr_casted =
builder.bitcast(llrust_outptr, llforeign_ret_ty.ptr_to());
let llforeign_retval = builder.load(llforeign_outptr_casted);
builder.ret(llforeign_retval);
}
None if llforeign_ret_ty != llrust_ret_ty => {
// Neither ABI uses an outpointer, but the types don't
// quite match. Must cast. Probably we should try and
// examine the types and use a concrete llvm cast, but
// right now we just use a temp memory location and
// bitcast the pointer, which is the same thing the
// old wrappers used to do.
let lltemp = builder.alloca(llforeign_ret_ty, "");
let lltemp_casted = builder.bitcast(lltemp, llrust_ret_ty.ptr_to());
builder.store(llrust_ret_val, lltemp_casted);
let llforeign_retval = builder.load(lltemp);
builder.ret(llforeign_retval);
}
None => {
// Neither ABI uses an outpointer, and the types
// match. Easy peasy.
builder.ret(llrust_ret_val);
}
Some(llforeign_outptr) if !rust_uses_outptr => {
// Foreign ABI requires an out pointer, but Rust doesn't.
// Store Rust return value.
let llforeign_outptr_casted =
builder.bitcast(llforeign_outptr, llrust_ret_ty.ptr_to());
builder.store(llrust_ret_val, llforeign_outptr_casted);
builder.ret_void();
}
Some(_) => {
// Both ABIs use outpointers. Easy peasy.
builder.ret_void();
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// General ABI Support
//
// This code is kind of a confused mess and needs to be reworked given
// the massive simplifications that have occurred.
pub fn link_name(i: &ast::ForeignItem) -> InternedString {
match attr::first_attr_value_str_by_name(&i.attrs, "link_name") {
Some(ln) => ln.clone(),
None => match weak_lang_items::link_name(&i.attrs) {
Some(name) => name,
None => i.ident.name.as_str(),
}
}
}
/// The ForeignSignature is the LLVM types of the arguments/return type of a function. Note that
/// these LLVM types are not quite the same as the LLVM types would be for a native Rust function
/// because foreign functions just plain ignore modes. They also don't pass aggregate values by
/// pointer like we do.
fn foreign_signature<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
fn_sig: &ty::FnSig<'tcx>,
arg_tys: &[Ty<'tcx>])
-> LlvmSignature {
let llarg_tys = arg_tys.iter().map(|&arg| foreign_arg_type_of(ccx, arg)).collect();
let (llret_ty, ret_def) = match fn_sig.output {
ty::FnConverging(ret_ty) =>
(type_of::foreign_arg_type_of(ccx, ret_ty), !return_type_is_void(ccx, ret_ty)),
ty::FnDiverging =>
(Type::nil(ccx), false)
};
LlvmSignature {
llarg_tys: llarg_tys,
llret_ty: llret_ty,
ret_def: ret_def
}
}
fn foreign_types_for_id<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
id: ast::NodeId) -> ForeignTypes<'tcx> {
foreign_types_for_fn_ty(ccx, ccx.tcx().node_id_to_type(id))
}
fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
ty: Ty<'tcx>) -> ForeignTypes<'tcx> {
let fn_sig = match ty.sty {
ty::TyBareFn(_, ref fn_ty) => &fn_ty.sig,
_ => ccx.sess().bug("foreign_types_for_fn_ty called on non-function type")
};
let fn_sig = ccx.tcx().erase_late_bound_regions(fn_sig);
let llsig = foreign_signature(ccx, &fn_sig, &fn_sig.inputs);
let fn_ty = cabi::compute_abi_info(ccx,
&llsig.llarg_tys,
llsig.llret_ty,
llsig.ret_def);
debug!("foreign_types_for_fn_ty(\
ty={:?}, \
llsig={} -> {}, \
fn_ty={} -> {}, \
ret_def={}",
ty,
ccx.tn().types_to_str(&llsig.llarg_tys),
ccx.tn().type_to_string(llsig.llret_ty),
ccx.tn().types_to_str(&fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>()),
ccx.tn().type_to_string(fn_ty.ret_ty.ty),
llsig.ret_def);
ForeignTypes {
fn_sig: fn_sig,
llsig: llsig,
fn_ty: fn_ty
}
}
<|fim▁hole|>fn lltype_for_fn_from_foreign_types(ccx: &CrateContext, tys: &ForeignTypes) -> Type {
let mut llargument_tys = Vec::new();
let ret_ty = tys.fn_ty.ret_ty;
let llreturn_ty = if ret_ty.is_indirect() {
llargument_tys.push(ret_ty.ty.ptr_to());
Type::void(ccx)
} else {
match ret_ty.cast {
Some(ty) => ty,
None => ret_ty.ty
}
};
for &arg_ty in &tys.fn_ty.arg_tys {
if arg_ty.is_ignore() {
continue;
}
// add padding
match arg_ty.pad {
Some(ty) => llargument_tys.push(ty),
None => ()
}
let llarg_ty = if arg_ty.is_indirect() {
arg_ty.ty.ptr_to()
} else {
match arg_ty.cast {
Some(ty) => ty,
None => arg_ty.ty
}
};
llargument_tys.push(llarg_ty);
}
if tys.fn_sig.variadic {
Type::variadic_func(&llargument_tys, &llreturn_ty)
} else {
Type::func(&llargument_tys[..], &llreturn_ty)
}
}
pub fn lltype_for_foreign_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
ty: Ty<'tcx>) -> Type {
lltype_for_fn_from_foreign_types(ccx, &foreign_types_for_fn_ty(ccx, ty))
}
fn add_argument_attributes(tys: &ForeignTypes,
llfn: ValueRef) {
let mut i = if tys.fn_ty.ret_ty.is_indirect() {
1
} else {
0
};
match tys.fn_ty.ret_ty.attr {
Some(attr) => unsafe {
llvm::LLVMAddFunctionAttribute(llfn, i as c_uint, attr.bits() as u64);
},
None => {}
}
i += 1;
for &arg_ty in &tys.fn_ty.arg_tys {
if arg_ty.is_ignore() {
continue;
}
// skip padding
if arg_ty.pad.is_some() { i += 1; }
match arg_ty.attr {
Some(attr) => unsafe {
llvm::LLVMAddFunctionAttribute(llfn, i as c_uint, attr.bits() as u64);
},
None => ()
}
i += 1;
}
}<|fim▁end|> | |
<|file_name|>activities.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# * Authors:
# * TJEBBES Gaston <[email protected]>
# * Arezki Feth <[email protected]>;
# * Miotte Julien <[email protected]>;
import os
from pyramid.httpexceptions import HTTPFound
from autonomie.forms.admin import (
ActivityConfigSchema,
)
from autonomie.models.activity import (
ActivityType,
ActivityMode,
ActivityAction,
)
from autonomie.views.admin.accompagnement import (
BaseAdminAccompagnement,
AccompagnementIndexView,
ACCOMPAGNEMENT_URL,
)
ACTIVITY_URL = os.path.join(ACCOMPAGNEMENT_URL, 'activity')
class AdminActivitiesView(BaseAdminAccompagnement):
"""
Activities Admin view
"""
title = u"Configuration du module de Rendez-vous"
schema = ActivityConfigSchema(title=u"")
route_name = ACTIVITY_URL
def before(self, form):
query = ActivityType.query()
types = query.filter_by(active=True)
modes = ActivityMode.query()
query = ActivityAction.query()
query = query.filter_by(parent_id=None)<|fim▁hole|> activity_appstruct = {
'footer': self.request.config.get("activity_footer", ""),
'types': [type_.appstruct() for type_ in types],
'modes': [mode.appstruct() for mode in modes],
'actions': self._recursive_action_appstruct(actions)
}
self._add_pdf_img_to_appstruct('activity', activity_appstruct)
form.set_appstruct(activity_appstruct)
def submit_success(self, activity_appstruct):
"""
Handle successfull activity configuration
"""
self.store_pdf_conf(activity_appstruct, 'activity')
# We delete the elements that are no longer in the appstruct
self.disable_types(activity_appstruct)
self.disable_actions(activity_appstruct, ActivityAction)
new_modes = self.delete_modes(activity_appstruct)
self.dbsession.flush()
self.add_types(activity_appstruct)
self.add_actions(activity_appstruct, "actions", ActivityAction)
self.add_modes(new_modes)
self.request.session.flash(self.validation_msg)
return HTTPFound(
self.request.route_path(self.parent_view.route_name)
)
def includeme(config):
config.add_route(ACTIVITY_URL, ACTIVITY_URL)
config.add_admin_view(AdminActivitiesView, parent=AccompagnementIndexView)<|fim▁end|> | actions = query.filter_by(active=True)
|
<|file_name|>HtmlClipboardFormat.py<|end_file_name|><|fim▁begin|># Copyright (c) 2008, Humanized, 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 Enso 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 Humanized, Inc. ``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 Humanized, Inc. 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
<|fim▁hole|> The Win32 clipboard uses a special format for handling HTML. The basic
problem that the special format is trying to solve is that the user can
select an arbitrary chunk of formatted text that might not be valid HTML.
For instance selecting half-way through a bolded word would contain no </b>
tag. The solution is to encase the fragment in a valid HTML document.
You can read more about this at:
http://msdn.microsoft.com/workshop/networking/clipboard/htmlclipboard.asp
This module deals with converting between the clipboard HTML format and
standard HTML format.
"""
# ----------------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------------
import re
# ----------------------------------------------------------------------------
# Private Functions
# ----------------------------------------------------------------------------
def _findFirst( pattern, src ):
"""
A helper function that simplifies the logic of using regex to find
the first match in a string.
"""
results = re.findall( pattern, src )
if len(results) > 0:
return results[0]
return None
# ----------------------------------------------------------------------------
# HtmlClipboardFormat Object
# ----------------------------------------------------------------------------
class HtmlClipboardFormat:
"""
Encapsulates the conversation between the clipboard HTML
format and standard HTML format.
"""
# The 1.0 HTML clipboard header format.
HEADER_FORMAT = \
"Version:1.0\r\n" \
"StartHTML:%(htmlStart)09d\r\n" \
"EndHTML:%(htmlEnd)09d\r\n" \
"StartFragment:%(fragmentStart)09d\r\n" \
"EndFragment:%(fragmentEnd)09d\r\n" \
"StartSelection:%(fragmentStart)09d\r\n" \
"EndSelection:%(fragmentEnd)09d\r\n" \
"SourceURL:Enso\r\n"
# A generic HTML page.
HTML_PAGE = \
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n" \
"<html>\n<head><title></title></head>\n" \
"<body>%s</body>\n" \
"</html>"
# These regexps find the character offsets of the fragment strings (see
# below) from the HTML clipboard format header.
START_RE = "StartFragment:(\d+)"
END_RE = "EndFragment:(\d+)"
# The Clipboard HTML format uses the following comment strings to mark
# the beginning and end of the text fragment which represents the user's
# actual selection; everything else is envelope.
START_FRAG = "<!-- StartFragment -->"
END_FRAG = "<!-- EndFragment -->"
def __init__( self, html ):
"""
Initializes the class to represent html.
"""
# Preconditions:
assert( type( html ) == unicode )
# The internal storage format is platonic unicode.
self.html = html
@classmethod
def fromClipboardHtml( cls, clipboardHtml ):
"""
Instantiates the class given a string containing the Win32 Html
Clipboard format. The given clipboardHtml is expected to be in
utf-8 and is expected to contain the special start-fragment and
end-fragment markers as defined in the class constants. If it's
not utf-8 or if it doesn't have the right delimiters, this function
logs a warning message and creates an instance empty of text.
"""
# Preconditions:
assert( type( clipboardHtml ) == str )
try:
html = clipboardHtml.decode( "utf-8" )
except UnicodeDecodeError:
# input can't be decoded from utf-8:
logging.warn( "Non-Utf-8 string in fromClipboardHtml." )
return cls( u"" )
start = _findFirst( cls.START_RE, clipboardHtml )
end = _findFirst( cls.END_RE, clipboardHtml )
if start and end:
html = clipboardHtml[ int(start): int(end) ]
html = html.decode( "utf-8" )
return cls( html )
else:
# Start and end not found in input:
logging.warn( "Missing delimiters in fromClipboardHtml." )
return cls( u"" )
@classmethod
def fromHtml( cls, html ):
"""
Instantiates the class given a string containing plain Html.
"""
# Preconditions:
assert( isinstance( html, unicode ) )
return cls( html )
def toClipboardHtml( self ):
"""
Returns the contents in the Win32 Html format.
"""
return self._encodeHtmlFragment( self.html )
def toHtml( self ):
"""
Returns the contents in the plain Html format.
"""
return self.html
def _createHtmlPage( self, fragment ):
"""
Takes an Html fragment and encloses it in a full Html page.
"""
return self.HTML_PAGE % fragment
def _encodeHtmlFragment(self, sourceHtml):
"""
Join all our bits of information into a string formatted as per the
clipboard HTML format spec.
The return value of this function is a Python string
encoded in UTF-8.
"""
# Preconditions:
assert( type( sourceHtml ) == unicode )
# LONGTERM TODO: The above contract statement involving
# .encode().decode() could have damaging performance
# repercussions.
# NOTE: Every time we construct a string, we must encode it to
# UTF-8 *before* we do any position-sensitive operations on
# it, such as taking its length or finding a substring
# position.
if "<body>" in sourceHtml:
htmlheader, fragment = sourceHtml.split( "<body>" )
fragment, footer = fragment.split( "</body>" )
htmlheader = htmlheader + "<body>"
footer = "</body>" + footer
fragment = "".join( [self.START_FRAG,
fragment,
self.END_FRAG] )
html = "".join([ htmlheader, fragment, footer ])
else:
fragment = sourceHtml
html = self._createHtmlPage( fragment )
fragment = fragment.encode( "utf-8" )
html = html.encode( "utf-8" )
assert html == html.decode( "utf-8" ).encode( "utf-8" ), \
"Encoding got out of whack in HtmlClipboardFormat."
# How long is the header going to be?
dummyHeader = self.HEADER_FORMAT % dict( htmlStart = 0,
htmlEnd = 0,
fragmentStart = 0,
fragmentEnd = 0 )
dummyHeader = dummyHeader.encode( "utf-8" )
headerLen = len(dummyHeader)
fragmentStart = html.find( fragment )
fragmentEnd = fragmentStart + len( fragment )
positions = dict( htmlStart = headerLen,
htmlEnd = headerLen + len(html),
fragmentStart = headerLen + fragmentStart,
fragmentEnd = headerLen + fragmentEnd )
header = self.HEADER_FORMAT % positions
header = header.encode( "utf-8" )
result = header + html
# Postconditions:
assert( type( result ) == str )
assert( result == result.decode( "utf-8" ).encode( "utf-8" ) )
return result<|fim▁end|> | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
|
<|file_name|>test_signal.py<|end_file_name|><|fim▁begin|># Test quiver-time
import keras as ks
from quiver_engine import server
import sys
# Load model
if sys.version_info.major == 2:<|fim▁hole|> model = ks.models.load_model('models/my_bestmodel.h5')
elif sys.version_info.major == 3:
model = ks.models.load_model('models/my_bestmodel_py3.h5')
# Names of classes of PAMAP2
classes = ['lying',
'sitting',
'standing',
'walking',
'cycling',
'vacccuum',
'ironing']
# Launch server
server.launch(model, classes=classes, top=7, input_folder='input/')<|fim▁end|> | |
<|file_name|>Relations.js<|end_file_name|><|fim▁begin|>module.exports = {
'handles belongsTo (blog, site)': {
mysql: {
result: {
id: 2,
name: 'bookshelfjs.org'
}
},
postgresql: {
result: {
id: 2,
name: 'bookshelfjs.org'
}
},
sqlite3: {
result: {
id: 2,
name: 'bookshelfjs.org'
}
}
},
'handles hasMany (posts)': {
mysql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},
postgresql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},
sqlite3: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}
},
'handles hasOne (meta)': {
mysql: {
result: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},
postgresql: {
result: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},
sqlite3: {
result: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},
'handles belongsToMany (posts)': {
mysql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},
postgresql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},
sqlite3: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
}
},
'eager loads "hasOne" relationships correctly (site -> meta)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
}
},
'eager loads "hasMany" relationships correctly (site -> authors, blogs)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}],
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
}
},
'eager loads "belongsTo" relationships correctly (blog -> site)': {
mysql: {
result: {
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}
},
postgresql: {
result: {
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}
},
sqlite3: {
result: {
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}
}
},
'eager loads "belongsToMany" models correctly (post -> tags)': {
mysql: {
result: {
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
}
},
postgresql: {
result: {
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
}
},
sqlite3: {
result: {
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
}
}
},
'Attaches an empty related model or collection if the `EagerRelation` comes back blank': {
mysql: {
result: {
id: 3,
name: 'backbonejs.org',
meta: {
},
blogs: [],
authors: []
}
},
postgresql: {
result: {
id: 3,
name: 'backbonejs.org',
meta: {
},
authors: [],
blogs: []
}
},
sqlite3: {
result: {
id: 3,
name: 'backbonejs.org',
meta: {
},
blogs: [],
authors: []
}
}
},
'eager loads "hasOne" models correctly (sites -> meta)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},{
id: 2,
name: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
},{
id: 3,
name: 'backbonejs.org',
meta: {
}
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},{
id: 2,
name: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
},{
id: 3,
name: 'backbonejs.org',
meta: {
}
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},{
id: 2,
name: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
},{
id: 3,
name: 'backbonejs.org',
meta: {
}
}]
}
},
'eager loads "belongsTo" models correctly (blogs -> site)': {
mysql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}]
}
},
'eager loads "hasMany" models correctly (site -> blogs)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
}
},
'eager loads "belongsToMany" models correctly (posts -> tags)': {
mysql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.',
tags: []
}]
},
postgresql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.',
tags: []
}]
},
sqlite3: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.',
tags: []
}]
}
},
'eager loads "hasMany" -> "hasMany" (site -> authors.ownPosts)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
}
}
},
'eager loads "hasMany" -> "belongsToMany" (site -> authors.posts)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 2,
_pivot_post_id: 1
},{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.',
_pivot_author_id: 2,
_pivot_post_id: 2
}]
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 2,
_pivot_post_id: 1
},{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.',
_pivot_author_id: 2,
_pivot_post_id: 2
}]
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.',
_pivot_author_id: 2,
_pivot_post_id: 2
},{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 2,
_pivot_post_id: 1
}]
}]
}
}
},
'does multi deep eager loads (site -> authors.ownPosts, authors.site, blogs.posts)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
}]
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
site: {
id: 1,
name: 'knexjs.org'
},
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
site: {
id: 1,
name: 'knexjs.org'
},
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
}]
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
}]
}]
}
}
},
'eager loads "hasMany" -> "hasMany" (sites -> authors.ownPosts)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'<|fim▁hole|> first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
},{
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
ownPosts: [{
id: 4,
owner_id: 3,
blog_id: 3,
name: 'This is a new Title 4!',
content: 'Lorem ipsum Anim sed eu sint aute.'
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
ownPosts: [{
id: 5,
owner_id: 4,
blog_id: 4,
name: 'This is a new Title 5!',
content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.'
}]
}]
},{
id: 3,
name: 'backbonejs.org',
authors: []
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
},{
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
ownPosts: [{
id: 4,
owner_id: 3,
blog_id: 3,
name: 'This is a new Title 4!',
content: 'Lorem ipsum Anim sed eu sint aute.'
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
ownPosts: [{
id: 5,
owner_id: 4,
blog_id: 4,
name: 'This is a new Title 5!',
content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.'
}]
}]
},{
id: 3,
name: 'backbonejs.org',
authors: []
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
},{
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
ownPosts: [{
id: 4,
owner_id: 3,
blog_id: 3,
name: 'This is a new Title 4!',
content: 'Lorem ipsum Anim sed eu sint aute.'
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
ownPosts: [{
id: 5,
owner_id: 4,
blog_id: 4,
name: 'This is a new Title 5!',
content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.'
}]
}]
},{
id: 3,
name: 'backbonejs.org',
authors: []
}]
}
},
'eager loads relations on a populated model (site -> blogs, authors.site)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org'
}
}
},
'eager loads attributes on a collection (sites -> blogs, authors.site)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org'
},{
id: 2,
name: 'bookshelfjs.org'
},{
id: 3,
name: 'backbonejs.org'
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org'
},{
id: 2,
name: 'bookshelfjs.org'
},{
id: 3,
name: 'backbonejs.org'
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org'
},{
id: 2,
name: 'bookshelfjs.org'
},{
id: 3,
name: 'backbonejs.org'
}]
}
},
'works with many-to-many (user -> roles)': {
mysql: {
result: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
},
postgresql: {
result: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
},
sqlite3: {
result: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
},
'works with eager loaded many-to-many (user -> roles)': {
mysql: {
result: {
uid: 1,
username: 'root',
roles: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
},
postgresql: {
result: {
uid: 1,
username: 'root',
roles: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
},
sqlite3: {
result: {
uid: 1,
username: 'root',
roles: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
}
},
'handles morphOne (photo)': {
mysql: {
result: {
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors'
}
},
postgresql: {
result: {
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors'
}
},
sqlite3: {
result: {
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors'
}
}
},
'handles morphMany (photo)': {
mysql: {
result: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},
postgresql: {
result: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},
sqlite3: {
result: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
}
},
'handles morphTo (imageable "authors")': {
mysql: {
result: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},
postgresql: {
result: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},
sqlite3: {
result: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
}
},
'handles morphTo (imageable "sites")': {
mysql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org'
}
}
},
'eager loads morphMany (sites -> photos)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
photos: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},{
id: 2,
name: 'bookshelfjs.org',
photos: [{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
}]
},{
id: 3,
name: 'backbonejs.org',
photos: []
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
photos: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},{
id: 2,
name: 'bookshelfjs.org',
photos: [{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
}]
},{
id: 3,
name: 'backbonejs.org',
photos: []
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
photos: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},{
id: 2,
name: 'bookshelfjs.org',
photos: [{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
}]
},{
id: 3,
name: 'backbonejs.org',
photos: []
}]
}
},
'eager loads morphTo (photos -> imageable)': {
mysql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
postgresql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
sqlite3: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
}
},
'eager loads beyond the morphTo, where possible': {
mysql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
postgresql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
sqlite3: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
}
},
'handles hasMany `through`': {
mysql: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},
postgresql: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},
sqlite3: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
}
},
'eager loads hasMany `through`': {
mysql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
}
},
'handles hasOne `through`': {
mysql: {
result: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},
postgresql: {
result: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},
sqlite3: {
result: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
}
},
'eager loads hasOne `through`': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
info: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},{
id: 2,
name: 'bookshelfjs.org',
info: {
id: 2,
meta_id: 2,
other_description: 'This is an info block for an eager hasOne -> through test',
_pivot_id: 2,
_pivot_site_id: 2
}
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
info: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},{
id: 2,
name: 'bookshelfjs.org',
info: {
id: 2,
meta_id: 2,
other_description: 'This is an info block for an eager hasOne -> through test',
_pivot_id: 2,
_pivot_site_id: 2
}
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
info: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},{
id: 2,
name: 'bookshelfjs.org',
info: {
id: 2,
meta_id: 2,
other_description: 'This is an info block for an eager hasOne -> through test',
_pivot_id: 2,
_pivot_site_id: 2
}
}]
}
},
'eager loads belongsToMany `through`': {
mysql: {
result: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_owner_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 3,
_pivot_owner_id: 2,
_pivot_blog_id: 1
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
_pivot_id: 2,
_pivot_owner_id: 2,
_pivot_blog_id: 2
}]
},{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
blogs: [{
id: 3,
site_id: 2,
name: 'Main Site Blog',
_pivot_id: 4,
_pivot_owner_id: 3,
_pivot_blog_id: 3
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
blogs: [{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
_pivot_id: 5,
_pivot_owner_id: 4,
_pivot_blog_id: 4
}]
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_owner_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 3,
_pivot_owner_id: 2,
_pivot_blog_id: 1
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
_pivot_id: 2,
_pivot_owner_id: 2,
_pivot_blog_id: 2
}]
},{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
blogs: [{
id: 3,
site_id: 2,
name: 'Main Site Blog',
_pivot_id: 4,
_pivot_owner_id: 3,
_pivot_blog_id: 3
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
blogs: [{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
_pivot_id: 5,
_pivot_owner_id: 4,
_pivot_blog_id: 4
}]
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_owner_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
blogs: [{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
_pivot_id: 2,
_pivot_owner_id: 2,
_pivot_blog_id: 2
},{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 3,
_pivot_owner_id: 2,
_pivot_blog_id: 1
}]
},{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
blogs: [{
id: 3,
site_id: 2,
name: 'Main Site Blog',
_pivot_id: 4,
_pivot_owner_id: 3,
_pivot_blog_id: 3
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
blogs: [{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
_pivot_id: 5,
_pivot_owner_id: 4,
_pivot_blog_id: 4
}]
}]
}
},
'#65 - should eager load correctly for models': {
mysql: {
result: {
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
}
},
postgresql: {
result: {
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: '3',
name: 'search engine'
}
}
},
sqlite3: {
result: {
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
}
}
},
'#65 - should eager load correctly for collections': {
mysql: {
result: [{
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
},{
hostname: 'apple.com',
instance_id: 10,
route: null,
instance: {
id: 10,
name: 'computers'
}
}]
},
postgresql: {
result: [{
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: '3',
name: 'search engine'
}
},{
hostname: 'apple.com',
instance_id: 10,
route: null,
instance: {
id: '10',
name: 'computers'
}
}]
},
sqlite3: {
result: [{
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
},{
hostname: 'apple.com',
instance_id: 10,
route: null,
instance: {
id: 10,
name: 'computers'
}
}]
}
},
'parses eager-loaded morphTo relations (model)': {
mysql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 1,
site_id_parsed: 1,
first_name_parsed: 'Tim',
last_name_parsed: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 2,
site_id_parsed: 1,
first_name_parsed: 'Bazooka',
last_name_parsed: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageableParsed: {
}
}]
},
postgresql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 1,
site_id_parsed: 1,
first_name_parsed: 'Tim',
last_name_parsed: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 2,
site_id_parsed: 1,
first_name_parsed: 'Bazooka',
last_name_parsed: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageableParsed: {
}
}]
},
sqlite3: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 1,
site_id_parsed: 1,
first_name_parsed: 'Tim',
last_name_parsed: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 2,
site_id_parsed: 1,
first_name_parsed: 'Bazooka',
last_name_parsed: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageableParsed: {
}
}]
}
}
};<|fim▁end|> | }]
},{
id: 2,
site_id: 1, |
<|file_name|>demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pexpect
import sys
import logging
import vt102
import os
import time
def termcheck(child, timeout=0):
time.sleep(0.05)
try:
logging.debug("Waiting for EOF or timeout=%d"%timeout)
child.expect(pexpect.EOF, timeout=timeout)
except pexpect.exceptions.TIMEOUT:
logging.debug("Hit timeout and have %d characters in child.before"%len(child.before))
return child.before
def termkey(child, stream, screen, key, timeout=0):
logging.debug("Sending '%s' to child"%key)
child.send(key)
s = termcheck(child)
logging.debug("Sending child.before text to vt102 stream")
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
# START LOGGING
logging.basicConfig(filename='menu_demo.log',level=logging.DEBUG)
# SETUP VT102 EMULATOR
#rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = (50,120)
stream=vt102.stream()
screen=vt102.screen((int(rows), int(columns)))
screen.attach(stream)
logging.debug("Setup vt102 with %d %d"%(int(rows),int(columns)))<|fim▁hole|>
logging.debug("Starting demo2.py child process...")
child = pexpect.spawn('./demo2.py', maxread=65536, dimensions=(int(rows),int(columns)))
s = termcheck(child)
logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before))
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
termkey(child, stream, screen, "a")
termkey(child, stream, screen, "1")
logging.debug("Quiting...")<|fim▁end|> | |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use std::collections::HashSet;
fn main() {
struct PentNums {
n: usize,
curr: usize
}<|fim▁hole|> if index == 0 {
return PentNums{n: index, curr: 0};
}
PentNums{n: index, curr: PentNums::get(index)}
}
fn get(index: usize) -> usize {
(index * ((index * 3) - 1)) / 2
}
}
impl Iterator for PentNums {
type Item = usize;
fn next(&mut self) -> Option<usize> {
self.n += 1;
self.curr = (self.n * ((self.n * 3) - 1)) / 2;
Some(self.curr)
}
}
fn is_pent(num: usize, mut h: &mut HashSet<usize>) -> bool {
if h.contains(&num) {
return true
}
let mut p = PentNums::new(h.len());
for elem in p {
if num == elem {
h.insert(num);
return true;
} else if elem > num {
return false;
}
}
false
}
// assumes a and b are pentagonal
fn sum_diff_pent(a: usize, b: usize, mut h: &mut HashSet<usize>) -> bool {
if a >= b {
return false;
}
let e = a + b;
// println!("{:?}", e);
if !is_pent(e, &mut h) {
return false;
}
let d = b - a;
// println!("{:?}", d);
if !is_pent(d, &mut h) {
return false;
}
true
}
let mut pA = PentNums::new(8)
.take(2500)
.collect::<Vec<_>>();
let mut h: HashSet<usize> = HashSet::new();
for num in pA.clone() {
h.insert(num);
}
'outer: for curr in pA {
// println!("{:?}", curr);
let mut pB = PentNums::new(4)
.take(2500)
.collect::<Vec<_>>();
for elem in pB {
// println!("{:?}", elem);
if elem >= curr {
continue 'outer;
}
if sum_diff_pent(elem, curr, &mut h) {
println!("{:?}", curr - elem);
break 'outer;
}
}
}
}<|fim▁end|> |
impl PentNums {
fn new(index: usize) -> PentNums { |
<|file_name|>cleanupslides.py<|end_file_name|><|fim▁begin|>from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
help = "Removes CompSlides from the database that do not have matching files on the drive."
def handle_noargs(self, **options):<|fim▁hole|> from stager.staging.models import CompSlide
import os.path
slides = CompSlide.objects.all()
for slide in slides:
if not os.path.exists(settings.MEDIA_ROOT+"/"+str(slide.image)):
print str(slide.image), "deleted"
slide.delete()<|fim▁end|> | |
<|file_name|>stateWithExternalTypeAndDirectImport.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>import { MyMap, IMapState } from './stateWithType';
export interface IApplicationState extends bf.IState {
someExternalMap: MyMap;
externalState: IMapState;
}<|fim▁end|> | import * as bf from 'bobflux'; |
<|file_name|>namespace_linux.go<|end_file_name|><|fim▁begin|>package sandbox
import (
"fmt"
"net"
"os"
"os/exec"
"runtime"
"sync"
"syscall"
"time"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/reexec"
"github.com/vishvananda/netlink"
"github.com/vishvananda/netns"
)
const prefix = "/var/run/docker/netns"
var (
once sync.Once
garbagePathMap = make(map[string]bool)
gpmLock sync.Mutex
gpmWg sync.WaitGroup
gpmCleanupPeriod = 60 * time.Second
gpmChan = make(chan chan struct{})
)
<|fim▁hole|>// The networkNamespace type is the linux implementation of the Sandbox
// interface. It represents a linux network namespace, and moves an interface
// into it when called on method AddInterface or sets the gateway etc.
type networkNamespace struct {
path string
sinfo *Info
nextIfIndex int
sync.Mutex
}
func init() {
reexec.Register("netns-create", reexecCreateNamespace)
}
func createBasePath() {
err := os.MkdirAll(prefix, 0644)
if err != nil && !os.IsExist(err) {
panic("Could not create net namespace path directory")
}
// Start the garbage collection go routine
go removeUnusedPaths()
}
func removeUnusedPaths() {
gpmLock.Lock()
period := gpmCleanupPeriod
gpmLock.Unlock()
ticker := time.NewTicker(period)
for {
var (
gc chan struct{}
gcOk bool
)
select {
case <-ticker.C:
case gc, gcOk = <-gpmChan:
}
gpmLock.Lock()
pathList := make([]string, 0, len(garbagePathMap))
for path := range garbagePathMap {
pathList = append(pathList, path)
}
garbagePathMap = make(map[string]bool)
gpmWg.Add(1)
gpmLock.Unlock()
for _, path := range pathList {
os.Remove(path)
}
gpmWg.Done()
if gcOk {
close(gc)
}
}
}
func addToGarbagePaths(path string) {
gpmLock.Lock()
garbagePathMap[path] = true
gpmLock.Unlock()
}
func removeFromGarbagePaths(path string) {
gpmLock.Lock()
delete(garbagePathMap, path)
gpmLock.Unlock()
}
// GC triggers garbage collection of namespace path right away
// and waits for it.
func GC() {
waitGC := make(chan struct{})
// Trigger GC now
gpmChan <- waitGC
// wait for gc to complete
<-waitGC
}
// GenerateKey generates a sandbox key based on the passed
// container id.
func GenerateKey(containerID string) string {
maxLen := 12
if len(containerID) < maxLen {
maxLen = len(containerID)
}
return prefix + "/" + containerID[:maxLen]
}
// NewSandbox provides a new sandbox instance created in an os specific way
// provided a key which uniquely identifies the sandbox
func NewSandbox(key string, osCreate bool) (Sandbox, error) {
info, err := createNetworkNamespace(key, osCreate)
if err != nil {
return nil, err
}
return &networkNamespace{path: key, sinfo: info}, nil
}
func reexecCreateNamespace() {
if len(os.Args) < 2 {
log.Fatal("no namespace path provided")
}
if err := syscall.Mount("/proc/self/ns/net", os.Args[1], "bind", syscall.MS_BIND, ""); err != nil {
log.Fatal(err)
}
if err := loopbackUp(); err != nil {
log.Fatal(err)
}
}
func createNetworkNamespace(path string, osCreate bool) (*Info, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
origns, err := netns.Get()
if err != nil {
return nil, err
}
defer origns.Close()
if err := createNamespaceFile(path); err != nil {
return nil, err
}
cmd := &exec.Cmd{
Path: reexec.Self(),
Args: append([]string{"netns-create"}, path),
Stdout: os.Stdout,
Stderr: os.Stderr,
}
if osCreate {
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
}
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("namespace creation reexec command failed: %v", err)
}
interfaces := []*Interface{}
info := &Info{Interfaces: interfaces}
return info, nil
}
func unmountNamespaceFile(path string) {
if _, err := os.Stat(path); err == nil {
syscall.Unmount(path, syscall.MNT_DETACH)
}
}
func createNamespaceFile(path string) (err error) {
var f *os.File
once.Do(createBasePath)
// Remove it from garbage collection list if present
removeFromGarbagePaths(path)
// If the path is there unmount it first
unmountNamespaceFile(path)
// wait for garbage collection to complete if it is in progress
// before trying to create the file.
gpmWg.Wait()
if f, err = os.Create(path); err == nil {
f.Close()
}
return err
}
func loopbackUp() error {
iface, err := netlink.LinkByName("lo")
if err != nil {
return err
}
return netlink.LinkSetUp(iface)
}
func (n *networkNamespace) RemoveInterface(i *Interface) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
origns, err := netns.Get()
if err != nil {
return err
}
defer origns.Close()
f, err := os.OpenFile(n.path, os.O_RDONLY, 0)
if err != nil {
return fmt.Errorf("failed get network namespace %q: %v", n.path, err)
}
defer f.Close()
nsFD := f.Fd()
if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
return err
}
defer netns.Set(origns)
// Find the network inteerface identified by the DstName attribute.
iface, err := netlink.LinkByName(i.DstName)
if err != nil {
return err
}
// Down the interface before configuring
if err := netlink.LinkSetDown(iface); err != nil {
return err
}
err = netlink.LinkSetName(iface, i.SrcName)
if err != nil {
fmt.Println("LinkSetName failed: ", err)
return err
}
// Move the network interface to caller namespace.
if err := netlink.LinkSetNsFd(iface, int(origns)); err != nil {
fmt.Println("LinkSetNsPid failed: ", err)
return err
}
return nil
}
func (n *networkNamespace) AddInterface(i *Interface) error {
n.Lock()
i.DstName = fmt.Sprintf("%s%d", i.DstName, n.nextIfIndex)
n.nextIfIndex++
n.Unlock()
runtime.LockOSThread()
defer runtime.UnlockOSThread()
origns, err := netns.Get()
if err != nil {
return err
}
defer origns.Close()
f, err := os.OpenFile(n.path, os.O_RDONLY, 0)
if err != nil {
return fmt.Errorf("failed get network namespace %q: %v", n.path, err)
}
defer f.Close()
// Find the network interface identified by the SrcName attribute.
iface, err := netlink.LinkByName(i.SrcName)
if err != nil {
return err
}
// Move the network interface to the destination namespace.
nsFD := f.Fd()
if err := netlink.LinkSetNsFd(iface, int(nsFD)); err != nil {
return err
}
if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
return err
}
defer netns.Set(origns)
// Down the interface before configuring
if err := netlink.LinkSetDown(iface); err != nil {
return err
}
// Configure the interface now this is moved in the proper namespace.
if err := configureInterface(iface, i); err != nil {
return err
}
// Up the interface.
if err := netlink.LinkSetUp(iface); err != nil {
return err
}
n.Lock()
n.sinfo.Interfaces = append(n.sinfo.Interfaces, i)
n.Unlock()
return nil
}
func (n *networkNamespace) SetGateway(gw net.IP) error {
if len(gw) == 0 {
return nil
}
err := programGateway(n.path, gw)
if err == nil {
n.sinfo.Gateway = gw
}
return err
}
func (n *networkNamespace) SetGatewayIPv6(gw net.IP) error {
if len(gw) == 0 {
return nil
}
err := programGateway(n.path, gw)
if err == nil {
n.sinfo.GatewayIPv6 = gw
}
return err
}
func (n *networkNamespace) Interfaces() []*Interface {
return n.sinfo.Interfaces
}
func (n *networkNamespace) Key() string {
return n.path
}
func (n *networkNamespace) Destroy() error {
// Assuming no running process is executing in this network namespace,
// unmounting is sufficient to destroy it.
if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
return err
}
// Stash it into the garbage collection list
addToGarbagePaths(n.path)
return nil
}<|fim▁end|> | |
<|file_name|>FlashOn.js<|end_file_name|><|fim▁begin|>import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdFlashOn(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<polygon points="14 4 14 26 20 26 20 44 34 20 26 20 34 4" />
</IconBase>
);
}<|fim▁hole|>
export default MdFlashOn;<|fim▁end|> | |
<|file_name|>post_listfield_item_listfield.py<|end_file_name|><|fim▁begin|>import unittest
import json
from datetime import datetime
from pymongo import MongoClient
from apps.basic_resource import server
from apps.basic_resource.documents import Article, Comment, Vote
class ResourcePostListFieldItemListField(unittest.TestCase):
"""
Test if a HTTP POST that adds entries to a listfield in a item of a
listfield on a resource gives the right response and adds the data
in the database.
"""
@classmethod
def setUpClass(cls):
cls.app = server.app.test_client()
cls.mongo_client = MongoClient()
comment_id = "528a5250aa2649ffd8ce8a90"
cls.initial_data = {
'title': "Test title",
'text': "Test text",
'publish': True,
'publish_date': datetime(2013, 10, 9, 8, 7, 8),
'comments': [
Comment(
id=comment_id,<|fim▁hole|> Vote(
ip_address="1.4.1.2",
date=datetime(2012, 5, 2, 9, 1, 3),
name="Jzorz"
),
Vote(
ip_address="2.4.5.2",
date=datetime(2012, 8, 2, 8, 2, 1),
name="Nahnahnah"
)
]
),
Comment(
text="Test comment 2 old",
email="[email protected]",
upvotes=[
Vote(
ip_address="1.4.1.4",
date=datetime(2013, 5, 2, 9, 1, 3),
name="Zwefhalala"
),
Vote(
ip_address="2.4.9.2",
date=datetime(2013, 8, 2, 8, 2, 1),
name="Jhardikranall"
)
]
),
],
'top_comment': Comment(
text="Top comment",
email="[email protected]",
upvotes=[
Vote(
ip_address="5.4.1.2",
date=datetime(2012, 5, 2, 9, 2, 3),
name="Majananejjeew"
),
Vote(
ip_address="2.4.1.2",
date=datetime(2012, 3, 2, 8, 2, 1),
name="Hoeieieie"
)
]
),
'tags': ["tag1", "tag2", "tag3"]
}
article = Article(**cls.initial_data).save()
cls.add_data = {
'ip_address': "5.5.5.5",
'name': "Wejejejeje"
}
cls.response = cls.app.post(
'/articles/{}/comments/{}/upvotes/'.format(
unicode(article['id']),
comment_id
),
headers={'content-type': 'application/json'},
data=json.dumps(cls.add_data)
)
@classmethod
def tearDownClass(cls):
cls.mongo_client.unittest_monkful.article.remove()
def test_status_code(self):
"""
Test if the response status code is 201.
"""
self.assertEqual(self.response.status_code, 201)
def test_content_type(self):
"""
Test if the content-type header is 'application/json'.
"""
self.assertEqual(
self.response.headers['content-type'],
'application/json'
)
def test_json(self):
"""
Test if the response data is valid JSON.
"""
try:
json.loads(self.response.data)
except:
self.fail("Response is not valid JSON.")
def test_content(self):
"""
Test if the deserialized response data evaluates back to our
data we posted to the resource in `setUpClass`.
"""
response_data = json.loads(self.response.data)
# Remove the date field because it's auto generated and we
# didn't include it in the original posted data.
del response_data['date']
self.assertEqual(response_data, self.add_data)
def test_documents(self):
"""
Test if the POST-ed data really ended up in the document
"""
upvotes = Article.objects[0].comments[0].upvotes
self.assertEqual(len(upvotes), 3)
self.assertEqual(upvotes[2].ip_address, self.add_data['ip_address'])<|fim▁end|> | text="Test comment old",
email="[email protected]",
upvotes=[ |
<|file_name|>functions_a.js<|end_file_name|><|fim▁begin|>var searchData=
[<|fim▁hole|><|fim▁end|> | ['takeoff',['takeOff',['../class_flight_controller.html#a514f2619b98216e9fca0ad876d000966',1,'FlightController']]]
]; |
<|file_name|>Search.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###############################################################################
#
# Search
# Returns current committees, subcommittees, and their membership.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo 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<|fim▁hole|># 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.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class Search(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the Search Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(Search, self).__init__(temboo_session, '/Library/SunlightLabs/Congress/Legislator/Search')
def new_input_set(self):
return SearchInputSet()
def _make_result_set(self, result, path):
return SearchResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return SearchChoreographyExecution(session, exec_id, path)
class SearchInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the Search
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the value of the APIKey input for this Choreo. ((required, string) The API Key provided by Sunlight Labs.)
"""
super(SearchInputSet, self)._set_input('APIKey', value)
def set_AllLegislators(self, value):
"""
Set the value of the AllLegislators input for this Choreo. ((optional, boolean) A boolean flag indicating to search for all legislators even when they are no longer in office.)
"""
super(SearchInputSet, self)._set_input('AllLegislators', value)
def set_Fields(self, value):
"""
Set the value of the Fields input for this Choreo. ((optional, string) A comma-separated list of fields to include in the response.)
"""
super(SearchInputSet, self)._set_input('Fields', value)
def set_Filters(self, value):
"""
Set the value of the Filters input for this Choreo. ((optional, string) A JSON object containing key/value pairs to be used as filters.)
"""
super(SearchInputSet, self)._set_input('Filters', value)
def set_Name(self, value):
"""
Set the value of the Name input for this Choreo. ((optional, string) Deprecated (retained for backward compatibility only).)
"""
super(SearchInputSet, self)._set_input('Name', value)
def set_Order(self, value):
"""
Set the value of the Order input for this Choreo. ((optional, string) Used to order the results by field name (e.g. field__asc).)
"""
super(SearchInputSet, self)._set_input('Order', value)
def set_Page(self, value):
"""
Set the value of the Page input for this Choreo. ((optional, integer) The page offset.)
"""
super(SearchInputSet, self)._set_input('Page', value)
def set_PerPage(self, value):
"""
Set the value of the PerPage input for this Choreo. ((optional, integer) The number of results to return per page.)
"""
super(SearchInputSet, self)._set_input('PerPage', value)
def set_Query(self, value):
"""
Set the value of the Query input for this Choreo. ((conditional, string) A search term.)
"""
super(SearchInputSet, self)._set_input('Query', value)
def set_ResponseFormat(self, value):
"""
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.)
"""
super(SearchInputSet, self)._set_input('ResponseFormat', value)
class SearchResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the Search Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from the Sunlight Congress API.)
"""
return self._output.get('Response', None)
class SearchChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return SearchResultSet(response, path)<|fim▁end|> | # |
<|file_name|>ext.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', 'every_sunday',
'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday',
'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday',
'once_at_next_sunday', 'every_random_interval']
def every_random_interval(job, interval: timedelta, loop=None):
"""
executes the job randomly once in the specified interval.
example:
run a job every day at random time
run a job every hour at random time
:param job: a callable(co-routine function) which returns
a co-routine or a future or an awaitable
:param interval: the interval can also be given in the format of datetime.timedelta,
then seconds, minutes, hours, days, weeks parameters are ignored.
:param loop: io loop if the provided job is a custom future linked up
with a different event loop.
:return: schedule object, so it could be cancelled at will of the user by
aschedule.cancel(schedule)
"""
if loop is None:
loop = asyncio.get_event_loop()
start = loop.time()
def wait_time_gen():
count = 0
while True:
rand = random.randrange(round(interval.total_seconds()))
tmp = round(start + interval.total_seconds() * count + rand - loop.time())
yield tmp
count += 1
schedule = JobSchedule(job, wait_time_gen(), loop=loop)
# add it to default_schedule_manager, so that user can aschedule.cancel it
default_schedule_manager.add_schedule(schedule)
return schedule
def every_day(job, loop=None):
return every(job, timedelta=timedelta(days=1), loop=loop)
def every_week(job, loop=None):
return every(job, timedelta=timedelta(days=7), loop=loop)
every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop)<|fim▁hole|>every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop)
every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop)
every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop)
every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop)
every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop)
every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop)
once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop)
once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop)
once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop)
once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop)
once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop)
once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop)
once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop)
def _nearest_weekday(weekday):
return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7)
def _every_weekday(job, weekday, loop=None):
return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop)
def _once_at_weekday(job, weekday, loop=None):
return once_at(job, _nearest_weekday(weekday), loop=loop)<|fim▁end|> | |
<|file_name|>test_net.py<|end_file_name|><|fim▁begin|>import unittest
"""
Test for the local and the web html page for table table generation
"""
class TestNET(unittest.TestCase):
def test_net(self):
pass
<|fim▁hole|><|fim▁end|> | if __name__ == "__main__":
unittest.main() |
<|file_name|>attack_plaidctf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
import sys
import os
import deadpool_dfa
import phoenixAES
import binascii
def processinput(iblock, blocksize):
#p=b'%0*x' % (2*blocksize, iblock) # Requires python3.5
p=('%0*x' % (2*blocksize, iblock)).encode('utf8')
open('foo', 'wb').write(binascii.unhexlify(p)*4)
return (None, ['-f', '-E', 'foo'])
def processoutput(output, blocksize):
return int(binascii.hexlify(output[:16]), 16)
# Patch drmless to always return decrypted version:
if not os.path.isfile('drmless.gold'):
with open('drmless', 'rb') as finput, open('drmless.gold', 'wb') as foutput:
foutput.write(finput.read(0x6C18)+b'\x01'+finput.read()[1:])
engine=deadpool_dfa.Acquisition(targetbin='./drmless', targetdata='./drmless', goldendata='drmless.gold',
dfa=phoenixAES, processinput=processinput, processoutput=processoutput, maxleaf=2048, faults=[('nop', lambda x: 0x90)], verbose=2)
tracefiles_sets=engine.run()<|fim▁hole|><|fim▁end|> | for trace in tracefiles_sets[1]:
if phoenixAES.crack_file(trace, encrypt=False):
break |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin
from tsj.models import *
admin.site.register(Company)
admin.site.register(Resident)<|fim▁hole|>admin.site.register(MeterReadingHistory)
admin.site.register(Employer)
admin.site.register(Notification)<|fim▁end|> | admin.site.register(House)
admin.site.register(ServiceCompany)
admin.site.register(MeterType) |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # The Rust core allocation library
//!
//! This is the lowest level library through which allocation in Rust can be
//! performed.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are reexported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! Currently, there are four major definitions in this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](arc/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This types allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Heap interfaces
//!
//! The [`heap`](heap/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.<|fim▁hole|>#![crate_type = "rlib"]
#![staged_api]
#![allow(unused_attributes)]
#![unstable(feature = "alloc",
reason = "this library is unlikely to be stabilized in its current \
form or name",
issue = "27783")]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
test(no_crate_inject))]
#![no_std]
#![cfg_attr(not(stage0), needs_allocator)]
#![feature(allocator)]
#![feature(box_syntax)]
#![feature(coerce_unsized)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(core_slice_ext)]
#![feature(custom_attribute)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(nonzero)]
#![feature(num_bits_bytes)]
#![feature(optin_builtin_traits)]
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(raw)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(unsize)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![cfg_attr(stage0, feature(alloc_system))]
#![cfg_attr(not(stage0), feature(needs_allocator))]
#![cfg_attr(test, feature(test, rustc_private, box_raw))]
#[cfg(stage0)]
extern crate alloc_system;
// Allow testing this library
#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;
// Heaps provided for low-level allocation strategies
pub mod heap;
// Primitive types using the heaps above
// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::HEAP;`
// and `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed { pub use std::boxed::{Box, HEAP}; }
#[cfg(test)]
mod boxed_test;
pub mod arc;
pub mod rc;
pub mod raw_vec;
/// Common out-of-memory routine
#[cold]
#[inline(never)]
#[unstable(feature = "oom", reason = "not a scrutinized interface",
issue = "27700")]
pub fn oom() -> ! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
}<|fim▁end|> |
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "alloc"] |
<|file_name|>test_decibel.py<|end_file_name|><|fim▁begin|>from acoustics.decibel import *
def test_dbsum():
assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5)
<|fim▁hole|>def test_dbadd():
assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5)
def test_dbsub():
assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5)
def test_dbmul():
assert(abs(dbmul(10.0, 2) - 13.0103) < 1e-5)
def test_dbdiv():
assert(abs(dbdiv(13.0103, 2) - 10.0) < 1e-5)<|fim▁end|> | def test_dbmean():
assert(dbmean([10.0, 10.0]) == 10.0)
|
<|file_name|>zoom-dom.ts<|end_file_name|><|fim▁begin|>import { fullSrc } from '../element/element';
import { pixels } from '../math/unit';
import { Clone } from './clone';
import { Container } from './container';
import { Image } from './image';
import { Overlay } from './overlay';
import { Wrapper } from './wrapper';
export class ZoomDOM {
static useExisting(element: HTMLImageElement, parent: HTMLElement, grandparent: HTMLElement): ZoomDOM {
let overlay = Overlay.create();
let wrapper = new Wrapper(grandparent);
let container = new Container(parent);
let image = new Image(element);
let src = fullSrc(element);
if (src === element.src) {
return new ZoomDOM(overlay, wrapper, container, image);
} else {
return new ZoomDOM(overlay, wrapper, container, image, new Clone(container.clone()));
}
}
static create(element: HTMLImageElement): ZoomDOM {
let overlay = Overlay.create();
let wrapper = Wrapper.create();
let container = Container.create();
let image = new Image(element);
let src = fullSrc(element);
if (src === element.src) {
return new ZoomDOM(overlay, wrapper, container, image);
} else {
return new ZoomDOM(overlay, wrapper, container, image, Clone.create(src));
}
}
readonly overlay: Overlay;
readonly wrapper: Wrapper;
readonly container: Container;
readonly image: Image;
readonly clone?: Clone;
constructor(overlay: Overlay, wrapper: Wrapper, container: Container, image: Image, clone?: Clone) {
this.overlay = overlay;
this.wrapper = wrapper;
this.container = container;
this.image = image;
this.clone = clone;
}
appendContainerToWrapper(): void {
this.wrapper.element.appendChild(this.container.element);
}
replaceImageWithWrapper(): void {
let parent = this.image.element.parentElement as HTMLElement;
parent.replaceChild(this.wrapper.element, this.image.element);<|fim▁hole|> }
appendCloneToContainer(): void {
if (this.clone !== undefined) {
this.container.element.appendChild(this.clone.element);
}
}
replaceImageWithClone(): void {
if (this.clone !== undefined) {
this.clone.show();
this.image.hide();
}
}
replaceCloneWithImage(): void {
if (this.clone !== undefined) {
this.image.show();
this.clone.hide();
}
}
fixWrapperHeight(): void {
this.wrapper.element.style.height = pixels(this.image.element.height);
}
collapsed(): void {
this.overlay.removeFrom(document.body);
this.image.deactivate();
this.wrapper.finishCollapsing();
}
/**
* Called at the end of an expansion to check if the clone loaded before our expansion finished. If it did, and is
* still not visible, we can now show it to the client.
*/
showCloneIfLoaded(): void {
if (this.clone !== undefined && this.clone.isLoaded() && this.clone.isHidden()) {
this.replaceImageWithClone();
}
}
}<|fim▁end|> | }
appendImageToContainer(): void {
this.container.element.appendChild(this.image.element); |
<|file_name|>jade.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp');
var jade = require('gulp-jade');
var config = require('../../config');
<|fim▁hole|> gulp.src(config.samples.jade.src)
.pipe(jade({}))
.pipe(gulp.dest(config.samples.html.dest));
});<|fim▁end|> | gulp.task('samples:jade', function () { |
<|file_name|>Promise.js<|end_file_name|><|fim▁begin|>// **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
var Ice = require("../Ice/ModuleRegistry").Ice;
Ice.__M.require(module,
[
"../Ice/Class",
"../Ice/TimerUtil"
]);
var Timer = Ice.Timer;
//
// Promise State
//
var State = {Pending: 0, Success: 1, Failed: 2};
var resolveImp = function(self, listener)
{
var callback = self.__state === State.Success ? listener.onResponse : listener.onException;
try
{
if(typeof callback !== "function")
{
listener.promise.setState(self.__state, self._args);
}
else
{
var result = callback.apply(null, self._args);
//
// Callback can return a new promise.
//
if(result && typeof result.then == "function")
{
result.then(
function()
{
var args = arguments;
listener.promise.succeed.apply(listener.promise, args);
},
function()
{
var args = arguments;
listener.promise.fail.apply(listener.promise, args);
});
}
else
{
listener.promise.succeed(result);
}
}
}
catch(e)
{
listener.promise.fail.call(listener.promise, e);
}
};
var Promise = Ice.Class({
__init__: function()
{
this.__state = State.Pending;
this.__listeners = [];
},
then: function(onResponse, onException)
{
var promise = new Promise();
var self = this;
//
// Use setImmediate so the listeners are not resolved until the call stack is empty.
//
Timer.setImmediate(
function()
{
self.__listeners.push(
{
promise:promise,
onResponse:onResponse,
onException:onException
});
self.resolve();<|fim▁hole|> {
return this.then(null, onException);
},
finally: function(cb)
{
var p = new Promise();
var self = this;
var finallyHandler = function(method)
{
return function()
{
var args = arguments;
try
{
var result = cb.apply(null, args);
if(result && typeof result.then == "function")
{
var handler = function(){ method.apply(p, args); };
result.then(handler).exception(handler);
}
else
{
method.apply(p, args);
}
}
catch(e)
{
method.apply(p, args);
}
};
};
Timer.setImmediate(
function(){
self.then(finallyHandler(p.succeed), finallyHandler(p.fail));
});
return p;
},
delay: function(ms)
{
var p = new Promise();
var self = this;
var delayHandler = function(promise, method)
{
return function()
{
var args = arguments;
Timer.setTimeout(
function()
{
method.apply(promise, args);
},
ms);
};
};
Timer.setImmediate(function()
{
self.then(delayHandler(p, p.succeed), delayHandler(p, p.fail));
});
return p;
},
resolve: function()
{
if(this.__state === State.Pending)
{
return;
}
var obj;
while((obj = this.__listeners.pop()))
{
//
// We use a separate function here to capture the listeners
// in the loop.
//
resolveImp(this, obj);
}
},
setState: function(state, args)
{
if(this.__state === State.Pending && state !== State.Pending)
{
this.__state = state;
this._args = args;
//
// Use setImmediate so the listeners are not resolved until the call stack is empty.
//
var self = this;
Timer.setImmediate(function(){ self.resolve(); });
}
},
succeed: function()
{
var args = arguments;
this.setState(State.Success, args);
return this;
},
fail: function()
{
var args = arguments;
this.setState(State.Failed, args);
return this;
},
succeeded: function()
{
return this.__state === State.Success;
},
failed: function()
{
return this.__state === State.Failed;
},
completed: function()
{
return this.__state !== State.Pending;
}
});
//
// Create a new promise object that is fulfilled when all the promise arguments
// are fulfilled or is rejected when one of the promises is rejected.
//
Promise.all = function()
{
// If only one argument is provided, check if the argument is an array
if(arguments.length === 1 && arguments[0] instanceof Array)
{
return Promise.all.apply(this, arguments[0]);
}
var promise = new Promise();
var promises = Array.prototype.slice.call(arguments);
var results = new Array(arguments.length);
var pending = promises.length;
if(pending === 0)
{
promise.succeed.apply(promise, results);
}
for(var i = 0; i < promises.length; ++i)
{
//
// Create an anonymous function to capture the loop index
//
/*jshint -W083 */
(function(j)
{
if(promises[j] && typeof promises[j].then == "function")
{
promises[j].then(
function()
{
results[j] = arguments;
pending--;
if(pending === 0)
{
promise.succeed.apply(promise, results);
}
},
function()
{
promise.fail.apply(promise, arguments);
});
}
else
{
results[j] = promises[j];
pending--;
if(pending === 0)
{
promise.succeed.apply(promise, results);
}
}
}(i));
/*jshint +W083 */
}
return promise;
};
Promise.try = function(onResponse)
{
return new Promise().succeed().then(onResponse);
};
Promise.delay = function(ms)
{
if(arguments.length > 1)
{
var p = new Promise();
var args = Array.prototype.slice.call(arguments);
ms = args.pop();
return p.succeed.apply(p, args).delay(ms);
}
else
{
return new Promise().succeed().delay(ms);
}
};
Ice.Promise = Promise;
module.exports.Ice = Ice;<|fim▁end|> | });
return promise;
},
exception: function(onException) |
<|file_name|>DATAXFER.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2017 Trail of Bits, 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.
*/
#pragma once
namespace {
template <typename D, typename S>
DEF_SEM(MOV, D dst, const S src) {
WriteZExt(dst, Read(src));
return memory;
}
template <typename D1, typename S1, typename D2, typename S2>
DEF_SEM(XCHG, D1 dst, S1 dst_val, D2 src, S2 src_val) {
auto old_dst = Read(dst_val);
auto old_src = Read(src_val);
WriteZExt(dst, old_src);
WriteZExt(src, old_dst);
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVBE16, D dst, const S src) {
WriteZExt(dst, __builtin_bswap16(Read(src)));
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVBE32, D dst, const S src) {
WriteZExt(dst, __builtin_bswap32(Read(src)));
return memory;
}
#if 64 == ADDRESS_SIZE_BITS
template <typename D, typename S>
DEF_SEM(MOVBE64, D dst, const S src) {
Write(dst, __builtin_bswap64(Read(src)));
return memory;
}
#endif
template <typename D, typename S>
DEF_SEM(MOVQ, D dst, S src) {
UWriteV64(dst, UExtractV64(UReadV64(src), 0));
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVD, D dst, S src) {
UWriteV32(dst, UExtractV32(UReadV32(src), 0));
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVxPS, D dst, S src) {
FWriteV32(dst, FReadV32(src));
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVxPD, D dst, S src) {
FWriteV64(dst, FReadV64(src));
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVDQx, D dst, S src) {
UWriteV128(dst, UReadV128(src));
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVLPS, D dst, S src) {
auto src_vec = FReadV32(src);
auto low1 = FExtractV32(src_vec, 0);
auto low2 = FExtractV32(src_vec, 1);
FWriteV32(dst, FInsertV32(FInsertV32(FReadV32(dst), 0, low1), 1, low2));
return memory;
}
DEF_SEM(MOVLHPS, V128W dst, V128 src) {
auto res = FReadV32(dst);
auto src1 = FReadV32(src);
res = FInsertV32(res, 2, FExtractV32(src1, 0));
res = FInsertV32(res, 3, FExtractV32(src1, 1));
FWriteV32(dst, res);
return memory;
}
DEF_SEM(MOVHLPS, V128W dst, V128 src) {
auto res = FReadV32(dst);
auto src1 = FReadV32(src);
res = FInsertV32(res, 0, FExtractV32(src1, 2));
res = FInsertV32(res, 1, FExtractV32(src1, 3));
FWriteV32(dst, res);
return memory;
}
template <typename D, typename S>
DEF_SEM(MOVLPD, D dst, S src) {
FWriteV64(dst, FInsertV64(FReadV64(dst), 0, FExtractV64(FReadV64(src), 0)));
return memory;
}
#if HAS_FEATURE_AVX
DEF_SEM(VMOVLPS, VV128W dst, V128 src1, MV64 src2) {
auto low_vec = FReadV32(src2);
FWriteV32(
dst, FInsertV32(FInsertV32(FReadV32(src1), 0, FExtractV32(low_vec, 0)), 1,
FExtractV32(low_vec, 1)));
return memory;
}
DEF_SEM(VMOVLPD, VV128W dst, V128 src1, MV64 src2) {
FWriteV64(dst, FInsertV64(FReadV64(src1), 0, FExtractV64(FReadV64(src2), 0)));
return memory;
}
DEF_SEM(VMOVLHPS, VV128W dst, V128 src1, V128 src2) {
/* DEST[63:0] ← SRC1[63:0] */
/* DEST[127:64] ← SRC2[63:0] */
/* DEST[VLMAX-1:128] ← 0 */
auto src1_vec = FReadV32(src1);<|fim▁hole|> temp_vec = FInsertV32(temp_vec, 1, FExtractV32(src1_vec, 1));
temp_vec = FInsertV32(temp_vec, 2, FExtractV32(src2_vec, 0));
temp_vec = FInsertV32(temp_vec, 3, FExtractV32(src2_vec, 1));
FWriteV32(dst, temp_vec);
return memory;
}
DEF_SEM(VMOVHLPS, VV128W dst, V128 src1, V128 src2) {
auto src1_vec = FReadV32(src1);
auto src2_vec = FReadV32(src2);
float32v4_t temp_vec = {};
temp_vec = FInsertV32(temp_vec, 0, FExtractV32(src2_vec, 2));
temp_vec = FInsertV32(temp_vec, 1, FExtractV32(src2_vec, 3));
temp_vec = FInsertV32(temp_vec, 2, FExtractV32(src1_vec, 2));
temp_vec = FInsertV32(temp_vec, 3, FExtractV32(src1_vec, 3));
FWriteV32(dst, temp_vec);
return memory;
}
#endif // HAS_FEATURE_AVX
} // namespace
// Fused `CALL $0; POP reg` sequences.
DEF_ISEL(CALL_POP_FUSED_32) = MOV<R32W, I32>;
DEF_ISEL(CALL_POP_FUSED_64) = MOV<R64W, I64>;
DEF_ISEL(MOV_GPR8_IMMb_C6r0) = MOV<R8W, I8>;
DEF_ISEL(MOV_MEMb_IMMb) = MOV<M8W, I8>;
DEF_ISEL_RnW_In(MOV_GPRv_IMMz, MOV);
DEF_ISEL_MnW_In(MOV_MEMv_IMMz, MOV);
DEF_ISEL(MOVBE_GPRv_MEMv_16) = MOVBE16<R16W, M16>;
DEF_ISEL(MOVBE_GPRv_MEMv_32) = MOVBE32<R32W, M32>;
IF_64BIT(DEF_ISEL(MOVBE_GPRv_MEMv_64) = MOVBE64<R64W, M64>;)
DEF_ISEL(MOV_GPR8_GPR8_88) = MOV<R8W, R8>;
DEF_ISEL(MOV_MEMb_GPR8) = MOV<M8W, R8>;
DEF_ISEL_MnW_Rn(MOV_MEMv_GPRv, MOV);
DEF_ISEL_RnW_Rn(MOV_GPRv_GPRv_89, MOV);
DEF_ISEL_RnW_Rn(MOV_GPRv_GPRv_8B, MOV);
DEF_ISEL(MOV_GPR8_MEMb) = MOV<R8W, M8>;
DEF_ISEL(MOV_GPR8_GPR8_8A) = MOV<R8W, R8>;
DEF_ISEL_RnW_Mn(MOV_GPRv_MEMv, MOV);
DEF_ISEL_MnW_Rn(MOV_MEMv_GPRv_8B, MOV);
DEF_ISEL(MOV_AL_MEMb) = MOV<R8W, M8>;
DEF_ISEL_RnW_Mn(MOV_OrAX_MEMv, MOV);
DEF_ISEL(MOV_MEMb_AL) = MOV<M8W, R8>;
DEF_ISEL_MnW_Rn(MOV_MEMv_OrAX, MOV);
DEF_ISEL(MOV_GPR8_IMMb_D0) = MOV<R8W, I8>;
DEF_ISEL(MOV_GPR8_IMMb_B0) =
MOV<R8W, I8>; // https://github.com/intelxed/xed/commit/906d25
DEF_ISEL_RnW_In(MOV_GPRv_IMMv, MOV);
DEF_ISEL(MOVNTI_MEMd_GPR32) = MOV<M32W, R32>;
IF_64BIT(DEF_ISEL(MOVNTI_MEMq_GPR64) = MOV<M64W, R64>;)
DEF_ISEL(XCHG_MEMb_GPR8) = XCHG<M8W, M8, R8W, R8>;
DEF_ISEL(XCHG_GPR8_GPR8) = XCHG<R8W, R8, R8W, R8>;
DEF_ISEL_MnW_Mn_RnW_Rn(XCHG_MEMv_GPRv, XCHG);
DEF_ISEL_RnW_Rn_RnW_Rn(XCHG_GPRv_GPRv, XCHG);
DEF_ISEL_RnW_Rn_RnW_Rn(XCHG_GPRv_OrAX, XCHG);
DEF_ISEL(MOVQ_MMXq_MEMq_0F6E) = MOVQ<V64W, MV64>;
DEF_ISEL(MOVQ_MMXq_GPR64) = MOVQ<V64W, V64>;
DEF_ISEL(MOVQ_MEMq_MMXq_0F7E) = MOVQ<V64W, V64>;
DEF_ISEL(MOVQ_GPR64_MMXq) = MOVQ<V64W, V64>;
DEF_ISEL(MOVQ_MMXq_MEMq_0F6F) = MOVQ<V64W, MV64>;
DEF_ISEL(MOVQ_MMXq_MMXq_0F6F) = MOVQ<V64W, V64>;
DEF_ISEL(MOVQ_MEMq_MMXq_0F7F) = MOVQ<MV64W, V64>;
DEF_ISEL(MOVQ_MMXq_MMXq_0F7F) = MOVQ<V64W, V64>;
DEF_ISEL(MOVQ_XMMdq_MEMq_0F6E) = MOVQ<V128W, MV64>;
IF_64BIT(DEF_ISEL(MOVQ_XMMdq_GPR64) = MOVQ<V128W, V64>;)
DEF_ISEL(MOVQ_MEMq_XMMq_0F7E) = MOVQ<MV64W, V128>;
IF_64BIT(DEF_ISEL(MOVQ_GPR64_XMMq) = MOVQ<V64W, V128>;)
DEF_ISEL(MOVQ_MEMq_XMMq_0FD6) = MOVQ<MV64W, V128>;
DEF_ISEL(MOVQ_XMMdq_XMMq_0FD6) = MOVQ<V128W, V128>;
DEF_ISEL(MOVQ_XMMdq_MEMq_0F7E) = MOVQ<V128W, MV64>;
DEF_ISEL(MOVQ_XMMdq_XMMq_0F7E) = MOVQ<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVQ_XMMdq_MEMq_6E) = MOVQ<VV128W, MV64>;
IF_64BIT(DEF_ISEL(VMOVQ_XMMdq_GPR64q) = MOVQ<VV128W, V64>;)
DEF_ISEL(VMOVQ_MEMq_XMMq_7E) = MOVQ<MV64W, V128>;
IF_64BIT(DEF_ISEL(VMOVQ_GPR64q_XMMq) = MOVQ<V64W, V128>;)
DEF_ISEL(VMOVQ_XMMdq_MEMq_7E) = MOVQ<VV128W, MV64>;
DEF_ISEL(VMOVQ_XMMdq_XMMq_7E) = MOVQ<VV128W, V128>;
DEF_ISEL(VMOVQ_MEMq_XMMq_D6) = MOVQ<MV64W, V128>;
DEF_ISEL(VMOVQ_XMMdq_XMMq_D6) = MOVQ<VV128W, V128>;
# if HAS_FEATURE_AVX512
DEF_ISEL(VMOVQ_XMMu64_MEMu64_AVX512) = MOVQ<VV128W, MV64>;
IF_64BIT(DEF_ISEL(VMOVQ_GPR64u64_XMMu64_AVX512) = MOVQ<V64W, V128>;)
IF_64BIT(DEF_ISEL(VMOVQ_XMMu64_GPR64u64_AVX512) = MOVQ<VV128W, V64>;)
DEF_ISEL(VMOVQ_XMMu64_XMMu64_AVX512) = MOVQ<VV128W, V128>;
DEF_ISEL(VMOVQ_MEMu64_XMMu64_AVX512) = MOVQ<MV64W, V128>;
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVD_MMXq_MEMd) = MOVD<V32W, MV32>;
DEF_ISEL(MOVD_MMXq_GPR32) = MOVD<V32W, V32>;
DEF_ISEL(MOVD_MEMd_MMXd) = MOVD<MV32W, V32>;
DEF_ISEL(MOVD_GPR32_MMXd) = MOVD<V32W, V32>;
DEF_ISEL(MOVD_XMMdq_MEMd) = MOVD<V128W, MV32>;
DEF_ISEL(MOVD_XMMdq_GPR32) = MOVD<V128W, V32>; // Zero extends.
DEF_ISEL(MOVD_MEMd_XMMd) = MOVD<MV32W, V128>;
DEF_ISEL(MOVD_GPR32_XMMd) = MOVD<V32W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVD_XMMdq_MEMd) = MOVD<VV128W, MV32>;
DEF_ISEL(VMOVD_XMMdq_GPR32d) = MOVD<VV128W, V32>;
DEF_ISEL(VMOVD_MEMd_XMMd) = MOVD<MV32W, V128>;
DEF_ISEL(VMOVD_GPR32d_XMMd) = MOVD<V32W, V128>;
# if HAS_FEATURE_AVX512
DEF_ISEL(VMOVD_XMMu32_MEMu32_AVX512) = MOVD<VV128W, MV32>;
DEF_ISEL(VMOVD_XMMu32_GPR32u32_AVX512) = MOVD<VV128W, V32>;
DEF_ISEL(VMOVD_MEMu32_XMMu32_AVX512) = MOVD<MV32W, V128>;
DEF_ISEL(VMOVD_GPR32u32_XMMu32_AVX512) = MOVD<V32W, V128>;
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVAPS_XMMps_MEMps) = MOVxPS<V128W, MV128>;
DEF_ISEL(MOVAPS_XMMps_XMMps_0F28) = MOVxPS<V128W, V128>;
DEF_ISEL(MOVAPS_MEMps_XMMps) = MOVxPS<MV128W, V128>;
DEF_ISEL(MOVAPS_XMMps_XMMps_0F29) = MOVxPS<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVAPS_XMMdq_MEMdq) = MOVxPS<VV128W, MV128>;
DEF_ISEL(VMOVAPS_XMMdq_XMMdq_28) = MOVxPS<VV128W, VV128>;
DEF_ISEL(VMOVAPS_MEMdq_XMMdq) = MOVxPS<MV128W, VV128>;
DEF_ISEL(VMOVAPS_XMMdq_XMMdq_29) = MOVxPS<VV128W, VV128>;
DEF_ISEL(VMOVAPS_YMMqq_MEMqq) = MOVxPS<VV256W, MV256>;
DEF_ISEL(VMOVAPS_YMMqq_YMMqq_28) = MOVxPS<VV256W, VV256>;
DEF_ISEL(VMOVAPS_MEMqq_YMMqq) = MOVxPS<MV256W, VV256>;
DEF_ISEL(VMOVAPS_YMMqq_YMMqq_29) = MOVxPS<VV256W, VV256>;
# if HAS_FEATURE_AVX512
//4102 VMOVAPS VMOVAPS_ZMMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//4103 VMOVAPS VMOVAPS_ZMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//4104 VMOVAPS VMOVAPS_ZMMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//4105 VMOVAPS VMOVAPS_MEMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//4106 VMOVAPS VMOVAPS_XMMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//4107 VMOVAPS VMOVAPS_XMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//4108 VMOVAPS VMOVAPS_XMMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//4109 VMOVAPS VMOVAPS_MEMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//4110 VMOVAPS VMOVAPS_YMMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//4111 VMOVAPS VMOVAPS_YMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//4112 VMOVAPS VMOVAPS_YMMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//4113 VMOVAPS VMOVAPS_MEMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVNTPS_MEMdq_XMMps) = MOVxPS<MV128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVNTPS_MEMdq_XMMdq) = MOVxPS<MV128W, VV128>;
DEF_ISEL(VMOVNTPS_MEMqq_YMMqq) = MOVxPS<MV256W, VV256>;
# if HAS_FEATURE_AVX512
//6168 VMOVNTPS VMOVNTPS_MEMf32_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//6169 VMOVNTPS VMOVNTPS_MEMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//6170 VMOVNTPS VMOVNTPS_MEMf32_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVUPS_XMMps_MEMps) = MOVxPS<V128W, MV128>;
DEF_ISEL(MOVUPS_XMMps_XMMps_0F10) = MOVxPS<V128W, V128>;
DEF_ISEL(MOVUPS_MEMps_XMMps) = MOVxPS<MV128W, V128>;
DEF_ISEL(MOVUPS_XMMps_XMMps_0F11) = MOVxPS<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVUPS_XMMdq_MEMdq) = MOVxPS<VV128W, MV128>;
DEF_ISEL(VMOVUPS_XMMdq_XMMdq_10) = MOVxPS<VV128W, VV128>;
DEF_ISEL(VMOVUPS_MEMdq_XMMdq) = MOVxPS<MV128W, VV128>;
DEF_ISEL(VMOVUPS_XMMdq_XMMdq_11) = MOVxPS<VV128W, VV128>;
DEF_ISEL(VMOVUPS_YMMqq_MEMqq) = MOVxPS<VV256W, MV256>;
DEF_ISEL(VMOVUPS_YMMqq_YMMqq_10) = MOVxPS<VV256W, VV256>;
DEF_ISEL(VMOVUPS_MEMqq_YMMqq) = MOVxPS<MV256W, VV256>;
DEF_ISEL(VMOVUPS_YMMqq_YMMqq_11) = MOVxPS<VV256W, VV256>;
# if HAS_FEATURE_AVX512
//4954 VMOVUPS VMOVUPS_ZMMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//4955 VMOVUPS VMOVUPS_ZMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4956 VMOVUPS VMOVUPS_ZMMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//4957 VMOVUPS VMOVUPS_MEMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4958 VMOVUPS VMOVUPS_XMMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//4959 VMOVUPS VMOVUPS_XMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4960 VMOVUPS VMOVUPS_XMMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//4961 VMOVUPS VMOVUPS_MEMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4962 VMOVUPS VMOVUPS_YMMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//4963 VMOVUPS VMOVUPS_YMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4964 VMOVUPS VMOVUPS_YMMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//4965 VMOVUPS VMOVUPS_MEMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVAPD_XMMpd_MEMpd) = MOVxPD<V128W, MV128>;
DEF_ISEL(MOVAPD_XMMpd_XMMpd_0F28) = MOVxPD<V128W, V128>;
DEF_ISEL(MOVAPD_MEMpd_XMMpd) = MOVxPD<MV128W, V128>;
DEF_ISEL(MOVAPD_XMMpd_XMMpd_0F29) = MOVxPD<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVAPD_XMMdq_MEMdq) = MOVxPD<VV128W, MV128>;
DEF_ISEL(VMOVAPD_XMMdq_XMMdq_28) = MOVxPD<VV128W, VV128>;
DEF_ISEL(VMOVAPD_MEMdq_XMMdq) = MOVxPD<MV128W, VV128>;
DEF_ISEL(VMOVAPD_XMMdq_XMMdq_29) = MOVxPD<VV128W, VV128>;
DEF_ISEL(VMOVAPD_YMMqq_MEMqq) = MOVxPD<VV256W, MV256>;
DEF_ISEL(VMOVAPD_YMMqq_YMMqq_28) = MOVxPD<VV256W, VV256>;
DEF_ISEL(VMOVAPD_MEMqq_YMMqq) = MOVxPD<MV256W, VV256>;
DEF_ISEL(VMOVAPD_YMMqq_YMMqq_29) = MOVxPD<VV256W, VV256>;
# if HAS_FEATURE_AVX512
//5585 VMOVAPD VMOVAPD_ZMMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//5586 VMOVAPD VMOVAPD_ZMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//5587 VMOVAPD VMOVAPD_ZMMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//5588 VMOVAPD VMOVAPD_MEMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//5589 VMOVAPD VMOVAPD_XMMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//5590 VMOVAPD VMOVAPD_XMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//5591 VMOVAPD VMOVAPD_XMMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//5592 VMOVAPD VMOVAPD_MEMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//5593 VMOVAPD VMOVAPD_YMMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//5594 VMOVAPD VMOVAPD_YMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
//5595 VMOVAPD VMOVAPD_YMMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//5596 VMOVAPD VMOVAPD_MEMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVNTPD_MEMdq_XMMpd) = MOVxPD<MV128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVNTPD_MEMdq_XMMdq) = MOVxPD<MV128W, VV128>;
DEF_ISEL(VMOVNTPD_MEMqq_YMMqq) = MOVxPD<MV256W, VV256>;
# if HAS_FEATURE_AVX512
//6088 VMOVNTPD VMOVNTPD_MEMf64_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//6089 VMOVNTPD VMOVNTPD_MEMf64_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//6090 VMOVNTPD VMOVNTPD_MEMf64_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVUPD_XMMpd_MEMpd) = MOVxPD<V128W, MV128>;
DEF_ISEL(MOVUPD_XMMpd_XMMpd_0F10) = MOVxPD<V128W, V128>;
DEF_ISEL(MOVUPD_MEMpd_XMMpd) = MOVxPD<MV128W, V128>;
DEF_ISEL(MOVUPD_XMMpd_XMMpd_0F11) = MOVxPD<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVUPD_XMMdq_MEMdq) = MOVxPD<VV128W, MV128>;
DEF_ISEL(VMOVUPD_XMMdq_XMMdq_10) = MOVxPD<VV128W, VV128>;
DEF_ISEL(VMOVUPD_MEMdq_XMMdq) = MOVxPD<MV128W, VV128>;
DEF_ISEL(VMOVUPD_XMMdq_XMMdq_11) = MOVxPD<VV128W, VV128>;
DEF_ISEL(VMOVUPD_YMMqq_MEMqq) = MOVxPD<VV256W, MV256>;
DEF_ISEL(VMOVUPD_YMMqq_YMMqq_10) = MOVxPD<VV256W, VV256>;
DEF_ISEL(VMOVUPD_MEMqq_YMMqq) = MOVxPD<MV256W, VV256>;
DEF_ISEL(VMOVUPD_YMMqq_YMMqq_11) = MOVxPD<VV256W, VV256>;
# if HAS_FEATURE_AVX512
//4991 VMOVUPD VMOVUPD_ZMMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//4992 VMOVUPD VMOVUPD_ZMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4993 VMOVUPD VMOVUPD_ZMMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
//4994 VMOVUPD VMOVUPD_MEMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4995 VMOVUPD VMOVUPD_XMMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//4996 VMOVUPD VMOVUPD_XMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4997 VMOVUPD VMOVUPD_XMMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
//4998 VMOVUPD VMOVUPD_MEMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//4999 VMOVUPD VMOVUPD_YMMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//5000 VMOVUPD VMOVUPD_YMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
//5001 VMOVUPD VMOVUPD_YMMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
//5002 VMOVUPD VMOVUPD_MEMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVNTDQ_MEMdq_XMMdq) = MOVDQx<MV128W, V128>;
DEF_ISEL(MOVNTDQA_XMMdq_MEMdq) = MOVDQx<V128W, MV128>;
DEF_ISEL(MOVDQU_XMMdq_MEMdq) = MOVDQx<V128W, MV128>;
DEF_ISEL(MOVDQU_XMMdq_XMMdq_0F6F) = MOVDQx<V128W, V128>;
DEF_ISEL(MOVDQU_MEMdq_XMMdq) = MOVDQx<MV128W, V128>;
DEF_ISEL(MOVDQU_XMMdq_XMMdq_0F7F) = MOVDQx<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVNTDQ_MEMdq_XMMdq) = MOVDQx<MV128W, V128>;
DEF_ISEL(VMOVNTDQ_MEMqq_YMMqq) = MOVDQx<MV256W, VV256>;
//5061 VMOVNTDQ VMOVNTDQ_MEMu32_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//5062 VMOVNTDQ VMOVNTDQ_MEMu32_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//5063 VMOVNTDQ VMOVNTDQ_MEMu32_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
DEF_ISEL(VMOVNTDQA_XMMdq_MEMdq) = MOVDQx<VV128W, MV128>;
DEF_ISEL(VMOVNTDQA_YMMqq_MEMqq) = MOVDQx<VV256W, MV256>;
//4142 VMOVNTDQA VMOVNTDQA_ZMMu32_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//4143 VMOVNTDQA VMOVNTDQA_XMMu32_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
//4144 VMOVNTDQA VMOVNTDQA_YMMu32_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM NOTSX REQUIRES_ALIGNMENT
DEF_ISEL(VMOVDQU_XMMdq_MEMdq) = MOVDQx<VV128W, MV128>;
DEF_ISEL(VMOVDQU_XMMdq_XMMdq_6F) = MOVDQx<VV128W, VV128>;
DEF_ISEL(VMOVDQU_MEMdq_XMMdq) = MOVDQx<MV128W, VV128>;
DEF_ISEL(VMOVDQU_XMMdq_XMMdq_7F) = MOVDQx<VV128W, VV128>;
DEF_ISEL(VMOVDQU_YMMqq_MEMqq) = MOVDQx<VV256W, MV256>;
DEF_ISEL(VMOVDQU_YMMqq_YMMqq_6F) = MOVDQx<VV256W, VV256>;
DEF_ISEL(VMOVDQU_MEMqq_YMMqq) = MOVDQx<MV256W, VV256>;
DEF_ISEL(VMOVDQU_YMMqq_YMMqq_7F) = MOVDQx<VV256W, VV256>;
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVDQA_MEMdq_XMMdq) = MOVDQx<MV128W, V128>;
DEF_ISEL(MOVDQA_XMMdq_XMMdq_0F7F) = MOVDQx<V128W, V128>;
DEF_ISEL(MOVDQA_XMMdq_MEMdq) = MOVDQx<V128W, MV128>;
DEF_ISEL(MOVDQA_XMMdq_XMMdq_0F6F) = MOVDQx<V128W, V128>;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVDQA_XMMdq_MEMdq) = MOVDQx<VV128W, MV128>;
DEF_ISEL(VMOVDQA_XMMdq_XMMdq_6F) = MOVDQx<VV128W, VV128>;
DEF_ISEL(VMOVDQA_MEMdq_XMMdq) = MOVDQx<MV128W, VV128>;
DEF_ISEL(VMOVDQA_XMMdq_XMMdq_7F) = MOVDQx<VV128W, VV128>;
DEF_ISEL(VMOVDQA_YMMqq_MEMqq) = MOVDQx<VV256W, MV256>;
DEF_ISEL(VMOVDQA_YMMqq_YMMqq_6F) = MOVDQx<VV256W, VV256>;
DEF_ISEL(VMOVDQA_MEMqq_YMMqq) = MOVDQx<MV256W, VV256>;
DEF_ISEL(VMOVDQA_YMMqq_YMMqq_7F) = MOVDQx<VV256W, VV256>;
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVLPS_MEMq_XMMps) = MOVLPS<MV64W, V128>;
DEF_ISEL(MOVLPS_XMMq_MEMq) = MOVLPS<V128W, MV64>;
IF_AVX(DEF_ISEL(VMOVLPS_MEMq_XMMq) = MOVLPS<MV64W, VV128>;)
IF_AVX(DEF_ISEL(VMOVLPS_XMMdq_XMMdq_MEMq) = VMOVLPS;)
DEF_ISEL(MOVHLPS_XMMq_XMMq) = MOVHLPS;
IF_AVX(DEF_ISEL(VMOVHLPS_XMMdq_XMMq_XMMq) = VMOVHLPS;)
IF_AVX(DEF_ISEL(VMOVHLPS_XMMdq_XMMdq_XMMdq) = VMOVHLPS;)
DEF_ISEL(MOVLHPS_XMMq_XMMq) = MOVLHPS;
IF_AVX(DEF_ISEL(VMOVLHPS_XMMdq_XMMq_XMMq) = VMOVLHPS;)
IF_AVX(DEF_ISEL(VMOVLHPS_XMMdq_XMMdq_XMMdq) = VMOVLHPS;)
#if HAS_FEATURE_AVX
# if HAS_FEATURE_AVX512
//4606 VMOVLPS DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_TUPLE2
//4607 VMOVLPS VMOVLPS_MEMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_TUPLE2
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVLPD_XMMsd_MEMq) = MOVLPD<V128W, MV64>;
DEF_ISEL(MOVLPD_MEMq_XMMsd) = MOVLPD<MV64W, V128>;
IF_AVX(DEF_ISEL(VMOVLPD_MEMq_XMMq) = MOVLPD<MV64W, VV128>;)
IF_AVX(DEF_ISEL(VMOVLPD_XMMdq_XMMdq_MEMq) = VMOVLPD;)
#if HAS_FEATURE_AVX
# if HAS_FEATURE_AVX512
//4599 VMOVLPD VMOVLPD_XMMf64_XMMf64_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_SCALAR
//4600 VMOVLPD VMOVLPD_MEMf64_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_SCALAR
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
namespace {
template <typename D, typename S>
DEF_SEM(MOVSD_MEM, D dst, S src) {
FWriteV64(dst, FExtractV64(FReadV64(src), 0));
return memory;
}
DEF_SEM(MOVSD, V128W dst, V128 src) {
FWriteV64(dst, FInsertV64(FReadV64(dst), 0, FExtractV64(FReadV64(src), 0)));
return memory;
}
#if HAS_FEATURE_AVX
// Basically the same as `VMOVLPD`.
DEF_SEM(VMOVSD, VV128W dst, V128 src1, V128 src2) {
FWriteV64(dst, FInsertV64(FReadV64(src2), 1, FExtractV64(FReadV64(src1), 1)));
return memory;
}
#endif // HAS_FEATURE_AVX
} // namespace
DEF_ISEL(MOVSD_XMM_XMMsd_XMMsd_0F10) = MOVSD;
DEF_ISEL(MOVSD_XMM_XMMdq_MEMsd) = MOVSD_MEM<V128W, MV64>;
DEF_ISEL(MOVSD_XMM_MEMsd_XMMsd) = MOVSD_MEM<MV64W, V128>;
DEF_ISEL(MOVSD_XMM_XMMsd_XMMsd_0F11) = MOVSD;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVSD_XMMdq_MEMq) = MOVSD_MEM<VV128W, MV64>;
DEF_ISEL(VMOVSD_MEMq_XMMq) = MOVSD_MEM<MV64W, VV128>;
DEF_ISEL(VMOVSD_XMMdq_XMMdq_XMMq_10) = VMOVSD;
DEF_ISEL(VMOVSD_XMMdq_XMMdq_XMMq_11) = VMOVSD;
# if HAS_FEATURE_AVX512
//3632 VMOVSD VMOVSD_XMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: DISP8_SCALAR MASKOP_EVEX MEMORY_FAULT_SUPPRESSION SIMD_SCALAR
//3633 VMOVSD VMOVSD_MEMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: DISP8_SCALAR MASKOP_EVEX MEMORY_FAULT_SUPPRESSION SIMD_SCALAR
//3634 VMOVSD VMOVSD_XMMf64_MASKmskw_XMMf64_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: MASKOP_EVEX SIMD_SCALAR
//3635 VMOVSD VMOVSD_XMMf64_MASKmskw_XMMf64_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: MASKOP_EVEX SIMD_SCALAR
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVNTSD_MEMq_XMMq) = MOVSD_MEM<MV64W, V128>;
namespace {
template <typename D, typename S>
DEF_SEM(MOVSS_MEM, D dst, S src) {
FWriteV32(dst, FExtractV32(FReadV32(src), 0));
return memory;
}
DEF_SEM(MOVSS, V128W dst, V128 src) {
FWriteV32(dst, FInsertV32(FReadV32(dst), 0, FExtractV32(FReadV32(src), 0)));
return memory;
}
#if HAS_FEATURE_AVX
DEF_SEM(VMOVSS, VV128W dst, V128 src1, V128 src2) {
FWriteV32(dst, FInsertV32(FReadV32(src1), 0, FExtractV32(FReadV32(src2), 0)));
return memory;
}
#endif // HAS_FEATURE_AVX
} // namespace
DEF_ISEL(MOVSS_XMMdq_MEMss) = MOVSS_MEM<V128W, MV32>;
DEF_ISEL(MOVSS_MEMss_XMMss) = MOVSS_MEM<MV32W, V128>;
DEF_ISEL(MOVSS_XMMss_XMMss_0F10) = MOVSS;
DEF_ISEL(MOVSS_XMMss_XMMss_0F11) = MOVSS;
#if HAS_FEATURE_AVX
DEF_ISEL(VMOVSS_XMMdq_MEMd) = MOVSS_MEM<VV128W, MV32>;
DEF_ISEL(VMOVSS_MEMd_XMMd) = MOVSS_MEM<MV32W, V128>;
DEF_ISEL(VMOVSS_XMMdq_XMMdq_XMMd_10) = VMOVSS;
DEF_ISEL(VMOVSS_XMMdq_XMMdq_XMMd_11) = VMOVSS;
# if HAS_FEATURE_AVX512
//3650 VMOVSS VMOVSS_XMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: DISP8_SCALAR MASKOP_EVEX MEMORY_FAULT_SUPPRESSION SIMD_SCALAR
//3651 VMOVSS VMOVSS_MEMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: DISP8_SCALAR MASKOP_EVEX MEMORY_FAULT_SUPPRESSION SIMD_SCALAR
//3652 VMOVSS VMOVSS_XMMf32_MASKmskw_XMMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: MASKOP_EVEX SIMD_SCALAR
//3653 VMOVSS VMOVSS_XMMf32_MASKmskw_XMMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_SCALAR ATTRIBUTES: MASKOP_EVEX SIMD_SCALAR
# endif // HAS_FEATURE_AVX512
#endif // HAS_FEATURE_AVX
DEF_ISEL(MOVNTSS_MEMd_XMMd) = MOVSS_MEM<MV32W, V128>;
namespace {
DEF_SEM(MOVHPD, V128W dst, MV64 src) {
FWriteV64(dst, FInsertV64(FReadV64(dst), 1, FExtractV64(FReadV64(src), 0)));
return memory;
}
DEF_SEM(MOVHPD_STORE, MV64W dst, V128 src) {
FWriteV64(dst, FExtractV64(FReadV64(src), 1));
return memory;
}
#if HAS_FEATURE_AVX
DEF_SEM(VMOVHPD, VV256W dst, V128 src1, MV64 src2) {
FWriteV64(dst, FInsertV64(FReadV64(src1), 1, FExtractV64(FReadV64(src2), 0)));
return memory;
}
#endif // HAS_FEATURE_AVX
} // namespace
DEF_ISEL(MOVHPD_XMMsd_MEMq) = MOVHPD;
DEF_ISEL(MOVHPD_MEMq_XMMsd) = MOVHPD_STORE;
IF_AVX(DEF_ISEL(VMOVHPD_XMMdq_XMMq_MEMq) = VMOVHPD;)
IF_AVX(DEF_ISEL(VMOVHPD_MEMq_XMMdq) = MOVHPD_STORE;)
//5181 VMOVHPD VMOVHPD_XMMf64_XMMf64_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_SCALAR
//5182 VMOVHPD VMOVHPD_MEMf64_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_SCALAR
namespace {
DEF_SEM(MOVHPS, V128W dst, MV64 src) {
auto dst_vec = FReadV32(dst);
auto src_vec = FReadV32(src);
auto low_entry = FExtractV32(src_vec, 0);
auto high_entry = FExtractV32(src_vec, 1);
FWriteV32(dst, FInsertV32(FInsertV32(dst_vec, 2, low_entry), 3, high_entry));
return memory;
}
DEF_SEM(MOVHPS_STORE, MV64W dst, V128 src) {
auto dst_vec = FClearV32(FReadV32(dst));
auto src_vec = FReadV32(src);
auto low_entry = FExtractV32(src_vec, 2);
auto high_entry = FExtractV32(src_vec, 3);
FWriteV32(dst, FInsertV32(FInsertV32(dst_vec, 0, low_entry), 1, high_entry));
return memory;
}
#if HAS_FEATURE_AVX
DEF_SEM(VMOVHPS, VV256W dst, V128 src1, MV64 src2) {
auto dst_vec = FReadV32(src1);
auto src_vec = FReadV32(src2);
auto low_entry = FExtractV32(src_vec, 0);
auto high_entry = FExtractV32(src_vec, 1);
FWriteV32(dst, FInsertV32(FInsertV32(dst_vec, 2, low_entry), 3, high_entry));
return memory;
}
#endif // HAS_FEATURE_AVX
} // namespace
DEF_ISEL(MOVHPS_XMMq_MEMq) = MOVHPS;
DEF_ISEL(MOVHPS_MEMq_XMMps) = MOVHPS_STORE;
IF_AVX(DEF_ISEL(VMOVHPS_XMMdq_XMMq_MEMq) = VMOVHPS;)
IF_AVX(DEF_ISEL(VMOVHPS_MEMq_XMMdq) = MOVHPS_STORE;)
//5197 VMOVHPS VMOVHPS_XMMf32_XMMf32_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_TUPLE2
//5198 VMOVHPS VMOVHPS_MEMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES: DISP8_TUPLE2
namespace {
template <typename T>
DEF_SEM(MOV_ES, R16W dst, T src) {
Write(dst, Read(src));
return __remill_sync_hyper_call(state, memory,
SyncHyperCall::kX86SetSegmentES);
}
template <typename T>
DEF_SEM(MOV_SS, R16W dst, T src) {
Write(dst, Read(src));
return __remill_sync_hyper_call(state, memory,
SyncHyperCall::kX86SetSegmentSS);
}
template <typename T>
DEF_SEM(MOV_DS, R16W dst, T src) {
Write(dst, Read(src));
return __remill_sync_hyper_call(state, memory,
SyncHyperCall::kX86SetSegmentDS);
}
template <typename T>
DEF_SEM(MOV_FS, R16W dst, T src) {
Write(dst, Read(src));
return __remill_sync_hyper_call(state, memory,
SyncHyperCall::kX86SetSegmentFS);
}
template <typename T>
DEF_SEM(MOV_GS, R16W dst, T src) {
Write(dst, Read(src));
return __remill_sync_hyper_call(state, memory,
SyncHyperCall::kX86SetSegmentGS);
}
} // namespace
DEF_ISEL(MOV_MEMw_SEG) = MOV<M16W, R16>;
DEF_ISEL(MOV_GPRv_SEG_16) = MOV<R16W, R16>;
DEF_ISEL(MOV_GPRv_SEG_32) = MOV<R32W, R16>;
IF_64BIT(DEF_ISEL(MOV_GPRv_SEG_64) = MOV<R64W, R16>;)
DEF_ISEL(MOV_SEG_MEMw_ES) = MOV_ES<M16>;
DEF_ISEL(MOV_SEG_MEMw_SS) = MOV_SS<M16>;
DEF_ISEL(MOV_SEG_MEMw_DS) = MOV_DS<M16>;
DEF_ISEL(MOV_SEG_MEMw_FS) = MOV_FS<M16>;
DEF_ISEL(MOV_SEG_MEMw_GS) = MOV_GS<M16>;
DEF_ISEL(MOV_SEG_GPR16_ES) = MOV_ES<R16>;
DEF_ISEL(MOV_SEG_GPR16_SS) = MOV_SS<R16>;
DEF_ISEL(MOV_SEG_GPR16_DS) = MOV_DS<R16>;
DEF_ISEL(MOV_SEG_GPR16_FS) = MOV_FS<R16>;
DEF_ISEL(MOV_SEG_GPR16_GS) = MOV_GS<R16>;
/*
25 MOV_DR MOV_DR_DR_GPR32 DATAXFER BASE I86 ATTRIBUTES: NOTSX RING0
26 MOV_DR MOV_DR_DR_GPR64 DATAXFER BASE I86 ATTRIBUTES: NOTSX RING0
27 MOV_DR MOV_DR_GPR32_DR DATAXFER BASE I86 ATTRIBUTES: RING0
28 MOV_DR MOV_DR_GPR64_DR DATAXFER BASE I86 ATTRIBUTES: RING0
1312 MASKMOVDQU MASKMOVDQU_XMMdq_XMMdq DATAXFER SSE2 SSE2 ATTRIBUTES: FIXED_BASE0 MASKOP NOTSX
545 MOVMSKPS MOVMSKPS_GPR32_XMMps DATAXFER SSE SSE ATTRIBUTES:
585 MOVSHDUP MOVSHDUP_XMMps_MEMps DATAXFER SSE3 SSE3 ATTRIBUTES: REQUIRES_ALIGNMENT
586 MOVSHDUP MOVSHDUP_XMMps_XMMps DATAXFER SSE3 SSE3 ATTRIBUTES: REQUIRES_ALIGNMENT
647 MOVLHPS MOVLHPS_XMMq_XMMq DATAXFER SSE SSE ATTRIBUTES:
648 MOVQ2DQ MOVQ2DQ_XMMdq_MMXq DATAXFER SSE2 SSE2 ATTRIBUTES: MMX_EXCEPT NOTSX
689 MOV_CR MOV_CR_CR_GPR32 DATAXFER BASE I86 ATTRIBUTES: NOTSX RING0
690 MOV_CR MOV_CR_CR_GPR64 DATAXFER BASE I86 ATTRIBUTES: NOTSX RING0
691 MOV_CR MOV_CR_GPR32_CR DATAXFER BASE I86 ATTRIBUTES: RING0
692 MOV_CR MOV_CR_GPR64_CR DATAXFER BASE I86 ATTRIBUTES: RING0
957 MOVSLDUP MOVSLDUP_XMMps_MEMps DATAXFER SSE3 SSE3 ATTRIBUTES: REQUIRES_ALIGNMENT
958 MOVSLDUP MOVSLDUP_XMMps_XMMps DATAXFER SSE3 SSE3 ATTRIBUTES: REQUIRES_ALIGNMENT
1071 MOVBE MOVBE_GPRv_MEMv DATAXFER MOVBE MOVBE ATTRIBUTES: SCALABLE
1072 MOVBE MOVBE_MEMv_GPRv DATAXFER MOVBE MOVBE ATTRIBUTES: SCALABLE
1484 MOVDQ2Q MOVDQ2Q_MMXq_XMMq DATAXFER SSE2 SSE2 ATTRIBUTES: MMX_EXCEPT NOTSX
1495 MOVMSKPD MOVMSKPD_GPR32_XMMpd DATAXFER SSE2 SSE2 ATTRIBUTES:
1829 MASKMOVQ MASKMOVQ_MMXq_MMXq DATAXFER MMX PENTIUMMMX ATTRIBUTES: FIXED_BASE0 MASKOP NOTSX
1839 MOVHLPS MOVHLPS_XMMq_XMMq DATAXFER SSE SSE ATTRIBUTES:
1880 MOVDDUP MOVDDUP_XMMdq_MEMq DATAXFER SSE3 SSE3 ATTRIBUTES: UNALIGNED
1881 MOVDDUP MOVDDUP_XMMdq_XMMq DATAXFER SSE3 SSE3 ATTRIBUTES: UNALIGNED
1882 BSWAP BSWAP_GPRv DATAXFER BASE I486REAL ATTRIBUTES: SCALABLE
2101 VMOVMSKPD VMOVMSKPD_GPR32d_XMMdq DATAXFER AVX AVX ATTRIBUTES:
2102 VMOVMSKPD VMOVMSKPD_GPR32d_YMMqq DATAXFER AVX AVX ATTRIBUTES:
2107 VMOVMSKPS VMOVMSKPS_GPR32d_XMMdq DATAXFER AVX AVX ATTRIBUTES:
2108 VMOVMSKPS VMOVMSKPS_GPR32d_YMMqq DATAXFER AVX AVX ATTRIBUTES:
2202 VMOVSHDUP VMOVSHDUP_XMMdq_MEMdq DATAXFER AVX AVX ATTRIBUTES:
2203 VMOVSHDUP VMOVSHDUP_XMMdq_XMMdq DATAXFER AVX AVX ATTRIBUTES:
2204 VMOVSHDUP VMOVSHDUP_YMMqq_MEMqq DATAXFER AVX AVX ATTRIBUTES:
2205 VMOVSHDUP VMOVSHDUP_YMMqq_YMMqq DATAXFER AVX AVX ATTRIBUTES:
2281 VMOVDDUP VMOVDDUP_XMMdq_MEMq DATAXFER AVX AVX ATTRIBUTES:
2282 VMOVDDUP VMOVDDUP_XMMdq_XMMdq DATAXFER AVX AVX ATTRIBUTES:
2283 VMOVDDUP VMOVDDUP_YMMqq_MEMqq DATAXFER AVX AVX ATTRIBUTES:
2284 VMOVDDUP VMOVDDUP_YMMqq_YMMqq DATAXFER AVX AVX ATTRIBUTES:
2464 VMOVSLDUP VMOVSLDUP_XMMdq_MEMdq DATAXFER AVX AVX ATTRIBUTES:
2465 VMOVSLDUP VMOVSLDUP_XMMdq_XMMdq DATAXFER AVX AVX ATTRIBUTES:
2466 VMOVSLDUP VMOVSLDUP_YMMqq_MEMqq DATAXFER AVX AVX ATTRIBUTES:
2467 VMOVSLDUP VMOVSLDUP_YMMqq_YMMqq DATAXFER AVX AVX ATTRIBUTES:
2619 VMOVLHPS VMOVLHPS_XMMdq_XMMq_XMMq DATAXFER AVX AVX ATTRIBUTES:
3395 VMOVHLPS VMOVHLPS_XMMdq_XMMdq_XMMdq DATAXFER AVX AVX ATTRIBUTES:
3804 VPMOVDB VPMOVDB_XMMu8_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3805 VPMOVDB VPMOVDB_MEMu8_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3806 VPMOVDB VPMOVDB_XMMu8_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3807 VPMOVDB VPMOVDB_MEMu8_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3808 VPMOVDB VPMOVDB_XMMu8_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3809 VPMOVDB VPMOVDB_MEMu8_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3814 VPMOVSDB VPMOVSDB_XMMi8_MASKmskw_ZMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3815 VPMOVSDB VPMOVSDB_MEMi8_MASKmskw_ZMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3816 VPMOVSDB VPMOVSDB_XMMi8_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3817 VPMOVSDB VPMOVSDB_MEMi8_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3818 VPMOVSDB VPMOVSDB_XMMi8_MASKmskw_YMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3819 VPMOVSDB VPMOVSDB_MEMi8_MASKmskw_YMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3826 VPMOVDW VPMOVDW_YMMu16_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3827 VPMOVDW VPMOVDW_MEMu16_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3828 VPMOVDW VPMOVDW_XMMu16_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3829 VPMOVDW VPMOVDW_MEMu16_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3830 VPMOVDW VPMOVDW_XMMu16_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3831 VPMOVDW VPMOVDW_MEMu16_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3853 VMOVSHDUP VMOVSHDUP_ZMMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3854 VMOVSHDUP VMOVSHDUP_ZMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX
3855 VMOVSHDUP VMOVSHDUP_XMMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3856 VMOVSHDUP VMOVSHDUP_XMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX
3857 VMOVSHDUP VMOVSHDUP_YMMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3858 VMOVSHDUP VMOVSHDUP_YMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX
3861 VPMOVSDW VPMOVSDW_YMMi16_MASKmskw_ZMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3862 VPMOVSDW VPMOVSDW_MEMi16_MASKmskw_ZMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3863 VPMOVSDW VPMOVSDW_XMMi16_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3864 VPMOVSDW VPMOVSDW_MEMi16_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3865 VPMOVSDW VPMOVSDW_XMMi16_MASKmskw_YMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3866 VPMOVSDW VPMOVSDW_MEMi16_MASKmskw_YMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3897 VPMOVZXWQ VPMOVZXWQ_ZMMi64_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3898 VPMOVZXWQ VPMOVZXWQ_ZMMi64_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3899 VPMOVZXWQ VPMOVZXWQ_XMMi64_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3900 VPMOVZXWQ VPMOVZXWQ_XMMi64_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3901 VPMOVZXWQ VPMOVZXWQ_YMMi64_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3902 VPMOVZXWQ VPMOVZXWQ_YMMi64_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3937 VPMOVUSQW VPMOVUSQW_XMMu16_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3938 VPMOVUSQW VPMOVUSQW_MEMu16_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3939 VPMOVUSQW VPMOVUSQW_XMMu16_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3940 VPMOVUSQW VPMOVUSQW_MEMu16_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3941 VPMOVUSQW VPMOVUSQW_XMMu16_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3942 VPMOVUSQW VPMOVUSQW_MEMu16_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3962 VPMOVUSQB VPMOVUSQB_XMMu8_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3963 VPMOVUSQB VPMOVUSQB_MEMu8_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3964 VPMOVUSQB VPMOVUSQB_XMMu8_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3965 VPMOVUSQB VPMOVUSQB_MEMu8_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3966 VPMOVUSQB VPMOVUSQB_XMMu8_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3967 VPMOVUSQB VPMOVUSQB_MEMu8_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3968 VPMOVUSQD VPMOVUSQD_YMMu32_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3969 VPMOVUSQD VPMOVUSQD_MEMu32_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3970 VPMOVUSQD VPMOVUSQD_XMMu32_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3971 VPMOVUSQD VPMOVUSQD_MEMu32_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3972 VPMOVUSQD VPMOVUSQD_XMMu32_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3973 VPMOVUSQD VPMOVUSQD_MEMu32_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3980 VPMOVSXDQ VPMOVSXDQ_ZMMi64_MASKmskw_YMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
3981 VPMOVSXDQ VPMOVSXDQ_ZMMi64_MASKmskw_MEMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3982 VPMOVSXDQ VPMOVSXDQ_XMMi64_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
3983 VPMOVSXDQ VPMOVSXDQ_XMMi64_MASKmskw_MEMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
3984 VPMOVSXDQ VPMOVSXDQ_YMMi64_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
3985 VPMOVSXDQ VPMOVSXDQ_YMMi64_MASKmskw_MEMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4027 VMOVDDUP VMOVDDUP_ZMMf64_MASKmskw_ZMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4028 VMOVDDUP VMOVDDUP_ZMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_MOVDDUP MASKOP_EVEX
4029 VMOVDDUP VMOVDDUP_XMMf64_MASKmskw_XMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4030 VMOVDDUP VMOVDDUP_XMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_MOVDDUP MASKOP_EVEX
4031 VMOVDDUP VMOVDDUP_YMMf64_MASKmskw_YMMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4032 VMOVDDUP VMOVDDUP_YMMf64_MASKmskw_MEMf64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_MOVDDUP MASKOP_EVEX
4045 VMOVDQU32 VMOVDQU32_ZMMu32_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4046 VMOVDQU32 VMOVDQU32_ZMMu32_MASKmskw_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4047 VMOVDQU32 VMOVDQU32_ZMMu32_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4048 VMOVDQU32 VMOVDQU32_MEMu32_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4049 VMOVDQU32 VMOVDQU32_XMMu32_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4050 VMOVDQU32 VMOVDQU32_XMMu32_MASKmskw_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4051 VMOVDQU32 VMOVDQU32_XMMu32_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4052 VMOVDQU32 VMOVDQU32_MEMu32_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4053 VMOVDQU32 VMOVDQU32_YMMu32_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4054 VMOVDQU32 VMOVDQU32_YMMu32_MASKmskw_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4055 VMOVDQU32 VMOVDQU32_YMMu32_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4056 VMOVDQU32 VMOVDQU32_MEMu32_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4242 VPMOVD2M VPMOVD2M_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512DQ_128 ATTRIBUTES:
4243 VPMOVD2M VPMOVD2M_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512DQ_256 ATTRIBUTES:
4244 VPMOVD2M VPMOVD2M_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512DQ_512 ATTRIBUTES:
4260 VPMOVSXBQ VPMOVSXBQ_ZMMi64_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4261 VPMOVSXBQ VPMOVSXBQ_ZMMi64_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4262 VPMOVSXBQ VPMOVSXBQ_XMMi64_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4263 VPMOVSXBQ VPMOVSXBQ_XMMi64_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4264 VPMOVSXBQ VPMOVSXBQ_YMMi64_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4265 VPMOVSXBQ VPMOVSXBQ_YMMi64_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4284 VPMOVZXBD VPMOVZXBD_ZMMi32_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4285 VPMOVZXBD VPMOVZXBD_ZMMi32_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4286 VPMOVZXBD VPMOVZXBD_XMMi32_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4287 VPMOVZXBD VPMOVZXBD_XMMi32_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4288 VPMOVZXBD VPMOVZXBD_YMMi32_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4289 VPMOVZXBD VPMOVZXBD_YMMi32_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4314 VPMOVB2M VPMOVB2M_MASKmskw_XMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES:
4315 VPMOVB2M VPMOVB2M_MASKmskw_YMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES:
4316 VPMOVB2M VPMOVB2M_MASKmskw_ZMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES:
4356 VMOVSLDUP VMOVSLDUP_ZMMf32_MASKmskw_ZMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4357 VMOVSLDUP VMOVSLDUP_ZMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX
4358 VMOVSLDUP VMOVSLDUP_XMMf32_MASKmskw_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4359 VMOVSLDUP VMOVSLDUP_XMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX
4360 VMOVSLDUP VMOVSLDUP_YMMf32_MASKmskw_YMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4361 VMOVSLDUP VMOVSLDUP_YMMf32_MASKmskw_MEMf32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX
4375 VPMOVSXBW VPMOVSXBW_XMMi16_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
4376 VPMOVSXBW VPMOVSXBW_XMMi16_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4377 VPMOVSXBW VPMOVSXBW_YMMi16_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
4378 VPMOVSXBW VPMOVSXBW_YMMi16_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4379 VPMOVSXBW VPMOVSXBW_ZMMi16_MASKmskw_YMMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
4380 VPMOVSXBW VPMOVSXBW_ZMMi16_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4422 VPMOVZXBQ VPMOVZXBQ_ZMMi64_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4423 VPMOVZXBQ VPMOVZXBQ_ZMMi64_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4424 VPMOVZXBQ VPMOVZXBQ_XMMi64_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4425 VPMOVZXBQ VPMOVZXBQ_XMMi64_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4426 VPMOVZXBQ VPMOVZXBQ_YMMi64_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4427 VPMOVZXBQ VPMOVZXBQ_YMMi64_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4494 VPMOVW2M VPMOVW2M_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES:
4495 VPMOVW2M VPMOVW2M_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES:
4496 VPMOVW2M VPMOVW2M_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES:
4539 VPMOVM2W VPMOVM2W_XMMu16_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES:
4540 VPMOVM2W VPMOVM2W_YMMu16_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES:
4541 VPMOVM2W VPMOVM2W_ZMMu16_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES:
4560 VPMOVM2B VPMOVM2B_XMMu8_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES:
4561 VPMOVM2B VPMOVM2B_YMMu8_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES:
4562 VPMOVM2B VPMOVM2B_ZMMu8_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES:
4577 VPMOVM2D VPMOVM2D_XMMu32_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512DQ_128 ATTRIBUTES:
4578 VPMOVM2D VPMOVM2D_YMMu32_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512DQ_256 ATTRIBUTES:
4579 VPMOVM2D VPMOVM2D_ZMMu32_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512DQ_512 ATTRIBUTES:
4605 VMOVLHPS VMOVLHPS_XMMf32_XMMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES:
4671 VPMOVZXBW VPMOVZXBW_XMMi16_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
4672 VPMOVZXBW VPMOVZXBW_XMMi16_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4673 VPMOVZXBW VPMOVZXBW_YMMi16_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
4674 VPMOVZXBW VPMOVZXBW_YMMi16_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4675 VPMOVZXBW VPMOVZXBW_ZMMi16_MASKmskw_YMMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
4676 VPMOVZXBW VPMOVZXBW_ZMMi16_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4696 VPMOVSQW VPMOVSQW_XMMi16_MASKmskw_ZMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4697 VPMOVSQW VPMOVSQW_MEMi16_MASKmskw_ZMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4698 VPMOVSQW VPMOVSQW_XMMi16_MASKmskw_XMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4699 VPMOVSQW VPMOVSQW_MEMi16_MASKmskw_XMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4700 VPMOVSQW VPMOVSQW_XMMi16_MASKmskw_YMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4701 VPMOVSQW VPMOVSQW_MEMi16_MASKmskw_YMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4717 VPMOVSQD VPMOVSQD_YMMi32_MASKmskw_ZMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4718 VPMOVSQD VPMOVSQD_MEMi32_MASKmskw_ZMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4719 VPMOVSQD VPMOVSQD_XMMi32_MASKmskw_XMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4720 VPMOVSQD VPMOVSQD_MEMi32_MASKmskw_XMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4721 VPMOVSQD VPMOVSQD_XMMi32_MASKmskw_YMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4722 VPMOVSQD VPMOVSQD_MEMi32_MASKmskw_YMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4723 VPMOVSQB VPMOVSQB_XMMi8_MASKmskw_ZMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4724 VPMOVSQB VPMOVSQB_MEMi8_MASKmskw_ZMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4725 VPMOVSQB VPMOVSQB_XMMi8_MASKmskw_XMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4726 VPMOVSQB VPMOVSQB_MEMi8_MASKmskw_XMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4727 VPMOVSQB VPMOVSQB_XMMi8_MASKmskw_YMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4728 VPMOVSQB VPMOVSQB_MEMi8_MASKmskw_YMMi64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4735 VPMOVWB VPMOVWB_XMMu8_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
4736 VPMOVWB VPMOVWB_MEMu8_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4737 VPMOVWB VPMOVWB_XMMu8_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
4738 VPMOVWB VPMOVWB_MEMu8_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4739 VPMOVWB VPMOVWB_YMMu8_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
4740 VPMOVWB VPMOVWB_MEMu8_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4862 VMOVDQU8 VMOVDQU8_XMMu8_MASKmskw_XMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
4863 VMOVDQU8 VMOVDQU8_XMMu8_MASKmskw_MEMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4864 VMOVDQU8 VMOVDQU8_XMMu8_MASKmskw_XMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
4865 VMOVDQU8 VMOVDQU8_MEMu8_MASKmskw_XMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4866 VMOVDQU8 VMOVDQU8_YMMu8_MASKmskw_YMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
4867 VMOVDQU8 VMOVDQU8_YMMu8_MASKmskw_MEMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4868 VMOVDQU8 VMOVDQU8_YMMu8_MASKmskw_YMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
4869 VMOVDQU8 VMOVDQU8_MEMu8_MASKmskw_YMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4870 VMOVDQU8 VMOVDQU8_ZMMu8_MASKmskw_ZMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
4871 VMOVDQU8 VMOVDQU8_ZMMu8_MASKmskw_MEMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4872 VMOVDQU8 VMOVDQU8_ZMMu8_MASKmskw_ZMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
4873 VMOVDQU8 VMOVDQU8_MEMu8_MASKmskw_ZMMu8_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4878 VPMOVUSDB VPMOVUSDB_XMMu8_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4879 VPMOVUSDB VPMOVUSDB_MEMu8_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4880 VPMOVUSDB VPMOVUSDB_XMMu8_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4881 VPMOVUSDB VPMOVUSDB_MEMu8_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4882 VPMOVUSDB VPMOVUSDB_XMMu8_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4883 VPMOVUSDB VPMOVUSDB_MEMu8_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4908 VPMOVUSDW VPMOVUSDW_YMMu16_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
4909 VPMOVUSDW VPMOVUSDW_MEMu16_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4910 VPMOVUSDW VPMOVUSDW_XMMu16_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
4911 VPMOVUSDW VPMOVUSDW_MEMu16_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
4912 VPMOVUSDW VPMOVUSDW_XMMu16_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
4913 VPMOVUSDW VPMOVUSDW_MEMu16_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5292 VPMOVQ2M VPMOVQ2M_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512DQ_128 ATTRIBUTES:
5293 VPMOVQ2M VPMOVQ2M_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512DQ_256 ATTRIBUTES:
5294 VPMOVQ2M VPMOVQ2M_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512DQ_512 ATTRIBUTES:
5515 VMOVDQU16 VMOVDQU16_XMMu16_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
5516 VMOVDQU16 VMOVDQU16_XMMu16_MASKmskw_MEMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5517 VMOVDQU16 VMOVDQU16_XMMu16_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
5518 VMOVDQU16 VMOVDQU16_MEMu16_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5519 VMOVDQU16 VMOVDQU16_YMMu16_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
5520 VMOVDQU16 VMOVDQU16_YMMu16_MASKmskw_MEMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5521 VMOVDQU16 VMOVDQU16_YMMu16_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
5522 VMOVDQU16 VMOVDQU16_MEMu16_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5523 VMOVDQU16 VMOVDQU16_ZMMu16_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
5524 VMOVDQU16 VMOVDQU16_ZMMu16_MASKmskw_MEMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5525 VMOVDQU16 VMOVDQU16_ZMMu16_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
5526 VMOVDQU16 VMOVDQU16_MEMu16_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5535 VPMOVSXBD VPMOVSXBD_ZMMi32_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5536 VPMOVSXBD VPMOVSXBD_ZMMi32_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5537 VPMOVSXBD VPMOVSXBD_XMMi32_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5538 VPMOVSXBD VPMOVSXBD_XMMi32_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5539 VPMOVSXBD VPMOVSXBD_YMMi32_MASKmskw_XMMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5540 VPMOVSXBD VPMOVSXBD_YMMi32_MASKmskw_MEMi8_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5627 VPMOVZXWD VPMOVZXWD_ZMMi32_MASKmskw_YMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5628 VPMOVZXWD VPMOVZXWD_ZMMi32_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5629 VPMOVZXWD VPMOVZXWD_XMMi32_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5630 VPMOVZXWD VPMOVZXWD_XMMi32_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5631 VPMOVZXWD VPMOVZXWD_YMMi32_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5632 VPMOVZXWD VPMOVZXWD_YMMi32_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5636 VMOVDQU64 VMOVDQU64_ZMMu64_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5637 VMOVDQU64 VMOVDQU64_ZMMu64_MASKmskw_MEMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5638 VMOVDQU64 VMOVDQU64_ZMMu64_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5639 VMOVDQU64 VMOVDQU64_MEMu64_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5640 VMOVDQU64 VMOVDQU64_XMMu64_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5641 VMOVDQU64 VMOVDQU64_XMMu64_MASKmskw_MEMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5642 VMOVDQU64 VMOVDQU64_XMMu64_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5643 VMOVDQU64 VMOVDQU64_MEMu64_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5644 VMOVDQU64 VMOVDQU64_YMMu64_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5645 VMOVDQU64 VMOVDQU64_YMMu64_MASKmskw_MEMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5646 VMOVDQU64 VMOVDQU64_YMMu64_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5647 VMOVDQU64 VMOVDQU64_MEMu64_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5665 VMOVDQA64 VMOVDQA64_ZMMu64_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5666 VMOVDQA64 VMOVDQA64_ZMMu64_MASKmskw_MEMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
5667 VMOVDQA64 VMOVDQA64_ZMMu64_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5668 VMOVDQA64 VMOVDQA64_MEMu64_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
5669 VMOVDQA64 VMOVDQA64_XMMu64_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5670 VMOVDQA64 VMOVDQA64_XMMu64_MASKmskw_MEMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
5671 VMOVDQA64 VMOVDQA64_XMMu64_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5672 VMOVDQA64 VMOVDQA64_MEMu64_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
5673 VMOVDQA64 VMOVDQA64_YMMu64_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5674 VMOVDQA64 VMOVDQA64_YMMu64_MASKmskw_MEMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
5675 VMOVDQA64 VMOVDQA64_YMMu64_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5676 VMOVDQA64 VMOVDQA64_MEMu64_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
5902 VPMOVZXDQ VPMOVZXDQ_ZMMi64_MASKmskw_YMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5903 VPMOVZXDQ VPMOVZXDQ_ZMMi64_MASKmskw_MEMi32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5904 VPMOVZXDQ VPMOVZXDQ_XMMi64_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5905 VPMOVZXDQ VPMOVZXDQ_XMMi64_MASKmskw_MEMi32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5906 VPMOVZXDQ VPMOVZXDQ_YMMi64_MASKmskw_XMMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5907 VPMOVZXDQ VPMOVZXDQ_YMMi64_MASKmskw_MEMi32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5931 VPMOVUSWB VPMOVUSWB_XMMu8_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
5932 VPMOVUSWB VPMOVUSWB_MEMu8_MASKmskw_XMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5933 VPMOVUSWB VPMOVUSWB_XMMu8_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
5934 VPMOVUSWB VPMOVUSWB_MEMu8_MASKmskw_YMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5935 VPMOVUSWB VPMOVUSWB_YMMu8_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
5936 VPMOVUSWB VPMOVUSWB_MEMu8_MASKmskw_ZMMu16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5961 VPMOVSWB VPMOVSWB_XMMi8_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: MASKOP_EVEX
5962 VPMOVSWB VPMOVSWB_MEMi8_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512BW_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5963 VPMOVSWB VPMOVSWB_XMMi8_MASKmskw_YMMi16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: MASKOP_EVEX
5964 VPMOVSWB VPMOVSWB_MEMi8_MASKmskw_YMMi16_AVX512 DATAXFER AVX512EVEX AVX512BW_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5965 VPMOVSWB VPMOVSWB_YMMi8_MASKmskw_ZMMi16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: MASKOP_EVEX
5966 VPMOVSWB VPMOVSWB_MEMi8_MASKmskw_ZMMi16_AVX512 DATAXFER AVX512EVEX AVX512BW_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5990 VPMOVSXWD VPMOVSXWD_ZMMi32_MASKmskw_YMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
5991 VPMOVSXWD VPMOVSXWD_ZMMi32_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5992 VPMOVSXWD VPMOVSXWD_XMMi32_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
5993 VPMOVSXWD VPMOVSXWD_XMMi32_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5994 VPMOVSXWD VPMOVSXWD_YMMi32_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
5995 VPMOVSXWD VPMOVSXWD_YMMi32_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
5996 VMOVHLPS VMOVHLPS_XMMf32_XMMf32_XMMf32_AVX512 DATAXFER AVX512EVEX AVX512F_128N ATTRIBUTES:
6007 VPMOVSXWQ VPMOVSXWQ_ZMMi64_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
6008 VPMOVSXWQ VPMOVSXWQ_ZMMi64_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6009 VPMOVSXWQ VPMOVSXWQ_XMMi64_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
6010 VPMOVSXWQ VPMOVSXWQ_XMMi64_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6011 VPMOVSXWQ VPMOVSXWQ_YMMi64_MASKmskw_XMMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
6012 VPMOVSXWQ VPMOVSXWQ_YMMi64_MASKmskw_MEMi16_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6171 VMOVDQA32 VMOVDQA32_ZMMu32_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
6172 VMOVDQA32 VMOVDQA32_ZMMu32_MASKmskw_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
6173 VMOVDQA32 VMOVDQA32_ZMMu32_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
6174 VMOVDQA32 VMOVDQA32_MEMu32_MASKmskw_ZMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
6175 VMOVDQA32 VMOVDQA32_XMMu32_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
6176 VMOVDQA32 VMOVDQA32_XMMu32_MASKmskw_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
6177 VMOVDQA32 VMOVDQA32_XMMu32_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
6178 VMOVDQA32 VMOVDQA32_MEMu32_MASKmskw_XMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
6179 VMOVDQA32 VMOVDQA32_YMMu32_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
6180 VMOVDQA32 VMOVDQA32_YMMu32_MASKmskw_MEMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
6181 VMOVDQA32 VMOVDQA32_YMMu32_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
6182 VMOVDQA32 VMOVDQA32_MEMu32_MASKmskw_YMMu32_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: AVX_REQUIRES_ALIGNMENT DISP8_FULLMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION REQUIRES_ALIGNMENT
6309 VPMOVQW VPMOVQW_XMMu16_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
6310 VPMOVQW VPMOVQW_MEMu16_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6311 VPMOVQW VPMOVQW_XMMu16_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
6312 VPMOVQW VPMOVQW_MEMu16_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6313 VPMOVQW VPMOVQW_XMMu16_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
6314 VPMOVQW VPMOVQW_MEMu16_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_QUARTERMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6325 VPMOVQB VPMOVQB_XMMu8_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
6326 VPMOVQB VPMOVQB_MEMu8_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6327 VPMOVQB VPMOVQB_XMMu8_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
6328 VPMOVQB VPMOVQB_MEMu8_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6329 VPMOVQB VPMOVQB_XMMu8_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
6330 VPMOVQB VPMOVQB_MEMu8_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_EIGHTHMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6331 VPMOVQD VPMOVQD_YMMu32_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: MASKOP_EVEX
6332 VPMOVQD VPMOVQD_MEMu32_MASKmskw_ZMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_512 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6333 VPMOVQD VPMOVQD_XMMu32_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: MASKOP_EVEX
6334 VPMOVQD VPMOVQD_MEMu32_MASKmskw_XMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_128 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6335 VPMOVQD VPMOVQD_XMMu32_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: MASKOP_EVEX
6336 VPMOVQD VPMOVQD_MEMu32_MASKmskw_YMMu64_AVX512 DATAXFER AVX512EVEX AVX512F_256 ATTRIBUTES: DISP8_HALFMEM MASKOP_EVEX MEMORY_FAULT_SUPPRESSION
6349 VPMOVM2Q VPMOVM2Q_XMMu64_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512DQ_128 ATTRIBUTES:
6350 VPMOVM2Q VPMOVM2Q_YMMu64_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512DQ_256 ATTRIBUTES:
6351 VPMOVM2Q VPMOVM2Q_ZMMu64_MASKmskw_AVX512 DATAXFER AVX512EVEX AVX512DQ_512 ATTRIBUTES:
*/
namespace {
template <typename D, typename S>
DEF_SEM(MOVZX, D dst, S src) {
WriteZExt(dst, Read(src));
return memory;
}
template <typename D, typename S, typename SextT>
DEF_SEM(MOVSX, D dst, S src) {
WriteZExt(dst, SExtTo<SextT>(Read(src)));
return memory;
}
} // namespace
DEF_ISEL(MOVZX_GPRv_MEMb_16) = MOVZX<R16W, M8>;
DEF_ISEL(MOVZX_GPRv_MEMb_32) = MOVZX<R32W, M8>;
IF_64BIT(DEF_ISEL(MOVZX_GPRv_MEMb_64) = MOVZX<R64W, M8>;)
DEF_ISEL(MOVZX_GPRv_GPR8_16) = MOVZX<R16W, R8>;
DEF_ISEL(MOVZX_GPRv_GPR8_32) = MOVZX<R32W, R8>;
IF_64BIT(DEF_ISEL(MOVZX_GPRv_GPR8_64) = MOVZX<R64W, R8>;)
DEF_ISEL(MOVZX_GPRv_MEMw_32) = MOVZX<R32W, M16>;
IF_64BIT(DEF_ISEL(MOVZX_GPRv_MEMw_64) = MOVZX<R64W, M16>;)
DEF_ISEL(MOVZX_GPRv_GPR16_32) = MOVZX<R32W, R16>;
IF_64BIT(DEF_ISEL(MOVZX_GPRv_GPR16_64) = MOVZX<R64W, R16>;)
DEF_ISEL(MOVSX_GPRv_MEMb_16) = MOVSX<R16W, M8, int16_t>;
DEF_ISEL(MOVSX_GPRv_MEMb_32) = MOVSX<R32W, M8, int32_t>;
IF_64BIT(DEF_ISEL(MOVSX_GPRv_MEMb_64) = MOVSX<R64W, M8, int64_t>;)
DEF_ISEL(MOVSX_GPRv_GPR8_16) = MOVSX<R16W, R8, int16_t>;
DEF_ISEL(MOVSX_GPRv_GPR8_32) = MOVSX<R32W, R8, int32_t>;
IF_64BIT(DEF_ISEL(MOVSX_GPRv_GPR8_64) = MOVSX<R64W, R8, int64_t>;)
DEF_ISEL(MOVSX_GPRv_MEMw_32) = MOVSX<R32W, M16, int32_t>;
IF_64BIT(DEF_ISEL(MOVSX_GPRv_MEMw_64) = MOVSX<R64W, M16, int64_t>;)
DEF_ISEL(MOVSX_GPRv_GPR16_32) = MOVSX<R32W, R16, int32_t>;
IF_64BIT(DEF_ISEL(MOVSX_GPRv_GPR16_64) = MOVSX<R64W, R16, int64_t>;)
DEF_ISEL(MOVSXD_GPRv_GPRz_16) = MOVSX<R32W, R16, int32_t>;
DEF_ISEL(MOVSXD_GPRv_GPRz_32) = MOVSX<R32W, R32, int32_t>;
IF_64BIT(DEF_ISEL(MOVSXD_GPRv_MEMd_32) = MOVSX<R64W, M32, int64_t>;)
IF_64BIT(DEF_ISEL(MOVSXD_GPRv_GPR32_32) = MOVSX<R64W, R32, int64_t>;)
IF_64BIT(DEF_ISEL(MOVSXD_GPRv_MEMd_64) = MOVSX<R64W, M32, int64_t>;)
IF_64BIT(DEF_ISEL(MOVSXD_GPRv_MEMz_64) = MOVSX<R64W, M32, int64_t>;)
IF_64BIT(DEF_ISEL(MOVSXD_GPRv_GPR32_64) = MOVSX<R64W, R32, int64_t>;)
IF_64BIT(DEF_ISEL(MOVSXD_GPRv_GPRz_64) = MOVSX<R64W, R32, int64_t>;)
#if HAS_FEATURE_AVX512
namespace {
template <typename D, typename K, typename S>
DEF_SEM(VPMOVSXBQ_MASKmskw_SIMD128, D dst, K k1, S src) {
auto src_vec = SReadV8(src);
auto dst_vec = SClearV64(SReadV64(dst));
auto k_vec = Read(k1);
for (auto i = 0u; i < 2u; i++) {
if (READBIT(k_vec, i) == 0) {
dst_vec = SInsertV64(dst_vec, i, 0);
} else {
auto v = SExtTo<int64_t>(SExtractV8(src_vec, i));
dst_vec = SInsertV64(dst_vec, i, v);
}
}
SWriteV64(dst, dst_vec);
return memory;
}
template <typename D, typename K, typename S>
DEF_SEM(VPMOVSXWD_MASKmskw_SIMD128, D dst, K k1, S src) {
auto src_vec = SReadV16(src);
auto dst_vec = SClearV32(SReadV32(dst));
auto k_vec = Read(k1);
for (auto i = 0u; i < 4u; i++) {
if (READBIT(k_vec, i) == 0) {
dst_vec = SInsertV32(dst_vec, i, 0);
} else {
auto v = SExtTo<int32_t>(SExtractV16(src_vec, i));
dst_vec = SInsertV32(dst_vec, i, v);
}
}
SWriteV32(dst, dst_vec);
return memory;
}
template <typename S1, typename S2>
DEF_SEM(KMOVW, S1 dst, S2 src) {
WriteZExt(dst, UInt16(Read(src)));
return memory;
}
} // namespace
DEF_ISEL(VPMOVSXBQ_XMMi64_MASKmskw_MEMi8_AVX512) = VPMOVSXBQ_MASKmskw_SIMD128<VV128W, R8, MV16>;
DEF_ISEL(VPMOVSXBQ_XMMi64_MASKmskw_XMMi8_AVX512) = VPMOVSXBQ_MASKmskw_SIMD128<VV128W, R8, V128>;
DEF_ISEL(VPMOVSXWD_XMMi32_MASKmskw_MEMi16_AVX512) = VPMOVSXWD_MASKmskw_SIMD128<VV128W, R8, MV64>;
DEF_ISEL(VPMOVSXWD_XMMi32_MASKmskw_XMMi16_AVX512) = VPMOVSXWD_MASKmskw_SIMD128<VV128W, R8, V128>;
DEF_ISEL(KMOVW_MASKmskw_MASKu16_AVX512) = KMOVW<R64W, R64>;
DEF_ISEL(KMOVW_GPR32u32_MASKmskw_AVX512) = KMOVW<R32W, R64>;
DEF_ISEL(KMOVW_MASKmskw_GPR32u32_AVX512) = KMOVW<R64W, R32>;
DEF_ISEL(KMOVW_MASKmskw_MEMu16_AVX512) = KMOVW<R64W, M16>;
DEF_ISEL(KMOVW_MEMu16_MASKmskw_AVX512) = KMOVW<M16W, R64>;
#endif // HAS_FEATURE_AVX512<|fim▁end|> | auto src2_vec = FReadV32(src2);
float32v4_t temp_vec = {};
temp_vec = FInsertV32(temp_vec, 0, FExtractV32(src1_vec, 0)); |
<|file_name|>sleeper.py<|end_file_name|><|fim▁begin|>import os
import sys
import time
import itertools
def get_sleeper():
if os.isatty(sys.stdout.fileno()):
return PrettySleeper()
return Sleeper()
_PROGRESS_WIDTH = 50
_WATCHING_MESSAGE = "Watching for changes... "
_PROGRESS_BAR = [
_WATCHING_MESSAGE + "".join('>' if offset == position else ' ' for offset in range(_PROGRESS_WIDTH - len(_WATCHING_MESSAGE)))
for position in range(_PROGRESS_WIDTH - len(_WATCHING_MESSAGE))
]
_WIPE_STRING = "\b" * _PROGRESS_WIDTH<|fim▁hole|> super(PrettySleeper, self).__init__()
self._bar_iterator = itertools.cycle(_PROGRESS_BAR)
def sleep(self, seconds):
sys.stdout.write(next(self._bar_iterator))
sys.stdout.flush()
sys.stdout.write(_WIPE_STRING)
time.sleep(seconds)
def wake(self):
sys.stdout.write(" " * _PROGRESS_WIDTH)
sys.stdout.write(_WIPE_STRING)
sys.stdout.flush()<|fim▁end|> |
class PrettySleeper(object):
def __init__(self): |
<|file_name|>database.cc<|end_file_name|><|fim▁begin|>#include <string.h>
#include <node.h>
#include "macros.h"
#include "database.h"
#include "statement.h"
using namespace node_sqlite3;
Persistent<FunctionTemplate> Database::constructor_template;
void Database::Init(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew("Database"));
NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
NODE_SET_PROTOTYPE_METHOD(t, "exec", Exec);
NODE_SET_PROTOTYPE_METHOD(t, "wait", Wait);
NODE_SET_PROTOTYPE_METHOD(t, "loadExtension", LoadExtension);
NODE_SET_PROTOTYPE_METHOD(t, "serialize", Serialize);
NODE_SET_PROTOTYPE_METHOD(t, "parallelize", Parallelize);
NODE_SET_PROTOTYPE_METHOD(t, "configure", Configure);
NODE_SET_GETTER(t, "open", OpenGetter);
NanAssignPersistent(constructor_template, t);
target->Set(NanNew("Database"),
t->GetFunction());
}
void Database::Process() {
NanScope();
if (!open && locked && !queue.empty()) {
EXCEPTION(NanNew<String>("Database handle is closed"), SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception };
bool called = false;
// Call all callbacks with the error object.
while (!queue.empty()) {
Call* call = queue.front();
Local<Function> cb = NanNew(call->baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(NanObjectWrapHandle(this), cb, 1, argv);
called = true;
}
queue.pop();
// We don't call the actual callback, so we have to make sure that
// the baton gets destroyed.
delete call->baton;
delete call;
}
// When we couldn't call a callback function, emit an error on the
// Database object.
if (!called) {
Local<Value> args[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(this), 2, args);
}
return;
}
while (open && (!locked || pending == 0) && !queue.empty()) {
Call* call = queue.front();
if (call->exclusive && pending > 0) {
break;
}
queue.pop();
locked = call->exclusive;
call->callback(call->baton);
delete call;
if (locked) break;
}
}
void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) {
NanScope();
if (!open && locked) {
EXCEPTION(NanNew<String>("Database is closed"), SQLITE_MISUSE, exception);
Local<Function> cb = NanNew(baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(NanObjectWrapHandle(this), cb, 1, argv);
}
else {
Local<Value> argv[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(this), 2, argv);
}
return;
}
if (!open || ((locked || exclusive || serialize) && pending > 0)) {
queue.push(new Call(callback, baton, exclusive || serialize));
}
else {
locked = exclusive;
callback(baton);
}
}
NAN_METHOD(Database::New) {
NanScope();
if (!args.IsConstructCall()) {
return NanThrowTypeError("Use the new operator to create new Database objects");
}
REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1;
int mode;
if (args.Length() >= pos && args[pos]->IsInt32()) {
mode = args[pos++]->Int32Value();
} else {
mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
}
Local<Function> callback;
if (args.Length() >= pos && args[pos]->IsFunction()) {
callback = Local<Function>::Cast(args[pos++]);
}
Database* db = new Database();
db->Wrap(args.This());
args.This()->Set(NanNew("filename"), args[0]->ToString(), ReadOnly);
args.This()->Set(NanNew("mode"), NanNew<Integer>(mode), ReadOnly);
// Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, mode);
Work_BeginOpen(baton);
NanReturnValue(args.This());
}
void Database::Work_BeginOpen(Baton* baton) {
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_Open, (uv_after_work_cb)Work_AfterOpen);
assert(status == 0);
}
void Database::Work_Open(uv_work_t* req) {
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_open_v2(
baton->filename.c_str(),
&db->_handle,
baton->mode,
NULL
);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->_handle));
sqlite3_close(db->_handle);
db->_handle = NULL;
}
else {
// Set default database handle values.
sqlite3_busy_timeout(db->_handle, 1000);
}
}
void Database::Work_AfterOpen(uv_work_t* req) {
NanScope();
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = true;
argv[0] = NanNew(NanNull());
}
Local<Function> cb = NanNew(baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else if (!db->open) {
Local<Value> args[] = { NanNew("error"), argv[0] };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
if (db->open) {
Local<Value> args[] = { NanNew("open") };
EMIT_EVENT(NanObjectWrapHandle(db), 1, args);
db->Process();
}
delete baton;
}
NAN_GETTER(Database::OpenGetter) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
NanReturnValue(NanNew<Boolean>(db->open));
}
NAN_METHOD(Database::Close) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(Work_BeginClose, baton, true);
NanReturnValue(args.This());
}
void Database::Work_BeginClose(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
baton->db->RemoveCallbacks();
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_Close, (uv_after_work_cb)Work_AfterClose);
assert(status == 0);
}
void Database::Work_Close(uv_work_t* req) {
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_close(db->_handle);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->_handle));
}
else {
db->_handle = NULL;
}
}
void Database::Work_AfterClose(uv_work_t* req) {
NanScope();
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = false;
// Leave db->locked to indicate that this db object has reached
// the end of its life.
argv[0] = NanNew(NanNull());
}
Local<Function> cb = NanNew(baton->callback);
// Fire callbacks.
if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else if (db->open) {
Local<Value> args[] = { NanNew("error"), argv[0] };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
if (!db->open) {
Local<Value> args[] = { NanNew("close"), argv[0] };
EMIT_EVENT(NanObjectWrapHandle(db), 1, args);
db->Process();
}
delete baton;
}
NAN_METHOD(Database::Serialize) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = true;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
NanReturnValue(args.This());
}
NAN_METHOD(Database::Parallelize) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = false;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
NanReturnValue(args.This());
}
NAN_METHOD(Database::Configure) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENTS(2);
if (args[0]->Equals(NanNew("trace"))) {
Local<Function> handle;
Baton* baton = new Baton(db, handle);
db->Schedule(RegisterTraceCallback, baton);
}
else if (args[0]->Equals(NanNew("profile"))) {
Local<Function> handle;
Baton* baton = new Baton(db, handle);
db->Schedule(RegisterProfileCallback, baton);
}
else if (args[0]->Equals(NanNew("busyTimeout"))) {
if (!args[1]->IsInt32()) {
return NanThrowTypeError("Value must be an integer");
}
Local<Function> handle;
Baton* baton = new Baton(db, handle);
baton->status = args[1]->Int32Value();
db->Schedule(SetBusyTimeout, baton);
}
else {
return NanThrowError(Exception::Error(String::Concat(
args[0]->ToString(),
NanNew<String>(" is not a valid configuration option")
)));
}
db->Process();
NanReturnValue(args.This());
}
void Database::SetBusyTimeout(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
// Abuse the status field for passing the timeout.
sqlite3_busy_timeout(baton->db->_handle, baton->status);
delete baton;
}
void Database::RegisterTraceCallback(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
Database* db = baton->db;
if (db->debug_trace == NULL) {
// Add it.
db->debug_trace = new AsyncTrace(db, TraceCallback);
sqlite3_trace(db->_handle, TraceCallback, db);
}
else {
// Remove it.
sqlite3_trace(db->_handle, NULL, NULL);
db->debug_trace->finish();
db->debug_trace = NULL;
}
delete baton;
}
void Database::TraceCallback(void* db, const char* sql) {
// Note: This function is called in the thread pool.
// Note: Some queries, such as "EXPLAIN" queries, are not sent through this.
static_cast<Database*>(db)->debug_trace->send(new std::string(sql));
}
void Database::TraceCallback(Database* db, std::string* sql) {
// Note: This function is called in the main V8 thread.
NanScope();
Local<Value> argv[] = {
NanNew("trace"),
NanNew<String>(sql->c_str())
};
EMIT_EVENT(NanObjectWrapHandle(db), 2, argv);
delete sql;
}
void Database::RegisterProfileCallback(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
Database* db = baton->db;
if (db->debug_profile == NULL) {
// Add it.
db->debug_profile = new AsyncProfile(db, ProfileCallback);
sqlite3_profile(db->_handle, ProfileCallback, db);
}
else {
// Remove it.
sqlite3_profile(db->_handle, NULL, NULL);
db->debug_profile->finish();
db->debug_profile = NULL;
}
delete baton;
}
void Database::ProfileCallback(void* db, const char* sql, sqlite3_uint64 nsecs) {
// Note: This function is called in the thread pool.
// Note: Some queries, such as "EXPLAIN" queries, are not sent through this.
ProfileInfo* info = new ProfileInfo();
info->sql = std::string(sql);
info->nsecs = nsecs;
static_cast<Database*>(db)->debug_profile->send(info);
}
void Database::ProfileCallback(Database *db, ProfileInfo* info) {
NanScope();
Local<Value> argv[] = {
NanNew("profile"),
NanNew<String>(info->sql.c_str()),
NanNew<Integer>((double)info->nsecs / 1000000.0)
};
EMIT_EVENT(NanObjectWrapHandle(db), 3, argv);
delete info;
}
void Database::RegisterUpdateCallback(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
Database* db = baton->db;
if (db->update_event == NULL) {
// Add it.
db->update_event = new AsyncUpdate(db, UpdateCallback);
sqlite3_update_hook(db->_handle, UpdateCallback, db);
}
else {
// Remove it.
sqlite3_update_hook(db->_handle, NULL, NULL);
db->update_event->finish();
db->update_event = NULL;
}
delete baton;
}
void Database::UpdateCallback(void* db, int type, const char* database,
const char* table, sqlite3_int64 rowid) {
// Note: This function is called in the thread pool.
// Note: Some queries, such as "EXPLAIN" queries, are not sent through this.
UpdateInfo* info = new UpdateInfo();
info->type = type;
info->database = std::string(database);
info->table = std::string(table);
info->rowid = rowid;
static_cast<Database*>(db)->update_event->send(info);
}
void Database::UpdateCallback(Database *db, UpdateInfo* info) {
NanScope();
Local<Value> argv[] = {
NanNew(sqlite_authorizer_string(info->type)),
NanNew<String>(info->database.c_str()),
NanNew<String>(info->table.c_str()),
NanNew<Integer>(info->rowid),
};
EMIT_EVENT(NanObjectWrapHandle(db), 4, argv);
delete info;
}
NAN_METHOD(Database::Exec) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(Work_BeginExec, baton, true);
NanReturnValue(args.This());
}
void Database::Work_BeginExec(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);<|fim▁hole|> assert(baton->db->pending == 0);
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_Exec, (uv_after_work_cb)Work_AfterExec);
assert(status == 0);
}
void Database::Work_Exec(uv_work_t* req) {
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
char* message = NULL;
baton->status = sqlite3_exec(
baton->db->_handle,
baton->sql.c_str(),
NULL,
NULL,
&message
);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
}
void Database::Work_AfterExec(uv_work_t* req) {
NanScope();
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db;
Local<Function> cb = NanNew(baton->callback);
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else {
Local<Value> args[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
}
else if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { NanNew(NanNull()) };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
db->Process();
delete baton;
}
NAN_METHOD(Database::Wait) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(Work_Wait, baton, true);
NanReturnValue(args.This());
}
void Database::Work_Wait(Baton* baton) {
NanScope();
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
Local<Function> cb = NanNew(baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { NanNew(NanNull()) };
TRY_CATCH_CALL(NanObjectWrapHandle(baton->db), cb, 1, argv);
}
baton->db->Process();
delete baton;
}
NAN_METHOD(Database::LoadExtension) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, filename);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new LoadExtensionBaton(db, callback, *filename);
db->Schedule(Work_BeginLoadExtension, baton, true);
NanReturnValue(args.This());
}
void Database::Work_BeginLoadExtension(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_LoadExtension, (uv_after_work_cb)Work_AfterLoadExtension);
assert(status == 0);
}
void Database::Work_LoadExtension(uv_work_t* req) {
LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data);
sqlite3_enable_load_extension(baton->db->_handle, 1);
char* message = NULL;
baton->status = sqlite3_load_extension(
baton->db->_handle,
baton->filename.c_str(),
0,
&message
);
sqlite3_enable_load_extension(baton->db->_handle, 0);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
}
void Database::Work_AfterLoadExtension(uv_work_t* req) {
NanScope();
LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data);
Database* db = baton->db;
Local<Function> cb = NanNew(baton->callback);
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else {
Local<Value> args[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
}
else if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { NanNew(NanNull()) };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
db->Process();
delete baton;
}
void Database::RemoveCallbacks() {
if (debug_trace) {
debug_trace->finish();
debug_trace = NULL;
}
if (debug_profile) {
debug_profile->finish();
debug_profile = NULL;
}
}<|fim▁end|> | |
<|file_name|>imgsearch.py<|end_file_name|><|fim▁begin|>import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-batch-size",type=int,help="size of image batch when indexing",default=1)
parser.add_argument("--search",help="image input file for similarity search")
parser.add_argument("--search-size",help="number of nearest neighbors",type=int,default=10)
args = parser.parse_args()
def batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
def image_resize(imgfile,width):
imgquery = cv2.imread(imgfile)
r = width / imgquery.shape[1]
dim = (int(width), int(imgquery.shape[0] * r))
small = cv2.resize(imgquery,dim)
return small
host = 'localhost'
sname = 'imgserv'
description = 'image classification'
mllib = 'caffe'
mltype = 'unsupervised'
extract_layer = 'loss3/classifier'
#extract_layer = 'pool5/7x7_s1'
nclasses = 1000
layer_size = 1000 # default output code size
width = height = 224
binarized = False
dd = DD(host)
dd.set_return_format(dd.RETURN_PYTHON)
ntrees = 100
metric = 'angular' # or 'euclidean'
# creating ML service
model_repo = os.getcwd() + '/model'
model = {'repository':model_repo,'templates':'../templates/caffe/'}
parameters_input = {'connector':'image','width':width,'height':height}
parameters_mllib = {'nclasses':nclasses,'template':'googlenet'}
parameters_output = {}
dd.put_service(sname,model,description,mllib,
parameters_input,parameters_mllib,parameters_output,mltype)
# reset call params
parameters_input = {}
parameters_mllib = {'gpu':True,'extract_layer':extract_layer}
parameters_output = {'binarized':binarized}
if args.index:
try:
os.remove('names.bin')
except:
pass
s = shelve.open('names.bin')
# list files in image repository
c = 0
onlyfiles = []
for (dirpath, dirnames, filenames) in walk(args.index):
nfilenames = []
for f in filenames:
nfilenames.append(dirpath + '/' + f)
onlyfiles.extend(nfilenames)
for x in batch(onlyfiles,args.index_batch_size):
sys.stdout.write('\r'+str(c)+'/'+str(len(onlyfiles)))
sys.stdout.flush()
classif = dd.post_predict(sname,x,parameters_input,parameters_mllib,parameters_output)
for p in classif['body']['predictions']:
if c == 0:
layer_size = len(p['vals'])
s['layer_size'] = layer_size
t = AnnoyIndex(layer_size,metric) # prepare index
t.add_item(c,p['vals'])
s[str(c)] = p['uri']
c = c + 1
#if c >= 10000:
# break
print 'building index...\n'
print 'layer_size=',layer_size
t.build(ntrees)
t.save('index.ann')
s.close()
if args.search:
s = shelve.open('names.bin')
u = AnnoyIndex(s['layer_size'],metric)
u.load('index.ann')
data = [args.search]
classif = dd.post_predict(sname,data,parameters_input,parameters_mllib,parameters_output)
near = u.get_nns_by_vector(classif['body']['predictions'][0]['vals'],args.search_size,include_distances=True)
print near
near_names = []
for n in near[0]:<|fim▁hole|> cv2.waitKey(0)
for n in near_names:
cv2.imshow('res',image_resize(n,224.0))
cv2.waitKey(0)
dd.delete_service(sname,clear='')<|fim▁end|> | near_names.append(s[str(n)])
print near_names
cv2.imshow('query',image_resize(args.search,224.0)) |
<|file_name|>vc_usd_nt.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2017 Sugimoto Takaaki
#
# 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.
#
import urllib
import json
from collections import OrderedDict<|fim▁hole|>d['btc']='https://api.cryptonator.com/api/ticker/btc-usd'
d['ltc']='https://api.cryptonator.com/api/ticker/ltc-usd'
d['doge']='https://api.cryptonator.com/api/ticker/doge-usd'
d['xrp']='https://api.cryptonator.com/api/ticker/xrp-usd'
d['eth']='https://api.cryptonator.com/api/ticker/eth-usd'
d['mona']='https://api.cryptonator.com/api/ticker/mona-usd'
outputString = ""
for url in d.values():
sock = urllib.urlopen(url)
jsonString = sock.read()
sock.close()
jsonCurrency = json.loads(jsonString)
price = jsonCurrency['ticker']['price']
outputString = outputString + price + " "
print outputString<|fim▁end|> |
# dictionary of api url
d = OrderedDict() |
<|file_name|>TestEvents.js<|end_file_name|><|fim▁begin|>'use strict';
var assert = require('assert')
, TestEvents = require('../lib/TestEvents');
var wasCalled = false;
var FN = function (ev) {
wasCalled = true;
};
describe('TestEvents', function () {
beforeEach(function () {
wasCalled = false;
});
describe('#on', function () {
it('Should bind a function for an event', function () {
TestEvents.on(TestEvents.EMITTED_EVENTS, FN);
});<|fim▁hole|> });
describe('#emit', function () {
it('Should call bound function for an event', function () {
TestEvents.emit(TestEvents.EMITTED_EVENTS);
assert.equal(wasCalled, true);
});
});
})<|fim▁end|> | |
<|file_name|>FunctionReturnType.py<|end_file_name|><|fim▁begin|>from typing import Optional, List
def a(x):
# type: (List[int]) -> List[str]
return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning>
def b(x):
# type: (int) -> List[str]
return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning>
def c():
# type: () -> int
return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning>
def d(x):
# type: (x: int) -> List[str]
return [str(x)]
def e():
# type: () -> int
pass
<|fim▁hole|>def f():
# type: () -> Optional[str]
x = int(input())
if x > 0:
return <warning descr="Expected type 'Optional[str]', got 'int' instead">42</warning>
elif x == 0:
return 'abc'
else:
return
def g(x):
# type: (Any) -> int
if x:
return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning>
else:
return <warning descr="Expected type 'int', got 'dict' instead">{}</warning><|fim▁end|> | |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';
var util = require('util')
, yeoman = require('yeoman-generator')
, github = require('../lib/github')
, path = require('path')
, inflect = require('inflect');
var BBBGenerator = module.exports = function BBBGenerator(args, options, config) {
// By calling `NamedBase` here, we get the argument to the subgenerator call
// as `this.name`.
yeoman.generators.NamedBase.apply(this, arguments);
if (!this.name) {
this.log.error('You have to provide a name for the subgenerator.');
process.exit(1);
}
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'] });
// Set destination root back to project root to help with testability
this.destinationRoot('../../');
});
this.appName = this.name;
this.destPath = util.format('client/%s', this.appName);
};
util.inherits(BBBGenerator, yeoman.generators.NamedBase);
BBBGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [{
name: 'githubUser',
message: 'Tell me again your username on Github?',
default: 'someuser'
},{
name: 'appDescription',
message: 'Give this app a description',
},{
name: 'version',
message: 'What is the starting version number for this app you\'d like to use?',<|fim▁hole|>
this.prompt(prompts, function (props) {
this.githubUser = props.githubUser;
this.appDescription = props.appDescription;
this.version = props.version;
cb();
}.bind(this));
};
BBBGenerator.prototype.userInfo = function userInfo() {
var self = this
, done = this.async();
github.githubUserInfo(this.githubUser, function (res) {
/*jshint camelcase:false */
self.realname = res.name;
self.email = res.email;
self.githubUrl = res.html_url;
done();
});
};
BBBGenerator.prototype.createDestFolder = function createDestFolder() {
this.mkdir(this.destPath);
this.destinationRoot(path.join(this.destinationRoot(), this.destPath));
};
BBBGenerator.prototype.fetchBoilerplate = function fetchBoilerplate() {
var self = this
, done = this.async();
this.remote('duro', 'clutch-backbone-boilerplate', function(err, remote) {
self.sourceRoot(remote.cachePath);
done();
});
};
BBBGenerator.prototype.buildApp = function buildSkeleton() {
var self = this;
this.directory('.','.');
};<|fim▁end|> | default: '0.1.0'
}]; |
<|file_name|>commands.py<|end_file_name|><|fim▁begin|>import re, shlex
<|fim▁hole|>
from hangupsbot.utils import text_to_segments
from hangupsbot.handlers import handler, StopEventHandling
from hangupsbot.commands import command
default_bot_alias = '/bot'
def find_bot_alias(aliases_list, text):
"""Return True if text starts with bot alias"""
command = text.split()[0].lower()
for alias in aliases_list:
if alias.lower().startswith('regex:') and re.search(alias[6:], command, re.IGNORECASE):
return True
elif command == alias.lower():
return True
return False
def is_bot_alias_too_long(text):
"""check whether the bot alias is too long or not"""
if default_bot_alias in text:
return True
else:
return False
@handler.register(priority=5, event=hangups.ChatMessageEvent)
def handle_command(bot, event):
"""Handle command messages"""
# Test if message is not empty
if not event.text:
return
# Get list of bot aliases
aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases')
if not aliases_list:
aliases_list = [default_bot_alias]
# Test if message starts with bot alias
if not find_bot_alias(aliases_list, event.text):
return
# Test if command handling is enabled
if not bot.get_config_suboption(event.conv_id, 'commands_enabled'):
raise StopEventHandling
# Parse message
line_args = shlex.split(event.text, posix=False)
# Test if command length is sufficient
if len(line_args) < 2:
yield from event.conv.send_message(
text_to_segments(_('{}: 무엇을 도와드릴까요?').format(event.user.full_name))
)
raise StopEventHandling
# Test if user has permissions for running command
commands_admin_list = command.get_admin_commands(bot, event.conv_id)
if commands_admin_list and line_args[1].lower() in commands_admin_list:
admins_list = bot.get_config_suboption(event.conv_id, 'admins')
if event.user_id.chat_id not in admins_list:
yield from event.conv.send_message(
text_to_segments(_('{}: 권한이 없습니다.').format(event.user.full_name))
)
raise StopEventHandling
# Run command
yield from command.run(bot, event, *line_args[1:])
#Check whether the bot alias is too long or not
if is_bot_alias_too_long(event.text):
yield from event.conv.send_message(
text_to_segments(_('**Tip**: /bot 대신에 /b, /, ! 등을 사용할 수 있어요'))
)
# Prevent other handlers from processing event
raise StopEventHandling<|fim▁end|> | import hangups |
<|file_name|>no.js<|end_file_name|><|fim▁begin|><|fim▁hole|> For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("widget","no",{move:"Klikk og dra for å flytte",label:"%1 widget"});<|fim▁end|> | /*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. |
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. 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.
from email.mime import text
import email.utils
import smtplib
import socket
import mailjet_rest
from scoreboard import main
app = main.get_app()
class MailFailure(Exception):
"""Inability to send mail."""
pass
def send(message, subject, to, to_name=None, sender=None, sender_name=None):
"""Send an email."""
sender = sender or app.config.get('MAIL_FROM')
sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or ''
mail_provider = app.config.get('MAIL_PROVIDER')
if mail_provider is None:
app.logger.error('No MAIL_PROVIDER configured!')
raise MailFailure('No MAIL_PROVIDER configured!')
elif mail_provider == 'smtp':
_send_smtp(message, subject, to, to_name, sender, sender_name)
elif mail_provider == 'mailjet':
_send_mailjet(message, subject, to, to_name, sender, sender_name)
else:
app.logger.error('Invalid MAIL_PROVIDER configured!')
raise MailFailure('Invalid MAIL_PROVIDER configured!')
def _send_smtp(message, subject, to, to_name, sender, sender_name):
"""SMTP implementation of sending email."""
host = app.config.get('MAIL_HOST')
if not host:
raise MailFailure('SMTP Server Not Configured')
try:
server = smtplib.SMTP(host)
except (smtplib.SMTPConnectError, socket.error) as ex:
app.logger.error('Unable to send mail: %s', str(ex))
raise MailFailure('Error connecting to SMTP server.')
msg = text.MIMEText(message)
msg['Subject'] = subject
msg['To'] = email.utils.formataddr((to_name, to))
msg['From'] = email.utils.formataddr((sender_name, sender))
try:
if app.debug:
server.set_debuglevel(True)
server.sendmail(sender, [to], msg.as_string())
except (smtplib.SMTPException, socket.error) as ex:
app.logger.error('Unable to send mail: %s', str(ex))
raise MailFailure('Error sending mail to SMTP server.')
finally:
try:
server.quit()
except smtplib.SMTPException:
pass
def _send_mailjet(message, subject, to, to_name, sender, sender_name):
"""Mailjet implementation of sending email."""
api_key = app.config.get('MJ_APIKEY_PUBLIC')
api_secret = app.config.get('MJ_APIKEY_PRIVATE')
if not api_key or not api_secret:
app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!')
return
# Note the data structures we use are api v3.1
client = mailjet_rest.Client(
auth=(api_key, api_secret),
api_url='https://api.mailjet.com/',
version='v3.1')
from_obj = {
"Email": sender,
}<|fim▁hole|> from_obj["Name"] = sender_name
to_obj = [{
"Email": to,
}]
if to_name:
to_obj[0]["Name"] = to_name
message = {
"From": from_obj,
"To": to_obj,
"Subject": subject,
"TextPart": message,
}
result = client.send.create(data={'Messages': [message]})
if result.status_code != 200:
app.logger.error(
'Error sending via mailjet: (%d) %r',
result.status_code, result.text)
raise MailFailure('Error sending via mailjet!')
try:
j = result.json()
except Exception:
app.logger.error('Error sending via mailjet: %r', result.text)
raise MailFailure('Error sending via mailjet!')
if j['Messages'][0]['Status'] != 'success':
app.logger.error('Error sending via mailjet: %r', j)
raise MailFailure('Error sending via mailjet!')<|fim▁end|> | if sender_name: |
<|file_name|>main.py<|end_file_name|><|fim▁begin|>import tensorflow as tf
import tensorflow.contrib.slim as slim
import pprint
import os
from datasets import dataset_factory
from dcgan import dcgan_generator, dcgan_discriminator
from train import dcgan_train_step
from tensorflow.python.training import optimizer
from collections import OrderedDict
from utils import graph_replace
#from keras.optimizers import Adam
flags = tf.app.flags
flags.DEFINE_integer('batch_size', 128, 'The size of minibatch when training [128]')
flags.DEFINE_float('learning_rate', 2e-4, 'Learning rate of optimizer [2e-4]')
flags.DEFINE_string('optimizer', 'Adam', 'Optimizer used when training [Adam]')
flags.DEFINE_string('dataset_name', 'mnist', 'Image dataset used when trainging [mnist]')
flags.DEFINE_string('split_name', 'train', 'Split name of dataset [train]')
flags.DEFINE_string('dataset_dir', './data/mnist/', 'Path to dataset directory [./data/mnist]')
flags.DEFINE_string('checkpoint_path', None, 'Path to checkpoint path [None]')
flags.DEFINE_string('train_dir', './train', 'Path to save new training result [./train]')
flags.DEFINE_integer('max_step', 1000, 'Maximum training steps [1000]')
flags.DEFINE_integer('z_dim', 100, 'z-dim for generator [100]')
flags.DEFINE_float('beta1', 0.5, 'Beta1 for Adam optimizer [0.5]')
flags.DEFINE_float('beta2', 0.999, 'Beta2 for Adam optimizer [0.999]')
flags.DEFINE_float('epsilon', 1e-8, 'Epsilon for Adam optimizer [1e-8]')
flags.DEFINE_integer('log_every_n_steps', 10, 'Log every n training steps [10]')
flags.DEFINE_integer('save_interval_secs', 600, 'How often, in seconds, to save the model checkpoint [600]')
flags.DEFINE_integer('save_summaries_secs', 10, 'How often, in seconds, to save the summary [10]')
flags.DEFINE_integer('sample_n', 16, 'How many images the network will produce in a sample process [16]')
flags.DEFINE_integer('unrolled_step', 0, 'Unrolled step in surrogate loss for generator [0]')
def extract_update_dict(update_ops):
"""Extract the map between tensor and its updated version in update_ops"""
update_map = OrderedDict()
name_to_var = {v.name: v for v in tf.global_variables()}
for u in update_ops:
var_name = u.op.inputs[0].name
var = name_to_var[var_name]
value = u.op.inputs[1]
if u.op.type == 'Assign':
update_map[var.value()] = value
elif u.op.type == 'AssignAdd':
update_map[var.value()] = value + var
else:
raise ValueError('Undefined unroll update type %s', u.op.type)
return update_map
def main(*args):
FLAGS = flags.FLAGS
pp = pprint.PrettyPrinter(indent=4)
print('Running flags:')
pp.pprint(FLAGS.__dict__['__flags'])
tf.logging.set_verbosity('INFO')
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Graph().as_default():
provider = slim.dataset_data_provider.DatasetDataProvider(dataset_factory.get_dataset(FLAGS.dataset_name, FLAGS.split_name, FLAGS.dataset_dir),
common_queue_capacity=2*FLAGS.batch_size,
common_queue_min=FLAGS.batch_size)
[image] = provider.get(['image'])
image = tf.to_float(image)
image = tf.subtract(tf.divide(image, 127.5), 1)
z = tf.random_uniform(shape=([FLAGS.z_dim]), minval=-1, maxval=1, name='z')
label_true = tf.random_uniform(shape=([]), minval=0.7, maxval=1.2, name='label_t')
label_false = tf.random_uniform(shape=([]), minval=0, maxval=0.3, name='label_f')<|fim▁hole|> sampler_z = tf.random_uniform(shape=([FLAGS.batch_size, FLAGS.z_dim]), minval=-1, maxval=1, name='sampler_z')
[image, z, label_true, label_false] = tf.train.batch([image, z, label_true, label_false], batch_size=FLAGS.batch_size, capacity=2*FLAGS.batch_size)
generator_result = dcgan_generator(z, 'Generator', reuse=False, output_height=28, fc1_c=1024, grayscale=True)
sampler_result = dcgan_generator(sampler_z, 'Generator', reuse=True, output_height=28, fc1_c=1024, grayscale=True)
discriminator_g, g_logits = dcgan_discriminator(generator_result, 'Discriminator', reuse=False, conv2d1_c=128, grayscale=True)
discriminator_d, d_logits = dcgan_discriminator(image, 'Discriminator', reuse=True, conv2d1_c=128, grayscale=True)
d_loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_false, logits=g_logits) + \
tf.losses.sigmoid_cross_entropy(multi_class_labels=label_true, logits=d_logits)
standard_g_loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_true, logits=g_logits)
if FLAGS.optimizer == 'Adam':
g_optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate,
beta1=FLAGS.beta1,
beta2=FLAGS.beta2,
epsilon=FLAGS.epsilon,
name='g_adam')
d_optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate,
beta1=FLAGS.beta1,
beta2=FLAGS.beta2,
epsilon=FLAGS.epsilon,
name='d_adam')
#unrolled_optimizer = Adam(lr=FLAGS.learning_rate,
# beta_1=FLAGS.beta1,
# beta_2=FLAGS.beta2,
# epsilon=FLAGS.epsilon)
elif FLAGS.optimizer == 'SGD':
g_optimizer = tf.train.GradientDescentOptimizer(learning_rate=FLAGS.learning_rate,
name='g_sgd')
d_optimizer = tf.train.GradientDescentOptimizer(learning_rate=FLAGS.learning_rate,
name='d_sgd')
var_g = slim.get_variables(scope='Generator', collection=tf.GraphKeys.TRAINABLE_VARIABLES)
var_d = slim.get_variables(scope='Discriminator', collection=tf.GraphKeys.TRAINABLE_VARIABLES)
#update_ops = unrolled_optimizer.get_updates(var_d, [], d_loss)
#update_map = extract_update_dict(update_ops)
#current_update_map = update_map
#pp.pprint(current_update_map)
current_update_map = OrderedDict()
for i in xrange(FLAGS.unrolled_step):
grads_d = list(zip(tf.gradients(standard_g_loss, var_d), var_d))
update_map = OrderedDict()
for g, v in grads_d:
update_map[v.value()] = v + g * FLAGS.learning_rate
current_update_map = graph_replace(update_map, update_map)
pp.pprint(current_update_map)
if FLAGS.unrolled_step != 0:
unrolled_loss = graph_replace(standard_g_loss, current_update_map)
g_loss = unrolled_loss
else:
g_loss = standard_g_loss
generator_global_step = slim.variable("generator_global_step",
shape=[],
dtype=tf.int64,
initializer=tf.zeros_initializer,
trainable=False)
discriminator_global_step = slim.variable("discriminator_global_step",
shape=[],
dtype=tf.int64,
initializer=tf.zeros_initializer,
trainable=False)
global_step = slim.get_or_create_global_step()
with tf.name_scope('train_step'):
train_step_kwargs = {}
train_step_kwargs['g'] = generator_global_step
train_step_kwargs['d'] = discriminator_global_step
if FLAGS.max_step:
train_step_kwargs['should_stop'] = tf.greater_equal(global_step, FLAGS.max_step)
else:
train_step_kwargs['should_stop'] = tf.constant(False)
train_step_kwargs['should_log'] = tf.equal(tf.mod(global_step, FLAGS.log_every_n_steps), 0)
train_op_d = slim.learning.create_train_op(d_loss, d_optimizer, variables_to_train=var_d, global_step=discriminator_global_step)
train_op_g = slim.learning.create_train_op(g_loss, g_optimizer, variables_to_train=var_g, global_step=generator_global_step)
train_op_s = tf.assign_add(global_step, 1)
train_op = [train_op_g, train_op_d, train_op_s]
def group_image(images):
sampler_result = tf.split(images, FLAGS.batch_size // 16, axis=0)
group_sample = []
for sample in sampler_result:
unstack_sample = tf.unstack(sample, num=16, axis=0)
group_sample.append(tf.concat([tf.concat([unstack_sample[i*4+j] for j in range(4)], axis=1) for i in range(4)], axis=0))
sampler_result = tf.stack(group_sample, axis=0)
return sampler_result
sampler_result = group_image(sampler_result)
train_data = group_image(image)
tf.summary.image('sampler_z', sampler_result, max_outputs=16)
tf.summary.image('train_data', train_data, max_outputs=16)
tf.summary.scalar('loss/g_loss', g_loss)
tf.summary.scalar('loss/d_loss', d_loss)
tf.summary.scalar('loss/standard_g_loss', standard_g_loss)
tf.summary.scalar('loss/total_loss', g_loss + d_loss)
tf.summary.scalar('loss/standard_total_loss', standard_g_loss + d_loss)
if FLAGS.unrolled_step != 0:
tf.summary.scalar('loss/unrolled_loss', unrolled_loss)
saver = tf.train.Saver()
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
if FLAGS.checkpoint_path:
if not tf.train.checkpoint_exists(FLAGS.checkpoint_path):
raise ValueError('Checkpoint not exist in path ', FLAGS.checkpoint_path)
else:
restore_vars = slim.get_variables_to_restore(exclude_patterns=split(FLAGS.exclude_scope, ','))
sess.run(slim.assign_from_checkpoint(FLAGS.checkpoint_path, restore_vars, ignore_missing_vars=False))
slim.learning.train(train_op,
FLAGS.train_dir,
global_step=global_step,
train_step_fn=dcgan_train_step,
train_step_kwargs=train_step_kwargs,
saver=saver,
save_interval_secs=FLAGS.save_interval_secs,
save_summaries_secs=FLAGS.save_summaries_secs)
return
if __name__ == '__main__':
tf.app.run(main=main)<|fim▁end|> | |
<|file_name|>UnmarshalProcessorTest.java<|end_file_name|><|fim▁begin|>/**
* 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.camel.processor;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.TestSupport;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultMessage;
import org.apache.camel.spi.DataFormat;
public class UnmarshalProcessorTest extends TestSupport {
public void testDataFormatReturnsSameExchange() throws Exception {
Exchange exchange = createExchangeWithBody(new DefaultCamelContext(), "body");
Processor processor = new UnmarshalProcessor(new MyDataFormat(exchange));
processor.process(exchange);
assertEquals("UnmarshalProcessor did not copy OUT from IN message", "body", exchange.getOut().getBody());
}
public void testDataFormatReturnsAnotherExchange() throws Exception {
CamelContext context = new DefaultCamelContext();
Exchange exchange = createExchangeWithBody(context, "body");
Exchange exchange2 = createExchangeWithBody(context, "body2");
Processor processor = new UnmarshalProcessor(new MyDataFormat(exchange2));
try {<|fim▁hole|> processor.process(exchange);
fail("Should have thrown exception");
} catch (RuntimeCamelException e) {
assertEquals("The returned exchange " + exchange2 + " is not the same as " + exchange + " provided to the DataFormat", e.getMessage());
}
}
public void testDataFormatReturnsMessage() throws Exception {
Exchange exchange = createExchangeWithBody(new DefaultCamelContext(), "body");
Message out = new DefaultMessage();
out.setBody(new Object());
Processor processor = new UnmarshalProcessor(new MyDataFormat(out));
processor.process(exchange);
assertSame("UnmarshalProcessor did not make use of the returned OUT message", out, exchange.getOut());
assertSame("UnmarshalProcessor did change the body bound to the OUT message", out.getBody(), exchange.getOut().getBody());
}
public void testDataFormatReturnsBody() throws Exception {
Exchange exchange = createExchangeWithBody(new DefaultCamelContext(), "body");
Object unmarshalled = new Object();
Processor processor = new UnmarshalProcessor(new MyDataFormat(unmarshalled));
processor.process(exchange);
assertSame("UnmarshalProcessor did not make use of the returned object being returned while unmarshalling", unmarshalled, exchange.getOut().getBody());
}
private static class MyDataFormat implements DataFormat {
private final Object object;
MyDataFormat(Exchange exchange) {
object = exchange;
}
MyDataFormat(Message message) {
object = message;
}
MyDataFormat(Object unmarshalled) {
object = unmarshalled;
}
@Override
public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception {
throw new IllegalAccessException("This method is not expected to be used by UnmarshalProcessor");
}
@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
return object;
}
}
}<|fim▁end|> | |
<|file_name|>ui.py<|end_file_name|><|fim▁begin|>import os
import pygtk
pygtk.require('2.0')
import gtk
from gtkcodebuffer import CodeBuffer, SyntaxLoader
class Ui(object):
"""
The user interface. This dialog is the LaTeX input window and includes
widgets to display compilation logs and a preview. It uses GTK2 which
must be installed an importable.
"""
app_name = 'InkTeX'
help_text = r"""You can set a preamble file and scale factor in the <b>settings</b> tab. The preamble should not include <b>\documentclass</b> and <b>\begin{document}</b>.
The LaTeX code you write is only the stuff between <b>\begin{document}</b> and <b>\end{document}</b>. Compilation errors are reported in the <b>log</b> tab.
The preamble file and scale factor are stored on a per-drawing basis, so in a new document, these information must be set again."""
about_text = r"""Written by <a href="mailto:[email protected]">Jan Oliver Oelerich <[email protected]></a>"""
def __init__(self, render_callback, src, settings):
"""Takes the following parameters:
* render_callback: callback function to execute with "apply" button
* src: source code that should be pre-inserted into the LaTeX input"""
self.render_callback = render_callback
self.src = src if src else ""
self.settings = settings
# init the syntax highlighting buffer
lang = SyntaxLoader("latex")
self.syntax_buffer = CodeBuffer(lang=lang)
self.setup_ui()
def render(self, widget, data=None):
"""Extracts the input LaTeX code and calls the render callback. If that
returns true, we quit and are happy."""
buf = self.text.get_buffer()
tex = buf.get_text(buf.get_start_iter(), buf.get_end_iter())
settings = dict()
if self.preamble.get_filename():
settings['preamble'] = self.preamble.get_filename()
settings['scale'] = self.scale.get_value()
if self.render_callback(tex, settings):
gtk.main_quit()
return False
def cancel(self, widget, data=None):
"""Close button pressed: Exit"""
raise SystemExit(1)
def destroy(self, widget, event, data=None):
"""Destroy hook for the GTK window. Quit and return False."""
gtk.main_quit()
return False
def setup_ui(self):
"""Creates the actual UI."""
# create a floating toplevel window and set some title and border
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
self.window.set_title(self.app_name)
self.window.set_border_width(8)
# connect delete and destroy events
self.window.connect("destroy", self.destroy)
self.window.connect("delete-event", self.destroy)
<|fim▁hole|>
self.notebook = gtk.Notebook()
self.page_latex = gtk.HBox(False, 5)
self.page_latex.set_border_width(8)
self.page_latex.show()
self.page_log = gtk.HBox(False, 5)
self.page_log.set_border_width(8)
self.page_log.show()
self.page_settings = gtk.HBox(False, 5)
self.page_settings.set_border_width(8)
self.page_settings.show()
self.page_help = gtk.VBox(False, 5)
self.page_help.set_border_width(8)
self.page_help.show()
self.notebook.append_page(self.page_latex, gtk.Label("LaTeX"))
self.notebook.append_page(self.page_log, gtk.Label("Log"))
self.notebook.append_page(self.page_settings, gtk.Label("Settings"))
self.notebook.append_page(self.page_help, gtk.Label("Help"))
self.notebook.show()
# First component: The input text view for the LaTeX code.
# It lives in a ScrolledWindow so we can get some scrollbars when the
# text is too long.
self.text = gtk.TextView(self.syntax_buffer)
self.text.get_buffer().set_text(self.src)
self.text.show()
self.text_container = gtk.ScrolledWindow()
self.text_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.text_container.set_shadow_type(gtk.SHADOW_IN)
self.text_container.add(self.text)
self.text_container.set_size_request(400, 200)
self.text_container.show()
self.page_latex.pack_start(self.text_container)
# Second component: The log view
self.log_view = gtk.TextView()
self.log_view.show()
self.log_container = gtk.ScrolledWindow()
self.log_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.log_container.set_shadow_type(gtk.SHADOW_IN)
self.log_container.add(self.log_view)
self.log_container.set_size_request(400, 200)
self.log_container.show()
self.page_log.pack_start(self.log_container)
# third component: settings
self.settings_container = gtk.Table(2,2)
self.settings_container.set_row_spacings(8)
self.settings_container.show()
self.label_preamble = gtk.Label("Preamble")
self.label_preamble.set_alignment(0, 0.5)
self.label_preamble.show()
self.preamble = gtk.FileChooserButton("...")
if 'preamble' in self.settings and os.path.exists(self.settings['preamble']):
self.preamble.set_filename(self.settings['preamble'])
self.preamble.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
self.preamble.show()
self.settings_container.attach(self.label_preamble, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=0, bottom_attach=1)
self.settings_container.attach(self.preamble, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=0, bottom_attach=1)
self.label_scale = gtk.Label("Scale")
self.label_scale.set_alignment(0, 0.5)
self.label_scale.show()
self.scale_adjustment = gtk.Adjustment(value=1.0, lower=0, upper=100,
step_incr=0.1)
self.scale = gtk.SpinButton(adjustment=self.scale_adjustment, digits=1)
if 'scale' in self.settings:
self.scale.set_value(float(self.settings['scale']))
self.scale.show()
self.settings_container.attach(self.label_scale, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=1, bottom_attach=2)
self.settings_container.attach(self.scale, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=1, bottom_attach=2)
self.page_settings.pack_start(self.settings_container)
# help tab
self.help_label = gtk.Label()
self.help_label.set_markup(Ui.help_text)
self.help_label.set_line_wrap(True)
self.help_label.show()
self.about_label = gtk.Label()
self.about_label.set_markup(Ui.about_text)
self.about_label.set_line_wrap(True)
self.about_label.show()
self.separator_help = gtk.HSeparator()
self.separator_help.show()
self.page_help.pack_start(self.help_label)
self.page_help.pack_start(self.separator_help)
self.page_help.pack_start(self.about_label)
self.box_container.pack_start(self.notebook, True, True)
# separator between buttonbar and notebook
self.separator_buttons = gtk.HSeparator()
self.separator_buttons.show()
self.box_container.pack_start(self.separator_buttons, False, False)
# the button bar
self.box_buttons = gtk.HButtonBox()
self.box_buttons.set_layout(gtk.BUTTONBOX_END)
self.box_buttons.show()
self.button_render = gtk.Button(stock=gtk.STOCK_APPLY)
self.button_cancel = gtk.Button(stock=gtk.STOCK_CLOSE)
self.button_render.set_flags(gtk.CAN_DEFAULT)
self.button_render.connect("clicked", self.render, None)
self.button_cancel.connect("clicked", self.cancel, None)
self.button_render.show()
self.button_cancel.show()
self.box_buttons.pack_end(self.button_cancel)
self.box_buttons.pack_end(self.button_render)
self.box_container.pack_start(self.box_buttons, False, False)
self.window.add(self.box_container)
self.window.set_default(self.button_render)
self.window.show()
def log(self, msg):
buffer = self.log_view.get_buffer()
buffer.set_text(msg)
self.notebook.set_current_page(1)
def main(self):
gtk.main()<|fim▁end|> | # This is our main container, vertically ordered.
self.box_container = gtk.VBox(False, 5)
self.box_container.show() |
<|file_name|>page.cc<|end_file_name|><|fim▁begin|>#include "page.h"
using namespace AhoViewer::Booru;
#include "curler.h"
#include "image.h"
#include "settings.h"
#include "site.h"
#include "threadpool.h"
#include <glibmm/i18n.h>
#include <iostream>
#define RETRY_COUNT 5
void Page::CellRendererThumbnail::get_preferred_width_vfunc(Gtk::Widget& widget,
int& minimum_width,
int& natural_width) const
{
// Item padding is applied to right and left
auto width{ widget.get_width() /
(widget.get_width() / (Image::BooruThumbnailSize + IconViewItemPadding * 2)) };
minimum_width = width - IconViewItemPadding * 2;
natural_width = width - IconViewItemPadding * 2;
}
Page::Page()
: Gtk::ScrolledWindow{},
m_PopupMenu{ nullptr },
m_IconView{ Gtk::make_managed<IconView>() },
m_Tab{ Gtk::make_managed<Gtk::EventBox>() },
m_TabIcon{ Gtk::make_managed<Gtk::Image>(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU) },
m_TabLabel{ Gtk::make_managed<Gtk::Label>(_("New Tab")) },
m_MenuLabel{ Gtk::make_managed<Gtk::Label>(_("New Tab")) },
m_TabButton{ Gtk::make_managed<Gtk::Button>() },
m_ImageList{ std::make_shared<ImageList>(this) },
m_SaveCancel{ Gio::Cancellable::create() }
{
set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
set_shadow_type(Gtk::SHADOW_ETCHED_IN);
// Create page tab {{{
m_TabButton->add(*(Gtk::make_managed<Gtk::Image>(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU)));
m_TabButton->property_relief() = Gtk::RELIEF_NONE;
m_TabButton->set_focus_on_click(false);
m_TabButton->set_tooltip_text(_("Close Tab"));
m_TabButton->signal_clicked().connect([&]() { m_SignalClosed(this); });
m_TabLabel->set_alignment(0.0, 0.5);
m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END);
m_MenuLabel->set_alignment(0.0, 0.5);
m_MenuLabel->set_ellipsize(Pango::ELLIPSIZE_END);
auto* hbox{ Gtk::make_managed<Gtk::HBox>() };
hbox->pack_start(*m_TabIcon, false, false);
hbox->pack_start(*m_TabLabel, true, true, 2);
hbox->pack_start(*m_TabButton, false, false);
hbox->show_all();
m_Tab->set_visible_window(false);
m_Tab->add(*hbox);
m_Tab->signal_button_release_event().connect(
sigc::mem_fun(*this, &Page::on_tab_button_release_event));
// }}}
m_ScrollConn = get_vadjustment()->signal_value_changed().connect(
sigc::mem_fun(*this, &Page::on_value_changed));
m_IconView->set_column_spacing(0);
m_IconView->set_row_spacing(0);
m_IconView->set_margin(0);
m_IconView->set_item_padding(IconViewItemPadding);
m_IconView->set_model(m_ListStore);
m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE);
m_IconView->signal_selection_changed().connect(
sigc::mem_fun(*this, &Page::on_selection_changed));
m_IconView->signal_button_press_event().connect(
sigc::mem_fun(*this, &Page::on_button_press_event));
// Workaround to have fully centered pixbufs
auto* cell{ Gtk::make_managed<CellRendererThumbnail>() };
m_IconView->pack_start(*cell);
m_IconView->add_attribute(cell->property_pixbuf(), m_Columns.pixbuf);
m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded));
m_SignalSaveProgressDisp.connect([&]() { m_SignalSaveProgress(this); });
// Check if next page should be loaded after current finishes
m_ImageList->signal_thumbnails_loaded().connect([&]() {
on_selection_changed();
if (!m_KeepAligned)
on_value_changed();
});
add(*m_IconView);
show_all();
}
Page::~Page()
{
m_Curler.cancel();
if (m_GetPostsThread.joinable())
m_GetPostsThread.join();
cancel_save();
m_ListStore->clear();
}
void Page::set_pixbuf(const size_t index, const Glib::RefPtr<Gdk::Pixbuf>& pixbuf)
{
m_ScrollConn.block();
ImageList::Widget::set_pixbuf(index, pixbuf);
while (Glib::MainContext::get_default()->pending())
Glib::MainContext::get_default()->iteration(true);
m_ScrollConn.unblock();
// Only keep the thumbnail aligned if the user has not scrolled
// and the thumbnail is most likely still being loaded
if (m_KeepAligned && m_ImageList->get_index() >= index)
scroll_to_selected();
}
void Page::set_selected(const size_t index)
{
Gtk::TreePath path{ std::to_string(index) };
m_IconView->select_path(path);
scroll_to_selected();
}
void Page::scroll_to_selected()
{
std::vector<Gtk::TreePath> paths{ m_IconView->get_selected_items() };
if (!paths.empty())
{
Gtk::TreePath path{ paths[0] };
if (path)
{
m_ScrollConn.block();
m_IconView->scroll_to_path(path, false, 0, 0);
m_ScrollConn.unblock();
}
}
}
void Page::search(const std::shared_ptr<Site>& site)
{
if (!ask_cancel_save())
return;
m_Curler.cancel();
cancel_save();
m_ImageList->clear();
if (m_GetPostsThread.joinable())
m_GetPostsThread.join();
m_Site = site;
m_Page = 1;
m_LastPage = false;
m_SearchTags = m_Tags;
// Trim leading and trailing whitespace for tab label
// and m_SearchTags which is used to display tags in other places
if (!m_SearchTags.empty())
{
size_t f{ m_SearchTags.find_first_not_of(' ') }, l{ m_SearchTags.find_last_not_of(' ') };
m_SearchTags = f == std::string::npos ? "" : m_SearchTags.substr(f, l - f + 1);
}
std::string label{ m_Site->get_name() + (m_SearchTags.empty() ? "" : " - " + m_SearchTags) };
m_TabLabel->set_text(label);
m_MenuLabel->set_text(label);
m_TabIcon->set(m_Site->get_icon_pixbuf());
m_Curler.set_share_handle(m_Site->get_share_handle());
m_Curler.set_referer(m_Site->get_url());
get_posts();
}
void Page::save_image(const std::string& path, const std::shared_ptr<Image>& img)
{
m_SaveCancel->reset();
if (m_SaveImagesThread.joinable())
m_SaveImagesThread.join();
m_Saving = true;
m_SaveImagesThread = std::thread([&, path, img]() {
img->save(path);
m_Saving = false;
});
}
void Page::save_images(const std::string& path)
{
m_SaveCancel->reset();
if (m_SaveImagesThread.joinable())
m_SaveImagesThread.join();
m_Saving = true;
m_SaveImagesCurrent = 0;
m_SaveImagesTotal = m_ImageList->get_vector_size();
m_SaveImagesThread = std::thread([&, path]() {
ThreadPool pool;
for (const std::shared_ptr<AhoViewer::Image>& img : *m_ImageList)
{
pool.push([&, path, img]() {
if (m_SaveCancel->is_cancelled())
return;
std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img);
bimage->save(
Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename())));
++m_SaveImagesCurrent;
if (!m_SaveCancel->is_cancelled())
m_SignalSaveProgressDisp();
});
}
m_SignalSaveProgressDisp();
pool.wait();
m_Saving = false;
});
}
// Returns true if we want to cancel or we're not saving
bool Page::ask_cancel_save()
{
if (!m_Saving)
return true;
auto* window = static_cast<Gtk::Window*>(get_toplevel());
Gtk::MessageDialog dialog(*window,
_("Are you sure that you want to stop saving images?"),
false,
Gtk::MESSAGE_QUESTION,
Gtk::BUTTONS_YES_NO,
true);
dialog.set_secondary_text(_("Closing this tab will stop the save operation."));
return dialog.run() == Gtk::RESPONSE_YES;
}
void Page::cancel_save()
{
m_SaveCancel->cancel();
for (const std::shared_ptr<AhoViewer::Image>& img : *m_ImageList)
{
std::shared_ptr<Image> bimage{ std::static_pointer_cast<Image>(img) };
bimage->cancel_download();
}
if (m_SaveImagesThread.joinable())
m_SaveImagesThread.join();
m_Saving = false;
}
void Page::get_posts()
{
std::string tags{ m_SearchTags };
m_KeepAligned = true;
if (m_Tags.find("rating:") == std::string::npos)
{
if (Settings.get_booru_max_rating() == Rating::SAFE)
{
tags += " rating:safe";
}
else if (Settings.get_booru_max_rating() == Rating::QUESTIONABLE)<|fim▁hole|> }
tags = m_Curler.escape(tags);
m_GetPostsThread = std::thread([&, tags]() {
// DanbooruV2 doesn't give the post count with the posts
// Get it from thier counts api
if (m_Page == 1 && m_Site->get_type() == Type::DANBOORU_V2)
{
m_Curler.set_url(m_Site->get_url() + "/counts/posts.xml?tags=" + tags);
if (m_Curler.perform())
{
try
{
xml::Document doc{ reinterpret_cast<char*>(m_Curler.get_data()),
m_Curler.get_data_size() };
if (doc.get_n_nodes())
{
std::string posts_count{ doc.get_children()[0].get_value() };
// Usually when you use a wildcard operator danbooru's count api will return
// a blank value here (blank but contains some whitespace and newlines)
if (posts_count.find_first_not_of(" \n\r") != std::string::npos)
m_PostsCount = std::stoul(posts_count);
}
}
catch (const std::runtime_error& e)
{
std::cerr << e.what() << std::endl << m_Curler.get_data() << std::endl;
}
catch (const std::invalid_argument& e)
{
std::cerr << e.what() << std::endl
<< "Failed to parse posts_count" << std::endl;
}
}
else if (m_Curler.is_cancelled())
{
return;
}
}
m_Curler.set_url(m_Site->get_posts_url(tags, m_Page));
if (m_Site->get_type() == Type::GELBOORU)
m_Curler.set_cookie_file(m_Site->get_cookie());
else
m_Curler.set_http_auth(m_Site->get_username(), m_Site->get_password());
bool success{ false };
size_t retry_count{ 0 };
do
{
success = m_Curler.perform();
if (success)
{
auto [posts, posts_count, error]{ m_Site->parse_post_data(
m_Curler.get_data(), m_Curler.get_data_size()) };
m_Posts = std::move(posts);
if (posts_count > 0)
m_PostsCount = posts_count;
m_PostsError = error;
}
} while (!m_Curler.is_cancelled() && !success && ++retry_count < RETRY_COUNT);
if (!success && !m_Curler.is_cancelled())
{
std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl
<< " " << m_Curler.get_error() << std::endl;
m_PostsError =
Glib::ustring::compose(_("Failed to download posts on %1"), m_Site->get_name());
}
if (!m_Curler.is_cancelled())
m_SignalPostsDownloaded();
});
m_SignalPostsDownloadStarted();
}
bool Page::get_next_page()
{
// Do not fetch the next page if this is the last
// or the current page is still loading
if (m_LastPage || m_GetPostsThread.joinable() || m_ImageList->is_loading())
return false;
if (!m_Saving)
{
++m_Page;
get_posts();
return false;
}
else if (!m_GetNextPageConn)
{
m_GetNextPageConn =
Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000);
}
return true;
}
// Adds the downloaded posts to the image list.
void Page::on_posts_downloaded()
{
if (!m_PostsError.empty())
{
m_SignalDownloadError(m_PostsError);
}
// 401 = Unauthorized
else if (m_Curler.get_response_code() == 401)
{
auto e{ Glib::ustring::compose(
_("Failed to login as %1 on %2"), m_Site->get_username(), m_Site->get_name()) };
m_SignalDownloadError(e);
}
else
{
auto n_posts{ m_Posts.size() };
if (!m_Posts.empty())
{
auto size_before{ m_ImageList->get_vector_size() };
m_ImageList->load(m_Posts, m_PostsCount);
// Number of posts that actually got added to the image list
// ie supported file types
n_posts = m_ImageList->get_vector_size() - size_before;
}
// No posts added to the imagelist
if (n_posts == 0)
{
if (m_Page == 1)
m_SignalDownloadError(_("No results found"));
else
m_SignalOnLastPage();
m_LastPage = true;
}
}
m_Curler.clear();
m_Posts.clear();
m_GetPostsThread.join();
}
void Page::on_selection_changed()
{
std::vector<Gtk::TreePath> paths{ m_IconView->get_selected_items() };
if (!paths.empty())
{
Gtk::TreePath path{ paths[0] };
if (path)
{
size_t index = path[0];
if (index + Settings.get_int("CacheSize") >= m_ImageList->get_vector_size() - 1)
get_next_page();
m_SignalSelectedChanged(index);
}
}
}
// Vertical scrollbar value changed
void Page::on_value_changed()
{
double value = get_vadjustment()->get_value(),
limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() -
get_vadjustment()->get_step_increment() * 3;
m_KeepAligned = false;
if (value >= limit)
get_next_page();
}
bool Page::on_button_press_event(GdkEventButton* e)
{
if (e->type == GDK_BUTTON_PRESS && e->button == 3)
{
Gtk::TreePath path = m_IconView->get_path_at_pos(e->x, e->y);
if (path)
{
m_IconView->select_path(path);
m_IconView->scroll_to_path(path, false, 0, 0);
m_PopupMenu->popup_at_pointer((GdkEvent*)e);
return true;
}
}
return false;
}
bool Page::on_tab_button_release_event(GdkEventButton* e)
{
if (e->type == GDK_BUTTON_RELEASE && e->button == 2)
m_SignalClosed(this);
return false;
}<|fim▁end|> | {
tags += " -rating:explicit";
} |
<|file_name|>PRESUBMIT.py<|end_file_name|><|fim▁begin|># Copyright 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.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""
import os
import re
import sys
def _CommonChecks(input_api, output_api):
"""Performs common checks, which includes running pylint."""
results = []
old_sys_path = sys.path
try:
# Modules in tools/perf depend on telemetry.
sys.path = [os.path.join(os.pardir, 'telemetry')] + sys.path
results.extend(input_api.canned_checks.RunPylint(
input_api, output_api, black_list=[], pylintrc='pylintrc'))
results.extend(_CheckJson(input_api, output_api))
results.extend(_CheckWprShaFiles(input_api, output_api))
finally:
sys.path = old_sys_path
return results
def _CheckWprShaFiles(input_api, output_api):
"""Check whether the wpr sha files have matching URLs."""
from catapult_base import cloud_storage
results = []
for affected_file in input_api.AffectedFiles(include_deletes=False):
filename = affected_file.AbsoluteLocalPath()
if not filename.endswith('wpr.sha1'):
continue
expected_hash = cloud_storage.ReadHash(filename)
is_wpr_file_uploaded = any(
cloud_storage.Exists(bucket, expected_hash)
for bucket in cloud_storage.BUCKET_ALIASES.itervalues())
if not is_wpr_file_uploaded:
wpr_filename = filename[:-5]
results.append(output_api.PresubmitError(
'The file matching %s is not in Cloud Storage yet.\n'
'You can upload your new WPR archive file with the command:\n'
'depot_tools/upload_to_google_storage.py --bucket '
'<Your pageset\'s bucket> %s.\nFor more info: see '
'http://www.chromium.org/developers/telemetry/'
'record_a_page_set#TOC-Upload-the-recording-to-Cloud-Storage' %
(filename, wpr_filename)))
return results
def _CheckJson(input_api, output_api):
"""Checks whether JSON files in this change can be parsed."""
for affected_file in input_api.AffectedFiles(include_deletes=False):
filename = affected_file.AbsoluteLocalPath()
if os.path.splitext(filename)[1] != '.json':
continue
try:
input_api.json.load(open(filename))
except ValueError:
return [output_api.PresubmitError('Error parsing JSON in %s!' % filename)]
return []
def CheckChangeOnUpload(input_api, output_api):
report = []
report.extend(_CommonChecks(input_api, output_api))
return report
def CheckChangeOnCommit(input_api, output_api):
report = []
report.extend(_CommonChecks(input_api, output_api))
return report
def _IsBenchmarksModified(change):
"""Checks whether CL contains any modification to Telemetry benchmarks."""<|fim▁hole|> if (os.path.join('tools', 'perf', 'benchmarks') in file_path or
os.path.join('tools', 'perf', 'measurements') in file_path):
return True
return False
def PostUploadHook(cl, change, output_api):
"""git cl upload will call this hook after the issue is created/modified.
This hook adds extra try bots list to the CL description in order to run
Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL
contains any changes to Telemetry benchmarks.
"""
benchmarks_modified = _IsBenchmarksModified(change)
rietveld_obj = cl.RpcServer()
issue = cl.issue
original_description = rietveld_obj.get_description(issue)
if not benchmarks_modified or re.search(
r'^CQ_EXTRA_TRYBOTS=.*', original_description, re.M | re.I):
return []
results = []
bots = [
'linux_perf_bisect',
'mac_perf_bisect',
'win_perf_bisect',
'android_nexus5_perf_bisect'
]
bots = ['tryserver.chromium.perf:%s' % s for s in bots]
bots_string = ';'.join(bots)
description = original_description
description += '\nCQ_EXTRA_TRYBOTS=%s' % bots_string
results.append(output_api.PresubmitNotifyResult(
'Automatically added Perf trybots to run Telemetry benchmarks on CQ.'))
if description != original_description:
rietveld_obj.update_description(issue, description)
return results<|fim▁end|> | for affected_file in change.AffectedFiles():
affected_file_path = affected_file.LocalPath()
file_path, _ = os.path.splitext(affected_file_path) |
<|file_name|>test_all.rs<|end_file_name|><|fim▁begin|>//! A compiler from an LR(1) table to a [recursive ascent] parser.
//!
//! [recursive ascent]: https://en.wikipedia.org/wiki/Recursive_ascent_parser
use grammar::repr::{Grammar, NonterminalString, TypeParameter};
use lr1::core::*;
use rust::RustWrite;
use std::io::{self, Write};
use util::Sep;
use super::base::CodeGenerator;
pub fn compile<'grammar, W: Write>(grammar: &'grammar Grammar,
user_start_symbol: NonterminalString,
start_symbol: NonterminalString,
states: &[LR1State<'grammar>],
out: &mut RustWrite<W>)
-> io::Result<()> {
let mut ascent = CodeGenerator::new_test_all(grammar,
user_start_symbol,
start_symbol,
states,
out);
ascent.write()
}
struct TestAll;
impl<'ascent, 'grammar, W: Write> CodeGenerator<'ascent, 'grammar, W, TestAll> {
fn new_test_all(grammar: &'grammar Grammar,
user_start_symbol: NonterminalString,
start_symbol: NonterminalString,
states: &'ascent [LR1State<'grammar>],
out: &'ascent mut RustWrite<W>)
-> Self {
CodeGenerator::new(grammar,
user_start_symbol,
start_symbol,
states,
out,
true,
"super",
TestAll)
}
fn write(&mut self) -> io::Result<()> {
self.write_parse_mod(|this| {
try!(this.write_parser_fn());
rust!(this.out, "mod {}ascent {{", this.prefix);
try!(super::ascent::compile(this.grammar,
this.user_start_symbol,
this.start_symbol,
this.states,
"super::super::super",
this.out));
rust!(this.out,
"pub use self::{}parse{}::parse_{};",
this.prefix,
this.start_symbol,
this.user_start_symbol);
rust!(this.out, "}}");
rust!(this.out, "mod {}parse_table {{", this.prefix);
try!(super::parse_table::compile(this.grammar,
this.user_start_symbol,
this.start_symbol,
this.states,
"super::super::super",
this.out));
rust!(this.out,
"pub use self::{}parse{}::parse_{};",
this.prefix,
this.start_symbol,
this.user_start_symbol);
rust!(this.out, "}}");
Ok(())
})
}
fn write_parser_fn(&mut self) -> io::Result<()> {
try!(self.start_parser_fn());
// parse input using both methods:
try!(self.call_delegate("ascent"));
try!(self.call_delegate("parse_table"));
// check that result is the same either way:
rust!(self.out,
"assert_eq!({}ascent, {}parse_table);",
self.prefix,
self.prefix);
rust!(self.out, "return {}ascent;", self.prefix);
try!(self.end_parser_fn());
Ok(())
}
fn call_delegate(&mut self, delegate: &str) -> io::Result<()> {
let non_lifetimes: Vec<_> =
self.grammar.type_parameters
.iter()<|fim▁hole|> TypeParameter::Lifetime(_) => false,
TypeParameter::Id(_) => true,
})
.cloned()
.collect();
let parameters = if non_lifetimes.is_empty() {
String::new()
} else {
format!("::<{}>", Sep(", ", &non_lifetimes))
};
rust!(self.out,
"let {}{} = {}{}::parse_{}{}(",
self.prefix,
delegate,
self.prefix,
delegate,
self.user_start_symbol,
parameters);
for parameter in &self.grammar.parameters {
rust!(self.out, "{},", parameter.name);
}
if self.grammar.intern_token.is_none() {
rust!(self.out, "{}tokens0.clone(),", self.prefix);
}
rust!(self.out, ");");
Ok(())
}
}<|fim▁end|> | .filter(|&tp| match *tp { |
<|file_name|>fib.py<|end_file_name|><|fim▁begin|>def fib_recursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Problem: This implementation is very slow.
approximate O(2^n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
if n <= 1:
return n
else:
return fib_recursive(n-1) + fib_recursive(n-2)
# print(fib_recursive(35)) # => 9227465 (slow)
def fib_list(n):
"""[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
list_results = [0, 1]
for i in range(2, n+1):<|fim▁hole|> return list_results[n]
# print(fib_list(100)) # => 354224848179261915075
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
sum = 0
if n <= 1:
return n
for i in range(n-1):
sum = fib_1 + fib_2
fib_1 = fib_2
fib_2 = sum
return sum
# => 354224848179261915075
# print(fib_iter(100))<|fim▁end|> | list_results.append(list_results[i-1] + list_results[i-2]) |
<|file_name|>paint_context.rs<|end_file_name|><|fim▁begin|>/* 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/. */
//! Painting of display lists using Moz2D/Azure.
use gfx_traits::color;
use display_list::TextOrientation::{SidewaysLeft, SidewaysRight, Upright};
use display_list::{BLUR_INFLATION_FACTOR, BorderRadii, BoxShadowClipMode, ClippingRegion};
use display_list::{TextDisplayItem};
use filters;
use font_context::FontContext;
use text::TextRun;
use text::glyph::CharIndex;
use azure::azure::AzIntSize;
use azure::azure_hl::{AntialiasMode, Color, ColorPattern, CompositionOp};
use azure::azure_hl::{DrawOptions, DrawSurfaceOptions, DrawTarget, ExtendMode, FilterType};
use azure::azure_hl::{GaussianBlurAttribute, StrokeOptions, SurfaceFormat};
use azure::azure_hl::{GaussianBlurInput, GradientStop, Filter, FilterNode, LinearGradientPattern};
use azure::azure_hl::{JoinStyle, CapStyle};
use azure::azure_hl::{Pattern, PatternRef, Path, PathBuilder, SurfacePattern};
use azure::scaled_font::ScaledFont;
use azure::{AzFloat, struct__AzDrawOptions, struct__AzGlyph};
use azure::{struct__AzGlyphBuffer, struct__AzPoint, AzDrawTargetFillGlyphs};
use euclid::matrix2d::Matrix2D;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::side_offsets::SideOffsets2D;
use euclid::size::Size2D;
use libc::types::common::c99::uint32_t;
use msg::compositor_msg::LayerKind;
use net_traits::image::base::{Image, PixelFormat};
use std::default::Default;
use std::f32;
use std::mem;
use std::ptr;
use std::sync::Arc;
use style::computed_values::{border_style, filter, image_rendering, mix_blend_mode};
use util::geometry::{self, Au, MAX_RECT, ZERO_RECT};
use util::opts;
use util::range::Range;
pub struct PaintContext<'a> {
pub draw_target: DrawTarget,
pub font_context: &'a mut Box<FontContext>,
/// The rectangle that this context encompasses in page coordinates.
pub page_rect: Rect<f32>,
/// The rectangle that this context encompasses in screen coordinates (pixels).
pub screen_rect: Rect<usize>,
/// The clipping rect for the stacking context as a whole.
pub clip_rect: Option<Rect<Au>>,
/// The current transient clipping region, if any. A "transient clipping region" is the
/// clipping region used by the last display item. We cache the last value so that we avoid
/// pushing and popping clipping regions unnecessarily.
pub transient_clip: Option<ClippingRegion>,
/// A temporary hack to disable clipping optimizations on 3d layers.
pub layer_kind: LayerKind,
}
#[derive(Copy, Clone)]
enum Direction {
Top,
Left,
Right,
Bottom
}
#[derive(Copy, Clone)]
enum DashSize {
DottedBorder = 1,
DashedBorder = 3
}
impl<'a> PaintContext<'a> {
pub fn draw_target(&self) -> &DrawTarget {
&self.draw_target
}
pub fn draw_solid_color(&self, bounds: &Rect<Au>, color: Color) {
self.draw_target.make_current();
self.draw_target.fill_rect(&bounds.to_nearest_azure_rect(),
PatternRef::Color(&ColorPattern::new(color)),
None);
}
pub fn draw_border(&self,
bounds: &Rect<Au>,
border: &SideOffsets2D<Au>,
radius: &BorderRadii<Au>,
color: &SideOffsets2D<Color>,
style: &SideOffsets2D<border_style::T>) {
let border = border.to_float_px();
let radius = radius.to_radii_px();
self.draw_border_segment(Direction::Top, bounds, &border, &radius, color, style);
self.draw_border_segment(Direction::Right, bounds, &border, &radius, color, style);
self.draw_border_segment(Direction::Bottom, bounds, &border, &radius, color, style);
self.draw_border_segment(Direction::Left, bounds, &border, &radius, color, style);
}
pub fn draw_line(&self, bounds: &Rect<Au>, color: Color, style: border_style::T) {
self.draw_target.make_current();
self.draw_line_segment(bounds, &Default::default(), color, style);
}
pub fn draw_push_clip(&self, bounds: &Rect<Au>) {
let rect = bounds.to_nearest_azure_rect();
let path_builder = self.draw_target.create_path_builder();
let left_top = Point2D::new(rect.origin.x, rect.origin.y);
let right_top = Point2D::new(rect.origin.x + rect.size.width, rect.origin.y);
let left_bottom = Point2D::new(rect.origin.x, rect.origin.y + rect.size.height);
let right_bottom = Point2D::new(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height);
path_builder.move_to(left_top);
path_builder.line_to(right_top);
path_builder.line_to(right_bottom);
path_builder.line_to(left_bottom);
let path = path_builder.finish();
self.draw_target.push_clip(&path);
}
pub fn draw_pop_clip(&self) {
self.draw_target.pop_clip();
}
pub fn draw_image(&self,
bounds: &Rect<Au>,
stretch_size: &Size2D<Au>,
image: Arc<Image>,
image_rendering: image_rendering::T) {
let size = Size2D::new(image.width as i32, image.height as i32);
let (pixel_width, source_format) = match image.format {
PixelFormat::RGBA8 => (4, SurfaceFormat::B8G8R8A8),
PixelFormat::K8 => (1, SurfaceFormat::A8),
PixelFormat::RGB8 => panic!("RGB8 color type not supported"),
PixelFormat::KA8 => panic!("KA8 color type not supported"),
};
let stride = image.width * pixel_width;
self.draw_target.make_current();
let draw_target_ref = &self.draw_target;
let azure_surface = draw_target_ref.create_source_surface_from_data(&image.bytes,
size,
stride as i32,
source_format);
let source_rect = Rect::new(Point2D::new(0.0, 0.0),
Size2D::new(image.width as AzFloat, image.height as AzFloat));
let dest_rect = bounds.to_nearest_azure_rect();
// TODO(pcwalton): According to CSS-IMAGES-3 § 5.3, nearest-neighbor interpolation is a
// conforming implementation of `crisp-edges`, but it is not the best we could do.
// Something like Scale2x would be ideal.
let draw_surface_filter = match image_rendering {
image_rendering::T::Auto => Filter::Linear,
image_rendering::T::CrispEdges | image_rendering::T::Pixelated => Filter::Point,
};
let draw_surface_options = DrawSurfaceOptions::new(draw_surface_filter, true);
let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
<|fim▁hole|> draw_target_ref.draw_surface(azure_surface,
dest_rect,
source_rect,
draw_surface_options,
draw_options);
return
}
// Slightly slower path: No need to stretch.
//
// Annoyingly, surface patterns in Azure/Skia are relative to the top left of the *canvas*,
// not the rectangle we're drawing to. So we need to translate it explicitly.
let matrix = Matrix2D::identity().translate(dest_rect.origin.x, dest_rect.origin.y);
let stretch_size = stretch_size.to_nearest_azure_size();
if source_rect.size == stretch_size {
let pattern = SurfacePattern::new(azure_surface.azure_source_surface,
true,
true,
&matrix);
draw_target_ref.fill_rect(&dest_rect,
PatternRef::Surface(&pattern),
Some(&draw_options));
return
}
// Slow path: Both stretch and a pattern are needed.
let draw_surface_options = DrawSurfaceOptions::new(draw_surface_filter, true);
let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
let temporary_draw_target =
self.draw_target.create_similar_draw_target(&stretch_size.to_azure_int_size(),
self.draw_target.get_format());
let temporary_dest_rect = Rect::new(Point2D::new(0.0, 0.0), stretch_size);
temporary_draw_target.draw_surface(azure_surface,
temporary_dest_rect,
source_rect,
draw_surface_options,
draw_options);
let temporary_surface = temporary_draw_target.snapshot();
let pattern = SurfacePattern::new(temporary_surface.azure_source_surface,
true,
true,
&matrix);
draw_target_ref.fill_rect(&dest_rect, PatternRef::Surface(&pattern), None);
}
pub fn clear(&self) {
let pattern = ColorPattern::new(color::transparent());
let rect = Rect::new(Point2D::new(self.page_rect.origin.x as AzFloat,
self.page_rect.origin.y as AzFloat),
Size2D::new(self.screen_rect.size.width as AzFloat,
self.screen_rect.size.height as AzFloat));
let mut draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
draw_options.set_composition_op(CompositionOp::Source);
self.draw_target.make_current();
self.draw_target.fill_rect(&rect, PatternRef::Color(&pattern), Some(&draw_options));
}
fn draw_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: &SideOffsets2D<Color>,
style: &SideOffsets2D<border_style::T>) {
let (style_select, color_select) = match direction {
Direction::Top => (style.top, color.top),
Direction::Left => (style.left, color.left),
Direction::Right => (style.right, color.right),
Direction::Bottom => (style.bottom, color.bottom)
};
match style_select {
border_style::T::none | border_style::T::hidden => {}
border_style::T::dotted => {
// FIXME(sammykim): This doesn't work well with dash_pattern and cap_style.
self.draw_dashed_border_segment(direction,
bounds,
border,
radius,
color_select,
DashSize::DottedBorder);
}
border_style::T::dashed => {
self.draw_dashed_border_segment(direction,
bounds,
border,
radius,
color_select,
DashSize::DashedBorder);
}
border_style::T::solid => {
self.draw_solid_border_segment(direction, bounds, border, radius, color_select);
}
border_style::T::double => {
self.draw_double_border_segment(direction, bounds, border, radius, color_select);
}
border_style::T::groove | border_style::T::ridge => {
self.draw_groove_ridge_border_segment(direction,
bounds,
border,
radius,
color_select,
style_select);
}
border_style::T::inset | border_style::T::outset => {
self.draw_inset_outset_border_segment(direction,
bounds,
border,
radius,
color_select,
style_select);
}
}
}
fn draw_line_segment(&self,
bounds: &Rect<Au>,
radius: &BorderRadii<AzFloat>,
color: Color,
style: border_style::T) {
let border = SideOffsets2D::new_all_same(bounds.size.width).to_float_px();
match style {
border_style::T::none | border_style::T::hidden => {}
border_style::T::dotted => {
self.draw_dashed_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
DashSize::DottedBorder);
}
border_style::T::dashed => {
self.draw_dashed_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
DashSize::DashedBorder);
}
border_style::T::solid => {
self.draw_solid_border_segment(Direction::Right, bounds, &border, radius, color)
}
border_style::T::double => {
self.draw_double_border_segment(Direction::Right, bounds, &border, radius, color)
}
border_style::T::groove | border_style::T::ridge => {
self.draw_groove_ridge_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
style);
}
border_style::T::inset | border_style::T::outset => {
self.draw_inset_outset_border_segment(Direction::Right,
bounds,
&border,
radius,
color,
style);
}
}
}
fn draw_border_path(&self,
bounds: &Rect<f32>,
direction: Direction,
border: &SideOffsets2D<f32>,
radii: &BorderRadii<AzFloat>,
color: Color) {
let mut path_builder = self.draw_target.create_path_builder();
self.create_border_path_segment(&mut path_builder,
bounds,
direction,
border,
radii,
BorderPathDrawingMode::EntireBorder);
let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
self.draw_target.fill(&path_builder.finish(),
Pattern::Color(ColorPattern::new(color)).to_pattern_ref(),
&draw_options);
}
fn push_rounded_rect_clip(&self, bounds: &Rect<f32>, radii: &BorderRadii<AzFloat>) {
let mut path_builder = self.draw_target.create_path_builder();
self.create_rounded_rect_path(&mut path_builder, bounds, radii);
self.draw_target.push_clip(&path_builder.finish());
}
// The following comment is wonderful, and stolen from
// gecko:gfx/thebes/gfxContext.cpp:RoundedRectangle for reference.
//
// It does not currently apply to the code, but will be extremely useful in
// the future when the below TODO is addressed.
//
// TODO(cgaebel): Switch from arcs to beziers for drawing the corners.
// Then, add http://www.subcide.com/experiments/fail-whale/
// to the reftest suite.
//
// ---------------------------------------------------------------
//
// For CW drawing, this looks like:
//
// ...******0** 1 C
// ****
// *** 2
// **
// *
// *
// 3
// *
// *
//
// Where 0, 1, 2, 3 are the control points of the Bezier curve for
// the corner, and C is the actual corner point.
//
// At the start of the loop, the current point is assumed to be
// the point adjacent to the top left corner on the top
// horizontal. Note that corner indices start at the top left and
// continue clockwise, whereas in our loop i = 0 refers to the top
// right corner.
//
// When going CCW, the control points are swapped, and the first
// corner that's drawn is the top left (along with the top segment).
//
// There is considerable latitude in how one chooses the four
// control points for a Bezier curve approximation to an ellipse.
// For the overall path to be continuous and show no corner at the
// endpoints of the arc, points 0 and 3 must be at the ends of the
// straight segments of the rectangle; points 0, 1, and C must be
// collinear; and points 3, 2, and C must also be collinear. This
// leaves only two free parameters: the ratio of the line segments
// 01 and 0C, and the ratio of the line segments 32 and 3C. See
// the following papers for extensive discussion of how to choose
// these ratios:
//
// Dokken, Tor, et al. "Good approximation of circles by
// curvature-continuous Bezier curves." Computer-Aided
// Geometric Design 7(1990) 33--41.
// Goldapp, Michael. "Approximation of circular arcs by cubic
// polynomials." Computer-Aided Geometric Design 8(1991) 227--238.
// Maisonobe, Luc. "Drawing an elliptical arc using polylines,
// quadratic, or cubic Bezier curves."
// http://www.spaceroots.org/documents/ellipse/elliptical-arc.pdf
//
// We follow the approach in section 2 of Goldapp (least-error,
// Hermite-type approximation) and make both ratios equal to
//
// 2 2 + n - sqrt(2n + 28)
// alpha = - * ---------------------
// 3 n - 4
//
// where n = 3( cbrt(sqrt(2)+1) - cbrt(sqrt(2)-1) ).
//
// This is the result of Goldapp's equation (10b) when the angle
// swept out by the arc is pi/2, and the parameter "a-bar" is the
// expression given immediately below equation (21).
//
// Using this value, the maximum radial error for a circle, as a
// fraction of the radius, is on the order of 0.2 x 10^-3.
// Neither Dokken nor Goldapp discusses error for a general
// ellipse; Maisonobe does, but his choice of control points
// follows different constraints, and Goldapp's expression for
// 'alpha' gives much smaller radial error, even for very flat
// ellipses, than Maisonobe's equivalent.
//
// For the various corners and for each axis, the sign of this
// constant changes, or it might be 0 -- it's multiplied by the
// appropriate multiplier from the list before using.
#[allow(non_snake_case)]
fn create_border_path_segment(&self,
path_builder: &mut PathBuilder,
bounds: &Rect<f32>,
direction: Direction,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
mode: BorderPathDrawingMode) {
// T = top, B = bottom, L = left, R = right
let box_TL = bounds.origin;
let box_TR = box_TL + Point2D::new(bounds.size.width, 0.0);
let box_BL = box_TL + Point2D::new(0.0, bounds.size.height);
let box_BR = box_TL + Point2D::new(bounds.size.width, bounds.size.height);
let rad_R: AzFloat = 0.;
let rad_BR = rad_R + f32::consts::FRAC_PI_4;
let rad_B = rad_BR + f32::consts::FRAC_PI_4;
let rad_BL = rad_B + f32::consts::FRAC_PI_4;
let rad_L = rad_BL + f32::consts::FRAC_PI_4;
let rad_TL = rad_L + f32::consts::FRAC_PI_4;
let rad_T = rad_TL + f32::consts::FRAC_PI_4;
let rad_TR = rad_T + f32::consts::FRAC_PI_4;
fn dx(x: AzFloat) -> Point2D<AzFloat> {
Point2D::new(x, 0.)
}
fn dy(y: AzFloat) -> Point2D<AzFloat> {
Point2D::new(0., y)
}
fn dx_if(cond: bool, dx: AzFloat) -> Point2D<AzFloat> {
Point2D::new(if cond { dx } else { 0. }, 0.)
}
fn dy_if(cond: bool, dy: AzFloat) -> Point2D<AzFloat> {
Point2D::new(0., if cond { dy } else { 0. })
}
match direction {
Direction::Top => {
let edge_TL = box_TL + dx(radius.top_left.max(border.left));
let edge_TR = box_TR + dx(-radius.top_right.max(border.right));
let edge_BR = edge_TR + dy(border.top);
let edge_BL = edge_TL + dy(border.top);
let corner_TL = edge_TL + dx_if(radius.top_left == 0., -border.left);
let corner_TR = edge_TR + dx_if(radius.top_right == 0., border.right);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(corner_TL);
path_builder.line_to(corner_TR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_TR),
}
if radius.top_right != 0. {
// the origin is the center of the arcs we're about to draw.
let origin = edge_TR + Point2D::new((border.right - radius.top_right).max(0.),
radius.top_right);
// the elbow is the inside of the border's curve.
let distance_to_elbow = (radius.top_right - border.top).max(0.);
path_builder.arc(origin, radius.top_right, rad_T, rad_TR, false);
path_builder.arc(origin, distance_to_elbow, rad_TR, rad_T, true);
}
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(edge_BR);
path_builder.line_to(edge_BL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_BL),
}
if radius.top_left != 0. {
let origin = edge_TL + Point2D::new(-(border.left - radius.top_left).max(0.),
radius.top_left);
let distance_to_elbow = (radius.top_left - border.top).max(0.);
path_builder.arc(origin, distance_to_elbow, rad_T, rad_TL, true);
path_builder.arc(origin, radius.top_left, rad_TL, rad_T, false);
}
}
Direction::Left => {
let edge_TL = box_TL + dy(radius.top_left.max(border.top));
let edge_BL = box_BL + dy(-radius.bottom_left.max(border.bottom));
let edge_TR = edge_TL + dx(border.left);
let edge_BR = edge_BL + dx(border.left);
let corner_TL = edge_TL + dy_if(radius.top_left == 0., -border.top);
let corner_BL = edge_BL + dy_if(radius.bottom_left == 0., border.bottom);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(corner_BL);
path_builder.line_to(corner_TL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_TL),
}
if radius.top_left != 0. {
let origin = edge_TL + Point2D::new(radius.top_left,
-(border.top - radius.top_left).max(0.));
let distance_to_elbow = (radius.top_left - border.left).max(0.);
path_builder.arc(origin, radius.top_left, rad_L, rad_TL, false);
path_builder.arc(origin, distance_to_elbow, rad_TL, rad_L, true);
}
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(edge_TR);
path_builder.line_to(edge_BR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_BR),
}
if radius.bottom_left != 0. {
let origin = edge_BL +
Point2D::new(radius.bottom_left,
(border.bottom - radius.bottom_left).max(0.));
let distance_to_elbow = (radius.bottom_left - border.left).max(0.);
path_builder.arc(origin, distance_to_elbow, rad_L, rad_BL, true);
path_builder.arc(origin, radius.bottom_left, rad_BL, rad_L, false);
}
}
Direction::Right => {
let edge_TR = box_TR + dy(radius.top_right.max(border.top));
let edge_BR = box_BR + dy(-radius.bottom_right.max(border.bottom));
let edge_TL = edge_TR + dx(-border.right);
let edge_BL = edge_BR + dx(-border.right);
let corner_TR = edge_TR + dy_if(radius.top_right == 0., -border.top);
let corner_BR = edge_BR + dy_if(radius.bottom_right == 0., border.bottom);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(edge_BL);
path_builder.line_to(edge_TL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_TL),
}
if radius.top_right != 0. {
let origin = edge_TR + Point2D::new(-radius.top_right,
-(border.top - radius.top_right).max(0.));
let distance_to_elbow = (radius.top_right - border.right).max(0.);
path_builder.arc(origin, distance_to_elbow, rad_R, rad_TR, true);
path_builder.arc(origin, radius.top_right, rad_TR, rad_R, false);
}
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(corner_TR);
path_builder.line_to(corner_BR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_BR),
}
if radius.bottom_right != 0. {
let origin = edge_BR +
Point2D::new(-radius.bottom_right,
(border.bottom - radius.bottom_right).max(0.));
let distance_to_elbow = (radius.bottom_right - border.right).max(0.);
path_builder.arc(origin, radius.bottom_right, rad_R, rad_BR, false);
path_builder.arc(origin, distance_to_elbow, rad_BR, rad_R, true);
}
}
Direction::Bottom => {
let edge_BL = box_BL + dx(radius.bottom_left.max(border.left));
let edge_BR = box_BR + dx(-radius.bottom_right.max(border.right));
let edge_TL = edge_BL + dy(-border.bottom);
let edge_TR = edge_BR + dy(-border.bottom);
let corner_BR = edge_BR + dx_if(radius.bottom_right == 0., border.right);
let corner_BL = edge_BL + dx_if(radius.bottom_left == 0., -border.left);
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.move_to(edge_TL);
path_builder.line_to(edge_TR);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_TR),
}
if radius.bottom_right != 0. {
let origin = edge_BR + Point2D::new((border.right - radius.bottom_right).max(0.),
-radius.bottom_right);
let distance_to_elbow = (radius.bottom_right - border.bottom).max(0.);
path_builder.arc(origin, distance_to_elbow, rad_B, rad_BR, true);
path_builder.arc(origin, radius.bottom_right, rad_BR, rad_B, false);
}
match mode {
BorderPathDrawingMode::EntireBorder => {
path_builder.line_to(corner_BR);
path_builder.line_to(corner_BL);
}
BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_BL),
}
if radius.bottom_left != 0. {
let origin = edge_BL - Point2D::new((border.left - radius.bottom_left).max(0.),
radius.bottom_left);
let distance_to_elbow = (radius.bottom_left - border.bottom).max(0.);
path_builder.arc(origin, radius.bottom_left, rad_B, rad_BL, false);
path_builder.arc(origin, distance_to_elbow, rad_BL, rad_B, true);
}
}
}
}
/// Creates a path representing the given rounded rectangle.
///
/// TODO(pcwalton): Should we unify with the code above? It doesn't seem immediately obvious
/// how to do that (especially without regressing performance) unless we have some way to
/// efficiently intersect or union paths, since different border styles/colors can force us to
/// slice through the rounded corners. My first attempt to unify with the above code resulted
/// in making a mess of it, and the simplicity of this code path is appealing, so it may not
/// be worth it… In any case, revisit this decision when we support elliptical radii.
fn create_rounded_rect_path(&self,
path_builder: &mut PathBuilder,
bounds: &Rect<f32>,
radii: &BorderRadii<AzFloat>) {
// +----------+
// / 1 2 \
// + 8 3 +
// | |
// + 7 4 +
// \ 6 5 /
// +----------+
path_builder.move_to(Point2D::new(bounds.origin.x + radii.top_left, bounds.origin.y)); // 1
path_builder.line_to(Point2D::new(bounds.max_x() - radii.top_right, bounds.origin.y)); // 2
path_builder.arc(Point2D::new(bounds.max_x() - radii.top_right,
bounds.origin.y + radii.top_right),
radii.top_right,
1.5f32 * f32::consts::FRAC_PI_2,
2.0f32 * f32::consts::PI,
false); // 3
path_builder.line_to(Point2D::new(bounds.max_x(), bounds.max_y() - radii.bottom_right)); // 4
path_builder.arc(Point2D::new(bounds.max_x() - radii.bottom_right,
bounds.max_y() - radii.bottom_right),
radii.bottom_right,
0.0,
f32::consts::FRAC_PI_2,
false); // 5
path_builder.line_to(Point2D::new(bounds.origin.x + radii.bottom_left, bounds.max_y())); // 6
path_builder.arc(Point2D::new(bounds.origin.x + radii.bottom_left,
bounds.max_y() - radii.bottom_left),
radii.bottom_left,
f32::consts::FRAC_PI_2,
f32::consts::PI,
false); // 7
path_builder.line_to(Point2D::new(bounds.origin.x, bounds.origin.y + radii.top_left)); // 8
path_builder.arc(Point2D::new(bounds.origin.x + radii.top_left,
bounds.origin.y + radii.top_left),
radii.top_left,
f32::consts::PI,
1.5f32 * f32::consts::FRAC_PI_2,
false); // 1
}
fn draw_dashed_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: Color,
dash_size: DashSize) {
let rect = bounds.to_nearest_azure_rect();
let draw_opts = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None);
let border_width = match direction {
Direction::Top => border.top,
Direction::Left => border.left,
Direction::Right => border.right,
Direction::Bottom => border.bottom
};
let dash_pattern = [border_width * (dash_size as i32) as AzFloat,
border_width * (dash_size as i32) as AzFloat];
let stroke_opts = StrokeOptions::new(border_width as AzFloat,
JoinStyle::MiterOrBevel,
CapStyle::Butt,
10 as AzFloat,
&dash_pattern);
let (start, end) = match direction {
Direction::Top => {
let y = rect.origin.y + border.top * 0.5;
let start = Point2D::new(rect.origin.x + radius.top_left, y);
let end = Point2D::new(rect.origin.x + rect.size.width - radius.top_right, y);
(start, end)
}
Direction::Left => {
let x = rect.origin.x + border.left * 0.5;
let start = Point2D::new(x, rect.origin.y + rect.size.height - radius.bottom_left);
let end = Point2D::new(x, rect.origin.y + border.top.max(radius.top_left));
(start, end)
}
Direction::Right => {
let x = rect.origin.x + rect.size.width - border.right * 0.5;
let start = Point2D::new(x, rect.origin.y + radius.top_right);
let end = Point2D::new(x, rect.origin.y + rect.size.height - radius.bottom_right);
(start, end)
}
Direction::Bottom => {
let y = rect.origin.y + rect.size.height - border.bottom * 0.5;
let start = Point2D::new(rect.origin.x + rect.size.width - radius.bottom_right, y);
let end = Point2D::new(rect.origin.x + border.left.max(radius.bottom_left), y);
(start, end)
}
};
self.draw_target.stroke_line(start,
end,
PatternRef::Color(&ColorPattern::new(color)),
&stroke_opts,
&draw_opts);
if radii_apply_to_border_direction(direction, radius) {
let mut path_builder = self.draw_target.create_path_builder();
self.create_border_path_segment(&mut path_builder,
&rect,
direction,
border,
radius,
BorderPathDrawingMode::CornersOnly);
self.draw_target.fill(&path_builder.finish(),
Pattern::Color(ColorPattern::new(color)).to_pattern_ref(),
&draw_opts);
}
}
fn draw_solid_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: Color) {
let rect = bounds.to_nearest_azure_rect();
self.draw_border_path(&rect, direction, border, radius, color);
}
fn compute_scaled_bounds(&self,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
shrink_factor: f32) -> Rect<f32> {
let rect = bounds.to_nearest_azure_rect();
let scaled_border = SideOffsets2D::new(shrink_factor * border.top,
shrink_factor * border.right,
shrink_factor * border.bottom,
shrink_factor * border.left);
let left_top = Point2D::new(rect.origin.x, rect.origin.y);
let scaled_left_top = left_top + Point2D::new(scaled_border.left,
scaled_border.top);
return Rect::new(scaled_left_top,
Size2D::new(rect.size.width - 2.0 * scaled_border.right,
rect.size.height - 2.0 * scaled_border.bottom));
}
fn scale_color(&self, color: Color, scale_factor: f32) -> Color {
return color::new(color.r * scale_factor,
color.g * scale_factor,
color.b * scale_factor,
color.a);
}
fn draw_double_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: Color) {
let scaled_border = SideOffsets2D::new((1.0 / 3.0) * border.top,
(1.0 / 3.0) * border.right,
(1.0 / 3.0) * border.bottom,
(1.0 / 3.0) * border.left);
let inner_scaled_bounds = self.compute_scaled_bounds(bounds, border, 2.0 / 3.0);
// draw the outer portion of the double border.
self.draw_solid_border_segment(direction, bounds, &scaled_border, radius, color);
// draw the inner portion of the double border.
self.draw_border_path(&inner_scaled_bounds, direction, &scaled_border, radius, color);
}
fn draw_groove_ridge_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: Color,
style: border_style::T) {
// original bounds as a Rect<f32>, with no scaling.
let original_bounds = self.compute_scaled_bounds(bounds, border, 0.0);
// shrink the bounds by 1/2 of the border, leaving the innermost 1/2 of the border
let inner_scaled_bounds = self.compute_scaled_bounds(bounds, border, 0.5);
let scaled_border = SideOffsets2D::new(0.5 * border.top,
0.5 * border.right,
0.5 * border.bottom,
0.5 * border.left);
let is_groove = match style {
border_style::T::groove => true,
border_style::T::ridge => false,
_ => panic!("invalid border style")
};
let lighter_color;
let mut darker_color = color::black();
if color != darker_color {
darker_color = self.scale_color(color, if is_groove { 1.0 / 3.0 } else { 2.0 / 3.0 });
lighter_color = color;
} else {
// You can't scale black color (i.e. 'scaled = 0 * scale', equals black).
darker_color = color::new(0.3, 0.3, 0.3, color.a);
lighter_color = color::new(0.7, 0.7, 0.7, color.a);
}
let (outer_color, inner_color) = match (direction, is_groove) {
(Direction::Top, true) | (Direction::Left, true) |
(Direction::Right, false) | (Direction::Bottom, false) => {
(darker_color, lighter_color)
}
(Direction::Top, false) | (Direction::Left, false) |
(Direction::Right, true) | (Direction::Bottom, true) => (lighter_color, darker_color),
};
// outer portion of the border
self.draw_border_path(&original_bounds, direction, &scaled_border, radius, outer_color);
// inner portion of the border
self.draw_border_path(&inner_scaled_bounds,
direction,
&scaled_border,
radius,
inner_color);
}
fn draw_inset_outset_border_segment(&self,
direction: Direction,
bounds: &Rect<Au>,
border: &SideOffsets2D<f32>,
radius: &BorderRadii<AzFloat>,
color: Color,
style: border_style::T) {
let is_inset = match style {
border_style::T::inset => true,
border_style::T::outset => false,
_ => panic!("invalid border style")
};
// original bounds as a Rect<f32>
let original_bounds = self.compute_scaled_bounds(bounds, border, 0.0);
// You can't scale black color (i.e. 'scaled = 0 * scale', equals black).
let mut scaled_color = color::black();
if color != scaled_color {
scaled_color = match direction {
Direction::Top | Direction::Left => {
self.scale_color(color, if is_inset { 2.0 / 3.0 } else { 1.0 })
}
Direction::Right | Direction::Bottom => {
self.scale_color(color, if is_inset { 1.0 } else { 2.0 / 3.0 })
}
};
} else {
scaled_color = match direction {
Direction::Top | Direction::Left => {
if is_inset {
color::new(0.3, 0.3, 0.3, color.a)
} else {
color::new(0.7, 0.7, 0.7, color.a)
}
}
Direction::Right | Direction::Bottom => {
if is_inset {
color::new(0.7, 0.7, 0.7, color.a)
} else {
color::new(0.3, 0.3, 0.3, color.a)
}
}
};
}
self.draw_border_path(&original_bounds, direction, border, radius, scaled_color);
}
/// Draws the given text display item into the current context.
pub fn draw_text(&mut self, text: &TextDisplayItem) {
let draw_target_transform = self.draw_target.get_transform();
// Optimization: Don’t set a transform matrix for upright text, and pass a start point to
// `draw_text_into_context`.
//
// For sideways text, it’s easier to do the rotation such that its center (the baseline’s
// start point) is at (0, 0) coordinates.
let baseline_origin = match text.orientation {
Upright => text.baseline_origin,
SidewaysLeft => {
let x = text.baseline_origin.x.to_f32_px();
let y = text.baseline_origin.y.to_f32_px();
self.draw_target.set_transform(&draw_target_transform.mul(&Matrix2D::new(0., -1.,
1., 0.,
x, y)));
Point2D::zero()
}
SidewaysRight => {
let x = text.baseline_origin.x.to_f32_px();
let y = text.baseline_origin.y.to_f32_px();
self.draw_target.set_transform(&draw_target_transform.mul(&Matrix2D::new(0., 1.,
-1., 0.,
x, y)));
Point2D::zero()
}
};
// Draw the text.
let temporary_draw_target =
self.create_draw_target_for_blur_if_necessary(&text.base.bounds, text.blur_radius);
{
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let font = self.font_context.get_paint_font_from_template(
&text.text_run.font_template, text.text_run.actual_pt_size);
font
.borrow()
.draw_text(&temporary_draw_target.draw_target,
&*text.text_run,
&text.range,
baseline_origin,
text.text_color,
opts::get().enable_text_antialiasing);
}
// Blur, if necessary.
self.blur_if_necessary(temporary_draw_target, text.blur_radius);
// Undo the transform, only when we did one.
if text.orientation != Upright {
self.draw_target.set_transform(&draw_target_transform)
}
}
/// Draws a linear gradient in the given boundaries from the given start point to the given end
/// point with the given stops.
pub fn draw_linear_gradient(&self,
bounds: &Rect<Au>,
start_point: &Point2D<Au>,
end_point: &Point2D<Au>,
stops: &[GradientStop]) {
self.draw_target.make_current();
let stops = self.draw_target.create_gradient_stops(stops, ExtendMode::Clamp);
let pattern = LinearGradientPattern::new(&start_point.to_nearest_azure_point(),
&end_point.to_nearest_azure_point(),
stops,
&Matrix2D::identity());
self.draw_target.fill_rect(&bounds.to_nearest_azure_rect(),
PatternRef::LinearGradient(&pattern),
None);
}
pub fn get_or_create_temporary_draw_target(&mut self,
filters: &filter::T,
blend_mode: mix_blend_mode::T)
-> DrawTarget {
// Determine if we need a temporary draw target.
if !filters::temporary_draw_target_needed_for_style_filters(filters) &&
blend_mode == mix_blend_mode::T::normal {
// Reuse the draw target, but remove the transient clip. If we don't do the latter,
// we'll be in a state whereby the paint subcontext thinks it has no transient clip
// (see `StackingContext::optimize_and_draw_into_context`) but it actually does,
// resulting in a situation whereby display items are seemingly randomly clipped out.
self.remove_transient_clip_if_applicable();
return self.draw_target.clone()
}
// FIXME(pcwalton): This surface might be bigger than necessary and waste memory.
let size = self.draw_target.get_size(); //Az size.
let mut size = Size2D::new(size.width, size.height); //Geom::Size.
// Pre-calculate if there is a blur expansion need.
let accum_blur = filters::calculate_accumulated_blur(filters);
let mut matrix = self.draw_target.get_transform();
if accum_blur > Au(0) {
// Set the correct size.
let side_inflation = accum_blur * BLUR_INFLATION_FACTOR;
size = Size2D::new(size.width + (side_inflation.to_nearest_px() * 2) as i32,
size.height + (side_inflation.to_nearest_px() * 2) as i32);
// Calculate the transform matrix.
let old_transform = self.draw_target.get_transform();
let inflated_size = Rect::new(Point2D::new(0.0, 0.0), Size2D::new(size.width as AzFloat,
size.height as AzFloat));
let temporary_draw_target_bounds = old_transform.transform_rect(&inflated_size);
matrix = Matrix2D::identity().translate(
-temporary_draw_target_bounds.origin.x as AzFloat,
-temporary_draw_target_bounds.origin.y as AzFloat).mul(&old_transform);
}
let temporary_draw_target =
self.draw_target.create_similar_draw_target(&size, self.draw_target.get_format());
temporary_draw_target.set_transform(&matrix);
temporary_draw_target
}
/// If we created a temporary draw target, then draw it to the main draw target. This is called
/// after doing all the painting, and the temporary draw target must not be used afterward.
pub fn draw_temporary_draw_target_if_necessary(&mut self,
temporary_draw_target: &DrawTarget,
filters: &filter::T,
blend_mode: mix_blend_mode::T) {
if (*temporary_draw_target) == self.draw_target {
// We're directly painting to the surface; nothing to do.
return
}
// Set up transforms.
let old_transform = self.draw_target.get_transform();
self.draw_target.set_transform(&Matrix2D::identity());
let rect = Rect::new(Point2D::new(0.0, 0.0), self.draw_target.get_size().to_azure_size());
let rect_temporary = Rect::new(Point2D::new(0.0, 0.0), temporary_draw_target.get_size().to_azure_size());
// Create the Azure filter pipeline.
let mut accum_blur = Au(0);
let (filter_node, opacity) = filters::create_filters(&self.draw_target,
temporary_draw_target,
filters,
&mut accum_blur);
// Perform the blit operation.
let mut draw_options = DrawOptions::new(opacity, CompositionOp::Over, AntialiasMode::None);
draw_options.set_composition_op(blend_mode.to_azure_composition_op());
// If there is a blur expansion, shift the transform and update the size.
if accum_blur > Au(0) {
// Remove both the transient clip and the stacking context clip, because we may need to
// draw outside the stacking context's clip.
self.remove_transient_clip_if_applicable();
self.pop_clip_if_applicable();
debug!("######### use expanded Rect.");
self.draw_target.draw_filter(&filter_node, &rect_temporary, &rect_temporary.origin, draw_options);
self.push_clip_if_applicable();
} else {
debug!("######### use regular Rect.");
self.draw_target.draw_filter(&filter_node, &rect, &rect.origin, draw_options);
}
self.draw_target.set_transform(&old_transform);
}
/// Draws a box shadow with the given boundaries, color, offset, blur radius, and spread
/// radius. `box_bounds` represents the boundaries of the box.
pub fn draw_box_shadow(&mut self,
box_bounds: &Rect<Au>,
offset: &Point2D<Au>,
color: Color,
blur_radius: Au,
spread_radius: Au,
clip_mode: BoxShadowClipMode) {
// Remove both the transient clip and the stacking context clip, because we may need to
// draw outside the stacking context's clip.
self.remove_transient_clip_if_applicable();
self.pop_clip_if_applicable();
// If we have blur, create a new draw target.
let shadow_bounds = box_bounds.translate(offset).inflate(spread_radius, spread_radius);
let side_inflation = blur_radius * BLUR_INFLATION_FACTOR;
let inflated_shadow_bounds = shadow_bounds.inflate(side_inflation, side_inflation);
let temporary_draw_target =
self.create_draw_target_for_blur_if_necessary(&inflated_shadow_bounds, blur_radius);
let path;
match clip_mode {
BoxShadowClipMode::Inset => {
path = temporary_draw_target.draw_target
.create_rectangular_border_path(&MAX_RECT,
&shadow_bounds);
self.draw_target.push_clip(&self.draw_target.create_rectangular_path(box_bounds))
}
BoxShadowClipMode::Outset => {
path = temporary_draw_target.draw_target.create_rectangular_path(&shadow_bounds);
self.draw_target.push_clip(&self.draw_target
.create_rectangular_border_path(&MAX_RECT,
box_bounds))
}
BoxShadowClipMode::None => {
path = temporary_draw_target.draw_target.create_rectangular_path(&shadow_bounds)
}
}
// Draw the shadow, and blur if we need to.
temporary_draw_target.draw_target.fill(&path,
Pattern::Color(ColorPattern::new(color)).to_pattern_ref(),
&DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None));
self.blur_if_necessary(temporary_draw_target, blur_radius);
// Undo the draw target's clip if we need to, and push back the stacking context clip.
if clip_mode != BoxShadowClipMode::None {
self.draw_target.pop_clip()
}
self.push_clip_if_applicable();
}
/// If we have blur, create a new draw target that's the same size as this tile, but with
/// enough space around the edges to hold the entire blur. (If we don't do the latter, then
/// there will be seams between tiles.)
fn create_draw_target_for_blur_if_necessary(&self, box_bounds: &Rect<Au>, blur_radius: Au)
-> TemporaryDrawTarget {
if blur_radius == Au(0) {
return TemporaryDrawTarget::from_main_draw_target(&self.draw_target)
}
// Intersect display item bounds with the tile bounds inflated by blur radius to get the
// smallest possible rectangle that encompasses all the paint.
let side_inflation = blur_radius * BLUR_INFLATION_FACTOR;
let tile_box_bounds =
geometry::f32_rect_to_au_rect(self.page_rect).intersection(box_bounds)
.unwrap_or(ZERO_RECT)
.inflate(side_inflation, side_inflation);
TemporaryDrawTarget::from_bounds(&self.draw_target, &tile_box_bounds)
}
/// Performs a blur using the draw target created in
/// `create_draw_target_for_blur_if_necessary`.
fn blur_if_necessary(&self, temporary_draw_target: TemporaryDrawTarget, blur_radius: Au) {
if blur_radius == Au(0) {
return
}
let blur_filter = self.draw_target.create_filter(FilterType::GaussianBlur);
blur_filter.set_attribute(GaussianBlurAttribute::StdDeviation(blur_radius.to_f64_px() as
AzFloat));
blur_filter.set_input(GaussianBlurInput, &temporary_draw_target.draw_target.snapshot());
temporary_draw_target.draw_filter(&self.draw_target, blur_filter);
}
pub fn push_clip_if_applicable(&self) {
if let Some(ref clip_rect) = self.clip_rect {
self.draw_push_clip(clip_rect)
}
}
pub fn pop_clip_if_applicable(&self) {
if self.clip_rect.is_some() {
self.draw_pop_clip()
}
}
pub fn remove_transient_clip_if_applicable(&mut self) {
if let Some(old_transient_clip) = mem::replace(&mut self.transient_clip, None) {
for _ in &old_transient_clip.complex {
self.draw_pop_clip()
}
self.draw_pop_clip()
}
}
/// Sets a new transient clipping region. Automatically calls
/// `remove_transient_clip_if_applicable()` first.
pub fn push_transient_clip(&mut self, clip_region: ClippingRegion) {
self.remove_transient_clip_if_applicable();
self.draw_push_clip(&clip_region.main);
for complex_region in &clip_region.complex {
// FIXME(pcwalton): Actually draw a rounded rect.
self.push_rounded_rect_clip(&complex_region.rect.to_nearest_azure_rect(),
&complex_region.radii.to_radii_px())
}
self.transient_clip = Some(clip_region)
}
}
pub trait ToAzurePoint {
fn to_nearest_azure_point(&self) -> Point2D<AzFloat>;
fn to_azure_point(&self) -> Point2D<AzFloat>;
}
impl ToAzurePoint for Point2D<Au> {
fn to_nearest_azure_point(&self) -> Point2D<AzFloat> {
Point2D::new(self.x.to_nearest_px() as AzFloat, self.y.to_nearest_px() as AzFloat)
}
fn to_azure_point(&self) -> Point2D<AzFloat> {
Point2D::new(self.x.to_f32_px(), self.y.to_f32_px())
}
}
pub trait ToAzureRect {
fn to_nearest_azure_rect(&self) -> Rect<AzFloat>;
fn to_azure_rect(&self) -> Rect<AzFloat>;
}
impl ToAzureRect for Rect<Au> {
fn to_nearest_azure_rect(&self) -> Rect<AzFloat> {
Rect::new(self.origin.to_nearest_azure_point(), self.size.to_nearest_azure_size())
}
fn to_azure_rect(&self) -> Rect<AzFloat> {
Rect::new(self.origin.to_azure_point(), self.size.to_azure_size())
}
}
pub trait ToAzureSize {
fn to_nearest_azure_size(&self) -> Size2D<AzFloat>;
fn to_azure_size(&self) -> Size2D<AzFloat>;
}
impl ToAzureSize for Size2D<Au> {
fn to_nearest_azure_size(&self) -> Size2D<AzFloat> {
Size2D::new(self.width.to_nearest_px() as AzFloat, self.height.to_nearest_px() as AzFloat)
}
fn to_azure_size(&self) -> Size2D<AzFloat> {
Size2D::new(self.width.to_f32_px(), self.height.to_f32_px())
}
}
impl ToAzureSize for AzIntSize {
fn to_nearest_azure_size(&self) -> Size2D<AzFloat> {
Size2D::new(self.width as AzFloat, self.height as AzFloat)
}
fn to_azure_size(&self) -> Size2D<AzFloat> {
Size2D::new(self.width as AzFloat, self.height as AzFloat)
}
}
trait ToAzureIntSize {
fn to_azure_int_size(&self) -> Size2D<i32>;
}
impl ToAzureIntSize for Size2D<Au> {
fn to_azure_int_size(&self) -> Size2D<i32> {
Size2D::new(self.width.to_nearest_px() as i32, self.height.to_nearest_px() as i32)
}
}
impl ToAzureIntSize for Size2D<AzFloat> {
fn to_azure_int_size(&self) -> Size2D<i32> {
Size2D::new(self.width as i32, self.height as i32)
}
}
impl ToAzureIntSize for Size2D<i32> {
fn to_azure_int_size(&self) -> Size2D<i32> {
Size2D::new(self.width, self.height)
}
}
trait ToSideOffsetsPx {
fn to_float_px(&self) -> SideOffsets2D<AzFloat>;
}
impl ToSideOffsetsPx for SideOffsets2D<Au> {
fn to_float_px(&self) -> SideOffsets2D<AzFloat> {
SideOffsets2D::new(self.top.to_nearest_px() as AzFloat,
self.right.to_nearest_px() as AzFloat,
self.bottom.to_nearest_px() as AzFloat,
self.left.to_nearest_px() as AzFloat)
}
}
trait ToRadiiPx {
fn to_radii_px(&self) -> BorderRadii<AzFloat>;
}
impl ToRadiiPx for BorderRadii<Au> {
fn to_radii_px(&self) -> BorderRadii<AzFloat> {
fn to_nearest_px(x: Au) -> AzFloat {
x.to_nearest_px() as AzFloat
}
BorderRadii {
top_left: to_nearest_px(self.top_left),
top_right: to_nearest_px(self.top_right),
bottom_left: to_nearest_px(self.bottom_left),
bottom_right: to_nearest_px(self.bottom_right),
}
}
}
trait ScaledFontExtensionMethods {
fn draw_text(&self,
draw_target: &DrawTarget,
run: &TextRun,
range: &Range<CharIndex>,
baseline_origin: Point2D<Au>,
color: Color,
antialias: bool);
}
impl ScaledFontExtensionMethods for ScaledFont {
fn draw_text(&self,
draw_target: &DrawTarget,
run: &TextRun,
range: &Range<CharIndex>,
baseline_origin: Point2D<Au>,
color: Color,
antialias: bool) {
let pattern = ColorPattern::new(color);
let azure_pattern = pattern.azure_color_pattern;
assert!(!azure_pattern.is_null());
let mut options = struct__AzDrawOptions {
mAlpha: 1f64 as AzFloat,
mCompositionOp: CompositionOp::Over as u8,
mAntialiasMode: if antialias { AntialiasMode::Subpixel as u8 }
else { AntialiasMode::None as u8 }
};
let mut origin = baseline_origin.clone();
let mut azglyphs = vec!();
azglyphs.reserve(range.length().to_usize());
for slice in run.natural_word_slices_in_visual_order(range) {
for (_i, glyph) in slice.glyphs.iter_glyphs_for_char_range(&slice.range) {
let glyph_advance = glyph.advance();
let glyph_offset = glyph.offset().unwrap_or(Point2D::zero());
let azglyph = struct__AzGlyph {
mIndex: glyph.id() as uint32_t,
mPosition: struct__AzPoint {
x: (origin.x + glyph_offset.x).to_f32_px(),
y: (origin.y + glyph_offset.y).to_f32_px(),
}
};
origin = Point2D::new(origin.x + glyph_advance, origin.y);
azglyphs.push(azglyph)
};
}
let azglyph_buf_len = azglyphs.len();
if azglyph_buf_len == 0 { return; } // Otherwise the Quartz backend will assert.
let mut glyphbuf = struct__AzGlyphBuffer {
mGlyphs: azglyphs.as_mut_ptr(),
mNumGlyphs: azglyph_buf_len as uint32_t
};
unsafe {
// TODO(Issue #64): this call needs to move into azure_hl.rs
AzDrawTargetFillGlyphs(draw_target.azure_draw_target,
self.get_ref(),
&mut glyphbuf,
azure_pattern,
&mut options,
ptr::null_mut());
}
}
}
trait DrawTargetExtensions {
/// Creates and returns a path that represents a rectangular border. Like this:
///
/// ```text
/// +--------------------------------+
/// |################################|
/// |#######+---------------------+##|
/// |#######| |##|
/// |#######+---------------------+##|
/// |################################|
/// +--------------------------------+
/// ```
fn create_rectangular_border_path<T>(&self, outer_rect: &T, inner_rect: &T)
-> Path
where T: ToAzureRect;
/// Creates and returns a path that represents a rectangle.
fn create_rectangular_path(&self, rect: &Rect<Au>) -> Path;
}
impl DrawTargetExtensions for DrawTarget {
fn create_rectangular_border_path<T>(&self, outer_rect: &T, inner_rect: &T)
-> Path
where T: ToAzureRect {
// +-----------+
// |2 |1
// | |
// | +---+---+
// | |9 |6 |5, 10
// | | | |
// | +---+ |
// | 8 7 |
// | |
// +-----------+
// 3 4
let (outer_rect, inner_rect) = (outer_rect.to_nearest_azure_rect(), inner_rect.to_nearest_azure_rect());
let path_builder = self.create_path_builder();
path_builder.move_to(Point2D::new(outer_rect.max_x(), outer_rect.origin.y)); // 1
path_builder.line_to(Point2D::new(outer_rect.origin.x, outer_rect.origin.y)); // 2
path_builder.line_to(Point2D::new(outer_rect.origin.x, outer_rect.max_y())); // 3
path_builder.line_to(Point2D::new(outer_rect.max_x(), outer_rect.max_y())); // 4
path_builder.line_to(Point2D::new(outer_rect.max_x(), inner_rect.origin.y)); // 5
path_builder.line_to(Point2D::new(inner_rect.max_x(), inner_rect.origin.y)); // 6
path_builder.line_to(Point2D::new(inner_rect.max_x(), inner_rect.max_y())); // 7
path_builder.line_to(Point2D::new(inner_rect.origin.x, inner_rect.max_y())); // 8
path_builder.line_to(inner_rect.origin); // 9
path_builder.line_to(Point2D::new(outer_rect.max_x(), inner_rect.origin.y)); // 10
path_builder.finish()
}
fn create_rectangular_path(&self, rect: &Rect<Au>) -> Path {
let rect = rect.to_nearest_azure_rect();
let path_builder = self.create_path_builder();
path_builder.move_to(rect.origin);
path_builder.line_to(Point2D::new(rect.max_x(), rect.origin.y));
path_builder.line_to(Point2D::new(rect.max_x(), rect.max_y()));
path_builder.line_to(Point2D::new(rect.origin.x, rect.max_y()));
path_builder.finish()
}
}
/// Converts a CSS blend mode (per CSS-COMPOSITING) to an Azure `CompositionOp`.
trait ToAzureCompositionOp {
/// Converts a CSS blend mode (per CSS-COMPOSITING) to an Azure `CompositionOp`.
fn to_azure_composition_op(&self) -> CompositionOp;
}
impl ToAzureCompositionOp for mix_blend_mode::T {
fn to_azure_composition_op(&self) -> CompositionOp {
match *self {
mix_blend_mode::T::normal => CompositionOp::Over,
mix_blend_mode::T::multiply => CompositionOp::Multiply,
mix_blend_mode::T::screen => CompositionOp::Screen,
mix_blend_mode::T::overlay => CompositionOp::Overlay,
mix_blend_mode::T::darken => CompositionOp::Darken,
mix_blend_mode::T::lighten => CompositionOp::Lighten,
mix_blend_mode::T::color_dodge => CompositionOp::ColorDodge,
mix_blend_mode::T::color_burn => CompositionOp::ColorBurn,
mix_blend_mode::T::hard_light => CompositionOp::HardLight,
mix_blend_mode::T::soft_light => CompositionOp::SoftLight,
mix_blend_mode::T::difference => CompositionOp::Difference,
mix_blend_mode::T::exclusion => CompositionOp::Exclusion,
mix_blend_mode::T::hue => CompositionOp::Hue,
mix_blend_mode::T::saturation => CompositionOp::Saturation,
mix_blend_mode::T::color => CompositionOp::Color,
mix_blend_mode::T::luminosity => CompositionOp::Luminosity,
}
}
}
/// Represents a temporary drawing surface. Some operations that perform complex compositing
/// operations need this.
struct TemporaryDrawTarget {
/// The draw target.
draw_target: DrawTarget,
/// The distance from the top left of the main draw target to the top left of this temporary
/// draw target.
offset: Point2D<AzFloat>,
}
impl TemporaryDrawTarget {
/// Creates a temporary draw target that simply draws to the main draw target.
fn from_main_draw_target(main_draw_target: &DrawTarget) -> TemporaryDrawTarget {
TemporaryDrawTarget {
draw_target: main_draw_target.clone(),
offset: Point2D::new(0.0, 0.0),
}
}
/// Creates a temporary draw target large enough to encompass the given bounding rect in page
/// coordinates. The temporary draw target will have the same transform as the tile we're
/// drawing to.
fn from_bounds(main_draw_target: &DrawTarget, bounds: &Rect<Au>) -> TemporaryDrawTarget {
let draw_target_transform = main_draw_target.get_transform();
let temporary_draw_target_bounds =
draw_target_transform.transform_rect(&bounds.to_azure_rect());
let temporary_draw_target_size =
Size2D::new(temporary_draw_target_bounds.size.width.ceil() as i32,
temporary_draw_target_bounds.size.height.ceil() as i32);
let temporary_draw_target =
main_draw_target.create_similar_draw_target(&temporary_draw_target_size,
main_draw_target.get_format());
let matrix =
Matrix2D::identity().translate(-temporary_draw_target_bounds.origin.x as AzFloat,
-temporary_draw_target_bounds.origin.y as AzFloat)
.mul(&draw_target_transform);
temporary_draw_target.set_transform(&matrix);
TemporaryDrawTarget {
draw_target: temporary_draw_target,
offset: temporary_draw_target_bounds.origin,
}
}
/// Composites this temporary draw target onto the main surface, with the given Azure filter.
fn draw_filter(self, main_draw_target: &DrawTarget, filter: FilterNode) {
let main_draw_target_transform = main_draw_target.get_transform();
let temporary_draw_target_size = self.draw_target.get_size();
let temporary_draw_target_size = Size2D::new(temporary_draw_target_size.width as AzFloat,
temporary_draw_target_size.height as AzFloat);
// Blit the blur onto the tile. We undo the transforms here because we want to directly
// stack the temporary draw target onto the tile.
main_draw_target.set_transform(&Matrix2D::identity());
main_draw_target.draw_filter(&filter,
&Rect::new(Point2D::new(0.0, 0.0), temporary_draw_target_size),
&self.offset,
DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None));
main_draw_target.set_transform(&main_draw_target_transform);
}
}
#[derive(Copy, Clone, PartialEq)]
enum BorderPathDrawingMode {
EntireBorder,
CornersOnly,
}
fn radii_apply_to_border_direction(direction: Direction, radius: &BorderRadii<AzFloat>) -> bool {
match (direction, radius.top_left, radius.top_right, radius.bottom_left, radius.bottom_right) {
(Direction::Top, a, b, _, _) |
(Direction::Right, _, a, _, b) |
(Direction::Bottom, _, _, a, b) |
(Direction::Left, a, _, b, _) => a != 0.0 || b != 0.0,
}
}<|fim▁end|> | // Fast path: No need to create a pattern.
if bounds.size == *stretch_size { |
<|file_name|>OperatorExpression.java<|end_file_name|><|fim▁begin|>package org.poormanscastle.studies.compilers.grammar.grammar3_1.astparser.ast;
import org.poormanscastle.studies.compilers.utils.grammartools.ast.CodePosition;
/**
* Created by georg on 15.01.16.
*/
public class OperatorExpression extends AbstractAstItem implements Expression {
private final Expression leftOperand, rightOperand;
private final Operator operator;
public OperatorExpression(CodePosition codePosition, Expression leftOperand, Operator operator, Expression rightOperand) {
super(codePosition);
this.leftOperand = leftOperand;
this.rightOperand = rightOperand;
this.operator = operator;
}
public Expression getLeftOperand() {
return leftOperand;
}
public Expression getRightOperand() {
return rightOperand;
}
public Operator getOperator() {
return operator;
}<|fim▁hole|> return visitor.proceedWithOperatorExpression(this);
}
@Override
public void accept(AstItemVisitor visitor) {
visitor.visitOperatorExpression(this);
if (leftOperand.handleProceedWith(visitor)) {
leftOperand.accept(visitor);
}
if (rightOperand.handleProceedWith(visitor)) {
rightOperand.accept(visitor);
}
visitor.leaveOperatorExpression(this);
}
}<|fim▁end|> |
@Override
public boolean handleProceedWith(AstItemVisitor visitor) { |
<|file_name|>rest_client.py<|end_file_name|><|fim▁begin|>import time
import requests
from .exceptions import HttpError
from .json import json_loads
def check_rep(rep):
if (rep.status_code // 100) != 2:
raise HttpError(rep.text, rep.status_code)
def rep_to_json(rep):
check_rep(rep)
# we use our json loads for date parsing
return json_loads(rep.text)
class RestClient:
MAX_ITERATIONS = 100
def __init__(
self,
url,
login,
password,
verify_ssl=True
):
self.base_url = url.strip("/")
self.session = requests.Session()
self.session.auth = (login, password)
self.verify_ssl = verify_ssl
def list(self, path, params=None):<|fim▁hole|> f"{self.base_url}/{path}/",
params=params,
verify=self.verify_ssl)
return rep_to_json(rep)
def retrieve(self, path, resource_id):
rep = self.session.get(
f"{self.base_url}/{path}/{resource_id}/",
verify=self.verify_ssl)
return rep_to_json(rep)
def create(self, path, data):
rep = self.session.post(
f"{self.base_url}/{path}/",
json=data,
verify=self.verify_ssl)
return rep_to_json(rep)
def partial_update(self, path, resource_id, data):
rep = self.session.patch(
f"{self.base_url}/{path}/{resource_id}/",
json=data,
verify=self.verify_ssl)
return rep_to_json(rep)
def update(self, path, resource_id, data):
rep = self.session.put(
f"{self.base_url}/{path}/{resource_id}/",
json=data,
verify=self.verify_ssl)
return rep_to_json(rep)
def detail_action(
self,
path,
resource_id,
http_method,
action_name,
params=None,
data=None,
return_json=True,
send_json=True):
rep = getattr(self.session, http_method.lower())(
f"{self.base_url}/{path}/{resource_id}/{action_name}/",
params=params,
json=data if send_json else None,
data=None if send_json else data,
verify=self.verify_ssl
)
if rep.status_code == 204:
return
if return_json:
return rep_to_json(rep)
check_rep(rep)
return rep.content
def list_action(
self,
path,
http_method,
action_name,
params=None,
data=None,
return_json=True,
send_json=True):
rep = getattr(self.session, http_method.lower())(
f"{self.base_url}/{path}/{action_name}/",
params=params,
json=data if send_json else None,
data=None if send_json else data,
verify=self.verify_ssl
)
if rep.status_code == 204:
return
if return_json:
return rep_to_json(rep)
check_rep(rep)
return rep.content
def destroy(self, path, resource_id, params=None):
rep = self.session.delete(
f"{self.base_url}/{path}/{resource_id}/",
params=params,
verify=self.verify_ssl)
if rep.status_code == 204:
return
return rep_to_json(rep)
def wait_for_on(self, timeout=10, freq=1):
start = time.time()
if timeout <= 0:
raise ValueError
while True:
if (time.time() - start) > timeout:
raise TimeoutError
try:
rep = self.session.get(
f"{self.base_url}/oteams/projects/",
params=dict(empty=True),
verify=self.verify_ssl)
if rep.status_code == 503:
raise TimeoutError
break
except (requests.exceptions.ConnectionError, TimeoutError):
pass
time.sleep(freq)<|fim▁end|> | rep = self.session.get( |
<|file_name|>lexer.js<|end_file_name|><|fim▁begin|>/*
* THIS FILE IS AUTO GENERATED FROM 'lib/lex/lexer.kep'
* DO NOT EDIT
*/
define(["require", "exports", "bennu/parse", "bennu/lang", "nu-stream/stream", "ecma-ast/token", "ecma-ast/position",
"./boolean_lexer", "./comment_lexer", "./identifier_lexer", "./line_terminator_lexer", "./null_lexer",
"./number_lexer", "./punctuator_lexer", "./reserved_word_lexer", "./string_lexer", "./whitespace_lexer",
"./regular_expression_lexer"
], (function(require, exports, parse, __o, __o0, lexToken, __o1, __o2, comment_lexer, __o3, line_terminator_lexer,
__o4, __o5, __o6, __o7, __o8, whitespace_lexer, __o9) {
"use strict";
var lexer, lexStream, lex, always = parse["always"],
attempt = parse["attempt"],
binds = parse["binds"],
choice = parse["choice"],
eof = parse["eof"],
getPosition = parse["getPosition"],
modifyState = parse["modifyState"],
getState = parse["getState"],
enumeration = parse["enumeration"],
next = parse["next"],
many = parse["many"],
runState = parse["runState"],
never = parse["never"],
ParserState = parse["ParserState"],
then = __o["then"],
streamFrom = __o0["from"],
SourceLocation = __o1["SourceLocation"],
SourcePosition = __o1["SourcePosition"],
booleanLiteral = __o2["booleanLiteral"],
identifier = __o3["identifier"],
nullLiteral = __o4["nullLiteral"],
numericLiteral = __o5["numericLiteral"],
punctuator = __o6["punctuator"],
reservedWord = __o7["reservedWord"],
stringLiteral = __o8["stringLiteral"],
regularExpressionLiteral = __o9["regularExpressionLiteral"],
type, type0, type1, type2, type3, p, type4, type5, type6, type7, p0, type8, p1, type9, p2, consume = (
function(tok, self) {
switch (tok.type) {
case "Comment":
case "Whitespace":
case "LineTerminator":
return self;
default:
return tok;
}
}),
isRegExpCtx = (function(prev) {
if ((!prev)) return true;
switch (prev.type) {
case "Keyword":
case "Punctuator":
return true;
}
return false;
}),
enterRegExpCtx = getState.chain((function(prev) {
return (isRegExpCtx(prev) ? always() : never());
})),
literal = choice(((type = lexToken.StringToken.create), stringLiteral.map((function(x) {
return [type, x];
}))), ((type0 = lexToken.BooleanToken.create), booleanLiteral.map((function(x) {<|fim▁hole|> return [type0, x];
}))), ((type1 = lexToken.NullToken.create), nullLiteral.map((function(x) {
return [type1, x];
}))), ((type2 = lexToken.NumberToken.create), numericLiteral.map((function(x) {
return [type2, x];
}))), ((type3 = lexToken.RegularExpressionToken.create), (p = next(enterRegExpCtx,
regularExpressionLiteral)), p.map((function(x) {
return [type3, x];
})))),
token = choice(attempt(((type4 = lexToken.IdentifierToken), identifier.map((function(x) {
return [type4, x];
})))), literal, ((type5 = lexToken.KeywordToken), reservedWord.map((function(x) {
return [type5, x];
}))), ((type6 = lexToken.PunctuatorToken), punctuator.map((function(x) {
return [type6, x];
})))),
inputElement = choice(((type7 = lexToken.CommentToken), (p0 = comment_lexer.comment), p0.map((function(
x) {
return [type7, x];
}))), ((type8 = lexToken.WhitespaceToken), (p1 = whitespace_lexer.whitespace), p1.map((function(x) {
return [type8, x];
}))), ((type9 = lexToken.LineTerminatorToken), (p2 = line_terminator_lexer.lineTerminator), p2.map(
(function(x) {
return [type9, x];
}))), token);
(lexer = then(many(binds(enumeration(getPosition, inputElement, getPosition), (function(start, __o10, end) {
var type10 = __o10[0],
value = __o10[1];
return always(new(type10)(new(SourceLocation)(start, end, (start.file || end.file)),
value));
}))
.chain((function(tok) {
return next(modifyState(consume.bind(null, tok)), always(tok));
}))), eof));
(lexStream = (function(s, file) {
return runState(lexer, new(ParserState)(s, new(SourcePosition)(1, 0, file), null));
}));
var y = lexStream;
(lex = (function(z) {
return y(streamFrom(z));
}));
(exports["lexer"] = lexer);
(exports["lexStream"] = lexStream);
(exports["lex"] = lex);
}));<|fim▁end|> | |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|>"""__Main__."""
import sys
import os
import logging
import argparse
import traceback
import shelve
from datetime import datetime
from CONSTANTS import CONSTANTS
from settings.settings import load_config, load_core, load_remote, load_email
from settings.settings import load_html, load_sms
from core import read_structure, readStructureFromFile, updateStructure
from core import clean_video_db, syncDirTree, transferLongVersions
from core import executeToDoFile, build_html_report, umount
from core import check_and_correct_videos_errors, clean_remote
from core import get_new_file_ids_from_structure, mount, check_mkv_videos
from notifications import send_sms_notification, send_mail_report, send_mail_log
def get_args():
"""Get args."""<|fim▁hole|> parser = argparse.ArgumentParser(description='pyHomeVM')
parser.add_argument('-c', '--config_file_path',
action='store',
default='settings/dev_config.cfg',
help='path to config file that is to be used.')
parser.add_argument('-s', '--sms', help='Enables sms notifications',
action='store_true')
parser.add_argument('-l', '--log', help='Enables log sending by e-mail',
action='store_true')
parser.add_argument('-r', '--report',
help='Enables html report sending by e-mail',
action='store_true')
parser.add_argument('-rem', '--remote',
help='Enables transfer of long versions to remote storage',
action='store_true')
parser.add_argument('-b', '--backup',
help='Enables backup of first videos',
action='store_true')
parser.add_argument('-stats',
help='Gets you statistics about your videos',
action='store_true')
args = parser.parse_args()
return args
def load_logger():
"""Load logger."""
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(CONSTANTS['log_file_path'])
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def main(argv=None):
"""Run main."""
start_time = datetime.now()
args = get_args() # Get args
logger = load_logger() # Set logger
logger.info('PROGRAM STARTED')
pid = str(os.getpid())
pidfile = "/tmp/pyHomeVM.pid"
config = load_config(args.config_file_path) # load config file
if os.path.isfile(pidfile):
logger.info('Program already running')
html = load_html(config)
email = load_email(config)
send_mail_log(CONSTANTS['log_file_path'], email, html)
sys.exit()
file(pidfile, 'w').write(pid)
(ffmpeg, local) = load_core(config) # load core configs
remote = load_remote(config)
html = load_html(config)
sms = load_sms(config)
email = load_email(config)
if(args.log):
email = load_email(config)
if(args.report):
html = load_html(config)
if(args.remote):
remote = load_remote(config)
if(args.sms):
sms = load_sms(config)
video_db = shelve.open(CONSTANTS['video_db_path'], writeback=True)
try:
if not os.path.exists(CONSTANTS['structure_file_path']):
raise Exception("Directory structure definition file not found.")
past_structure = readStructureFromFile(CONSTANTS)
except Exception:
logger.info(traceback.format_exc())
logger.info('{} not found'.format(CONSTANTS['structure_file_path']))
past_structure = {} # Start as new
new_structure = read_structure(local)
video_ids = get_new_file_ids_from_structure(new_structure, video_db)
check_and_correct_videos_errors(video_ids, video_db, local, ffmpeg)
logger.info('Checked for errors and corrupted')
html_data = updateStructure(
past_structure,
read_structure(local),
local,
ffmpeg,
remote,
video_db)
sms_sent_file = os.path.join(CONSTANTS['script_root_dir'], 'sms_sent')
if(mount(remote)):
logger.info('Mount succesfull')
syncDirTree(local, remote)
transferLongVersions(local, remote, video_db)
if(os.path.isfile(CONSTANTS['todo_file_path'])):
executeToDoFile(CONSTANTS['todo_file_path'], local, CONSTANTS)
if(os.path.exists(sms_sent_file)):
os.remove(sms_sent_file)
logger.info('sms_sent file has been deleted')
clean_remote(remote)
umount(remote)
else:
logger.info('Mount unssuccesfull')
if(not os.path.exists(sms_sent_file) and args.sms):
send_sms_notification(sms)
logger.info('Sms sent')
with open(sms_sent_file, 'w') as sms_not:
msg = 'SMS has been sent {}'.format(CONSTANTS['TODAY'])
sms_not.write(msg)
logger.info(msg)
if(args.report and (
html_data['new'] != '' or
html_data['modified'] != '' or
html_data['deleted'] != '' or
html_data['moved'] != '')):
html_report = build_html_report(html_data, CONSTANTS, html)
send_mail_report(html_report, email)
logger.info('Mail report sent')
if(args.log):
send_mail_log(CONSTANTS['log_file_path'], email, html)
logger.info('log file sent')
clean_video_db(video_db)
check_mkv_videos(local, video_db)
logger.info('DB cleaned')
video_db.close()
logger.info('Script ran in {}'.format(datetime.now() - start_time))
os.unlink(pidfile)
if __name__ == "__main__":
sys.exit(main())<|fim▁end|> | |
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.db import models
from Corretor.base import CorretorException
from Corretor.base import ExecutorException
from Corretor.base import CompiladorException
from Corretor.base import ComparadorException
from Corretor.base import LockException
from model_utils import Choices
class RetornoCorrecao(models.Model):
"""Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao).
"""
TIPOS = Choices(
(0,'loading',u'Loading'),
(1,'compilacao',u'Compilação'),
(2,'execucao',u'Execução'),
(3,'comparacao',u'Comparação'),
(4,'lock',u'Lock'),
(5,'correto',u'Correto'),
)
tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading)
msg = models.TextField(u"Mensagem",blank=True,null=True)
task_id = models.CharField(max_length=350,blank=True,null=True)
class Meta:
verbose_name = u'Retorno Correção'
app_label = 'Corretor'
def __unicode__(self):
return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg)
def altera_dados(self,sucesso=True,erroException=None):
"""
Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem
que foi com sucesso.
"""
tipo = RetornoCorrecao.TIPOS.correto
correcao_msg = "Correto!"
# print ">>altera_dados"
# print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException)
if sucesso == True:
# print ">>retorno.successful()"
tipo = RetornoCorrecao.TIPOS.correto
correcao_msg = "Correto!"
elif isinstance(erroException,CorretorException):
# print "erro: %s" % erroException.message
if isinstance(erroException,ExecutorException):
correcao_msg = erroException.message
tipo = RetornoCorrecao.TIPOS.execucao
if isinstance(erroException,CompiladorException):
correcao_msg = erroException.message<|fim▁hole|> correcao_msg = erroException.message
tipo = RetornoCorrecao.TIPOS.comparacao
if isinstance(erroException,LockException):
correcao_msg = erroException.message
tipo = RetornoCorrecao.TIPOS.lock
self.tipo = tipo
self.msg = correcao_msg<|fim▁end|> | tipo = RetornoCorrecao.TIPOS.compilacao
if isinstance(erroException,ComparadorException): |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated<|fim▁hole|><|fim▁end|> | # in this software or its documentation.
#
# |
<|file_name|>client.go<|end_file_name|><|fim▁begin|>package gatt
import (
"encoding/binary"
"fmt"
"log"
"sync"
"github.com/currantlabs/ble"
"github.com/currantlabs/ble/linux/att"
)
const (
cccNotify = 0x0001
cccIndicate = 0x0002
)
// NewClient returns a GATT Client.
func NewClient(conn ble.Conn) (*Client, error) {
p := &Client{
subs: make(map[uint16]*sub),
conn: conn,
}
p.ac = att.NewClient(conn, p)
go p.ac.Loop()
return p, nil
}
// A Client is a GATT Client.
type Client struct {
sync.RWMutex
profile *ble.Profile
name string
subs map[uint16]*sub
ac *att.Client
conn ble.Conn
}
// Address returns the address of the client.
func (p *Client) Address() ble.Addr {
p.RLock()
defer p.RUnlock()
return p.conn.RemoteAddr()
}
// Name returns the name of the client.
func (p *Client) Name() string {
p.RLock()
defer p.RUnlock()
return p.name
}
// Profile returns the discovered profile.
func (p *Client) Profile() *ble.Profile {
p.RLock()
defer p.RUnlock()
return p.profile
}
// DiscoverProfile discovers the whole hierachy of a server.
func (p *Client) DiscoverProfile(force bool) (*ble.Profile, error) {
if p.profile != nil && !force {
return p.profile, nil
}
ss, err := p.DiscoverServices(nil)
if err != nil {
return nil, fmt.Errorf("can't discover services: %s\n", err)
}
for _, s := range ss {
cs, err := p.DiscoverCharacteristics(nil, s)
if err != nil {
return nil, fmt.Errorf("can't discover characteristics: %s\n", err)
}
for _, c := range cs {
_, err := p.DiscoverDescriptors(nil, c)
if err != nil {
return nil, fmt.Errorf("can't discover descriptors: %s\n", err)
}
}
}
p.profile = &ble.Profile{Services: ss}
return p.profile, nil
}
// DiscoverServices finds all the primary services on a server. [Vol 3, Part G, 4.4.1]
// If filter is specified, only filtered services are returned.
func (p *Client) DiscoverServices(filter []ble.UUID) ([]*ble.Service, error) {
p.Lock()
defer p.Unlock()
if p.profile == nil {
p.profile = &ble.Profile{}
}
start := uint16(0x0001)
for {
length, b, err := p.ac.ReadByGroupType(start, 0xFFFF, ble.PrimaryServiceUUID)
if err == ble.ErrAttrNotFound {
return p.profile.Services, nil
}
if err != nil {
return nil, err
}
for len(b) != 0 {
h := binary.LittleEndian.Uint16(b[:2])
endh := binary.LittleEndian.Uint16(b[2:4])
u := ble.UUID(b[4:length])
if filter == nil || ble.Contains(filter, u) {
s := &ble.Service{
UUID: u,
Handle: h,
EndHandle: endh,
}
p.profile.Services = append(p.profile.Services, s)
}
if endh == 0xFFFF {
return p.profile.Services, nil
}<|fim▁hole|> start = endh + 1
b = b[length:]
}
}
}
// DiscoverIncludedServices finds the included services of a service. [Vol 3, Part G, 4.5.1]
// If filter is specified, only filtered services are returned.
func (p *Client) DiscoverIncludedServices(ss []ble.UUID, s *ble.Service) ([]*ble.Service, error) {
p.Lock()
defer p.Unlock()
return nil, nil
}
// DiscoverCharacteristics finds all the characteristics within a service. [Vol 3, Part G, 4.6.1]
// If filter is specified, only filtered characteristics are returned.
func (p *Client) DiscoverCharacteristics(filter []ble.UUID, s *ble.Service) ([]*ble.Characteristic, error) {
p.Lock()
defer p.Unlock()
start := s.Handle
var lastChar *ble.Characteristic
for start <= s.EndHandle {
length, b, err := p.ac.ReadByType(start, s.EndHandle, ble.CharacteristicUUID)
if err == ble.ErrAttrNotFound {
break
} else if err != nil {
return nil, err
}
for len(b) != 0 {
h := binary.LittleEndian.Uint16(b[:2])
p := ble.Property(b[2])
vh := binary.LittleEndian.Uint16(b[3:5])
u := ble.UUID(b[5:length])
c := &ble.Characteristic{
UUID: u,
Property: p,
Handle: h,
ValueHandle: vh,
EndHandle: s.EndHandle,
}
if filter == nil || ble.Contains(filter, u) {
s.Characteristics = append(s.Characteristics, c)
}
if lastChar != nil {
lastChar.EndHandle = c.Handle - 1
}
lastChar = c
start = vh + 1
b = b[length:]
}
}
return s.Characteristics, nil
}
// DiscoverDescriptors finds all the descriptors within a characteristic. [Vol 3, Part G, 4.7.1]
// If filter is specified, only filtered descriptors are returned.
func (p *Client) DiscoverDescriptors(filter []ble.UUID, c *ble.Characteristic) ([]*ble.Descriptor, error) {
p.Lock()
defer p.Unlock()
start := c.ValueHandle + 1
for start <= c.EndHandle {
fmt, b, err := p.ac.FindInformation(start, c.EndHandle)
if err == ble.ErrAttrNotFound {
break
} else if err != nil {
return nil, err
}
length := 2 + 2
if fmt == 0x02 {
length = 2 + 16
}
for len(b) != 0 {
h := binary.LittleEndian.Uint16(b[:2])
u := ble.UUID(b[2:length])
d := &ble.Descriptor{UUID: u, Handle: h}
if filter == nil || ble.Contains(filter, u) {
c.Descriptors = append(c.Descriptors, d)
}
if u.Equal(ble.ClientCharacteristicConfigUUID) {
c.CCCD = d
}
start = h + 1
b = b[length:]
}
}
return c.Descriptors, nil
}
// ReadCharacteristic reads a characteristic value from a server. [Vol 3, Part G, 4.8.1]
func (p *Client) ReadCharacteristic(c *ble.Characteristic) ([]byte, error) {
p.Lock()
defer p.Unlock()
return p.ac.Read(c.ValueHandle)
}
// ReadLongCharacteristic reads a characteristic value which is longer than the MTU. [Vol 3, Part G, 4.8.3]
func (p *Client) ReadLongCharacteristic(c *ble.Characteristic) ([]byte, error) {
p.Lock()
defer p.Unlock()
return nil, nil
}
// WriteCharacteristic writes a characteristic value to a server. [Vol 3, Part G, 4.9.3]
func (p *Client) WriteCharacteristic(c *ble.Characteristic, v []byte, noRsp bool) error {
p.Lock()
defer p.Unlock()
if noRsp {
p.ac.WriteCommand(c.ValueHandle, v)
return nil
}
return p.ac.Write(c.ValueHandle, v)
}
// ReadDescriptor reads a characteristic descriptor from a server. [Vol 3, Part G, 4.12.1]
func (p *Client) ReadDescriptor(d *ble.Descriptor) ([]byte, error) {
p.Lock()
defer p.Unlock()
return p.ac.Read(d.Handle)
}
// WriteDescriptor writes a characteristic descriptor to a server. [Vol 3, Part G, 4.12.3]
func (p *Client) WriteDescriptor(d *ble.Descriptor, v []byte) error {
p.Lock()
defer p.Unlock()
return p.ac.Write(d.Handle, v)
}
// ReadRSSI retrieves the current RSSI value of remote peripheral. [Vol 2, Part E, 7.5.4]
func (p *Client) ReadRSSI() int {
p.Lock()
defer p.Unlock()
// TODO:
return 0
}
// ExchangeMTU informs the server of the client’s maximum receive MTU size and
// request the server to respond with its maximum receive MTU size. [Vol 3, Part F, 3.4.2.1]
func (p *Client) ExchangeMTU(mtu int) (int, error) {
p.Lock()
defer p.Unlock()
return p.ac.ExchangeMTU(mtu)
}
// Subscribe subscribes to indication (if ind is set true), or notification of a
// characteristic value. [Vol 3, Part G, 4.10 & 4.11]
func (p *Client) Subscribe(c *ble.Characteristic, ind bool, h ble.NotificationHandler) error {
p.Lock()
defer p.Unlock()
if c.CCCD == nil {
return fmt.Errorf("CCCD not found")
}
if ind {
return p.setHandlers(c.CCCD.Handle, c.ValueHandle, cccIndicate, h)
}
return p.setHandlers(c.CCCD.Handle, c.ValueHandle, cccNotify, h)
}
// Unsubscribe unsubscribes to indication (if ind is set true), or notification
// of a specified characteristic value. [Vol 3, Part G, 4.10 & 4.11]
func (p *Client) Unsubscribe(c *ble.Characteristic, ind bool) error {
p.Lock()
defer p.Unlock()
if c.CCCD == nil {
return fmt.Errorf("CCCD not found")
}
if ind {
return p.setHandlers(c.CCCD.Handle, c.ValueHandle, cccIndicate, nil)
}
return p.setHandlers(c.CCCD.Handle, c.ValueHandle, cccNotify, nil)
}
func (p *Client) setHandlers(cccdh, vh, flag uint16, h ble.NotificationHandler) error {
s, ok := p.subs[vh]
if !ok {
s = &sub{cccdh, 0x0000, nil, nil}
p.subs[vh] = s
}
switch {
case h == nil && (s.ccc&flag) == 0:
return nil
case h != nil && (s.ccc&flag) != 0:
return nil
case h == nil && (s.ccc&flag) != 0:
s.ccc &= ^uint16(flag)
case h != nil && (s.ccc&flag) == 0:
s.ccc |= flag
}
v := make([]byte, 2)
binary.LittleEndian.PutUint16(v, s.ccc)
if flag == cccNotify {
s.nHandler = h
} else {
s.iHandler = h
}
return p.ac.Write(s.cccdh, v)
}
// ClearSubscriptions clears all subscriptions to notifications and indications.
func (p *Client) ClearSubscriptions() error {
p.Lock()
defer p.Unlock()
zero := make([]byte, 2)
for vh, s := range p.subs {
if err := p.ac.Write(s.cccdh, zero); err != nil {
return err
}
delete(p.subs, vh)
}
return nil
}
// CancelConnection disconnects the connection.
func (p *Client) CancelConnection() error {
p.Lock()
defer p.Unlock()
return p.conn.Close()
}
// Disconnected returns a receiving channel, which is closed when the client disconnects.
func (p *Client) Disconnected() <-chan struct{} {
p.Lock()
defer p.Unlock()
return p.conn.Disconnected()
}
// HandleNotification ...
func (p *Client) HandleNotification(req []byte) {
p.Lock()
defer p.Unlock()
vh := att.HandleValueIndication(req).AttributeHandle()
sub, ok := p.subs[vh]
if !ok {
// FIXME: disconnects and propagate an error to the user.
log.Printf("Got an unregistered notification")
return
}
fn := sub.nHandler
if req[0] == att.HandleValueIndicationCode {
fn = sub.iHandler
}
if fn != nil {
fn(req[3:])
}
}
type sub struct {
cccdh uint16
ccc uint16
nHandler ble.NotificationHandler
iHandler ble.NotificationHandler
}<|fim▁end|> | |
<|file_name|>mappingMaker.js<|end_file_name|><|fim▁begin|>'use strict';
const inflect = require('i')();
const _ = require('lodash');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const options = {
adapter: 'mongodb',
connectionString: 'mongodb://127.0.0.1:27017/testDB',
db: 'testDB',
inflect: true
};
console.log(JSON.stringify(options));
const runningAsScript = !module.parent;
/*
*** Elastic-Search mapping maker. ***
* -------------------------------- *
Generate scaffolded elastic-search mapping from a harvester app.
Meant to be run @cmd line, but can also be required and used in code.
#Usage: node mappingMaker.js path-to-harvester-app primary-es-graph-resource(e.g. people) file-to-create.json
NB: argv[3] (in this case, "file-to-create.json") is optional. If not specified, no file will be written to disk;
instead the mapping will
be console.logged.
*/
const functionTypeLookup = {
'function Stri': 'string',
'function Numb': 'number',
'function Bool': 'boolean',
'function Date': 'date',
'function Buff': 'buffer',
'function Arra': 'array'
};
function getFunctionType(fn) {
return functionTypeLookup[fn.toString().substr(0, 13)];
}
function MappingMaker() {
}
MappingMaker.prototype.generateMapping = function generateMapping(harvestApp, pov, outputFile) {
let harvesterApp;
if (_.isString(harvestApp)) {
harvesterApp = require(harvestApp)(options);
} else {
harvesterApp = Promise.resolve(harvestApp);
}
return harvesterApp
.catch() // harvestApp doesn't have to work perfectly; we just need its schemas.
.then((_harvesterApp) => {
return make(_harvesterApp, pov);
})
.then((mappingData) => {
if (outputFile) {
console.log(`Saving mapping to ${outputFile}`);
return fs.writeFileAsync(outputFile, JSON.stringify(mappingData, null, 4)).then(() => {
console.log('Saved.');
return mappingData;
}).error((e) => {
console.error('Unable to save file, because: ', e.message);
});
}
console.log('Generated Mapping: ');
console.log(JSON.stringify(mappingData, null, 4));
return mappingData;
});
};
function make(harvestApp, pov) {
const schemaName = inflect.singularize(pov);
const startingSchema = harvestApp._schema[schemaName];
const maxDepth = 4;
const _depth = 0;
const retVal = {};
retVal[pov] = { properties: {} };
const _cursor = retVal[pov].properties;
function getNextLevelSchema(propertyName, propertyValue, cursor, depth) {
let nextCursor;
if (depth === 1) {
cursor.links = cursor.links || { type: 'nested' };
cursor.links.properties = cursor.links.properties || {};
cursor.links.properties[propertyName] = {
type: 'nested',
properties: {}
};
nextCursor = cursor.links.properties[propertyName].properties;
} else {
if (depth === maxDepth) {
return;
}
cursor[propertyName] = {
type: 'nested',
properties: {}
};
nextCursor = cursor[propertyName].properties;
}
harvestApp._schema[propertyValue] && getLinkedSchemas(harvestApp._schema[propertyValue], nextCursor, depth);
}
function getLinkedSchemas(_startingSchema, cursor, depth) {
if (depth >= maxDepth) {
console.warn(`[Elastic-harvest] Graph depth of ${depth} exceeds ${maxDepth}. Graph dive halted prematurely` +
' - please investigate.'); // harvest schema may have circular references.
return null;
}
const __depth = depth + 1;
_.each(_startingSchema, (propertyValue, propertyName) => {
if (typeof propertyValue !== 'function') {
if (_.isString(propertyValue)) {
getNextLevelSchema(propertyName, propertyValue, cursor, __depth);
} else if (_.isArray(propertyValue)) {
if (_.isString(propertyValue[0])) {
getNextLevelSchema(propertyName, propertyValue[0], cursor, __depth);
} else {
getNextLevelSchema(propertyName, propertyValue[0].ref, cursor, __depth);
}
} else if (_.isObject(propertyValue)) {
getNextLevelSchema(propertyName, propertyValue.ref, cursor, __depth);
}
} else {
const fnType = getFunctionType(propertyValue);
if (fnType === 'string') {
cursor.id = {
type: 'string',
index: 'not_analyzed'<|fim▁hole|> };
} else if (fnType === 'number') {
cursor[propertyName] = {
type: 'long'
};
} else if (fnType === 'date') {
cursor[propertyName] = {
type: 'date'
};
} else if (fnType === 'boolean') {
cursor[propertyName] = {
type: 'boolean'
};
} else if (fnType === 'array') {
console.warn('[mapping-maker] Array-type scaffolding not yet implemented; ' +
`The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`);
} else if (fnType === 'buffer') {
console.warn('[mapping-maker] Buffer-type scaffolding not yet implemented; ' +
`The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`);
} else {
console.warn('[mapping-maker] unsupported type; ' +
`The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`);
}
}
});
return cursor;
}
getLinkedSchemas(startingSchema, _cursor, _depth);
return retVal;
}
if (runningAsScript) {
const mappingMaker = new MappingMaker();
mappingMaker.generateMapping(process.argv[2], process.argv[3], process.argv[4]);
} else {
module.exports = MappingMaker;
}<|fim▁end|> | };
cursor[propertyName] = {
type: 'string',
index: 'not_analyzed' |
<|file_name|>webglshaderprecisionformat.rs<|end_file_name|><|fim▁begin|>/* 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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding;
use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding::WebGLShaderPrecisionFormatMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, JSRef};
use dom::bindings::utils::{Reflector,reflect_dom_object};
#[dom_struct]
pub struct WebGLShaderPrecisionFormat {
reflector_: Reflector,
range_min: i32,
range_max: i32,
precision: i32,
}
impl WebGLShaderPrecisionFormat {
fn new_inherited(range_min: i32, range_max: i32, precision: i32) -> WebGLShaderPrecisionFormat {
WebGLShaderPrecisionFormat {
reflector_: Reflector::new(),
range_min: range_min,
range_max: range_max,
precision: precision,
}
}
pub fn new(global: GlobalRef,
range_min: i32,
range_max: i32,
precision: i32) -> Temporary<WebGLShaderPrecisionFormat> {
reflect_dom_object(
box WebGLShaderPrecisionFormat::new_inherited(range_min, range_max, precision),
global,
WebGLShaderPrecisionFormatBinding::Wrap)
}
}
impl<'a> WebGLShaderPrecisionFormatMethods for JSRef<'a, WebGLShaderPrecisionFormat> {
fn RangeMin(self) -> i32 {
self.range_min
}<|fim▁hole|> }
fn Precision(self) -> i32 {
self.precision
}
}<|fim▁end|> |
fn RangeMax(self) -> i32 {
self.range_max |
<|file_name|>libxml.js<|end_file_name|><|fim▁begin|>const express = require('express');
const libxmljs = require('libxmljs');
express().get('/some/path', function(req) {<|fim▁hole|> libxmljs.parseXml(req.param("some-xml"));
});<|fim▁end|> | // OK: libxml does not expand entities by default |
<|file_name|>CategoryManagerImpl.java<|end_file_name|><|fim▁begin|>package hska.iwi.eShopMaster.model.businessLogic.manager.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import hska.iwi.eShopMaster.model.businessLogic.manager.CategoryManager;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.Category;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.User;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
public class CategoryManagerImpl implements CategoryManager {
private final static String BASIS_URL_CATEGORY = "http://localhost:8081/api/catalog/category/";
private final Logger logger = Logger.getLogger(CategoryManagerImpl.class);
private final ObjectMapper parser = new ObjectMapper();
private final User currentUser;
public CategoryManagerImpl(User currentUser) {
this.currentUser = currentUser;
}
@Override
public List<Category> getCategories() {
List<Category> categories = null;
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
categories = parser.readValue(response.getEntity(String.class), List.class);
} catch (Exception ex) {
logger.error(ex);
}
return categories;
}
@Override
public Category getCategory(int id) {
Category category = null;
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY)
.path(String.valueOf(id));
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
category = parser.readValue(response.getEntity(String.class), Category.class);
} catch (Exception ex) {
logger.error(ex);
}
return category;
}
@Override
public void addCategory(String name) {
Category category = new Category(name);
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY);
webResource.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)<|fim▁hole|> .post(ClientResponse.class, parser.writeValueAsString(category));
} catch (Exception ex) {
logger.error(ex);
}
}
@Override
public void delCategoryById(int id) {
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY)
.path(String.valueOf(id));
webResource.accept(MediaType.APPLICATION_JSON_TYPE)
.header("usr", currentUser.getUsername())
.header("pass", currentUser.getPassword())
.delete();
} catch (Exception ex) {
logger.error(ex);
}
}
}<|fim▁end|> | .header("usr", currentUser.getUsername())
.header("pass", currentUser.getPassword()) |
<|file_name|>numpy2go.py<|end_file_name|><|fim▁begin|>import numpy as np
import ctypes
import numpy.ctypeslib as npct<|fim▁hole|># https://scipy-lectures.github.io/advanced/interfacing_with_c/interfacing_with_c.html#id5
numpy2go = npct.load_library("numpy2go", ".")
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')
numpy2go.Test.restype = None
numpy2go.Test.argtypes = [array_1d_double, ctypes.c_int]
data = np.array([0.0, 1.0, 2.0])
print("Python says", data)
numpy2go.Test(data, len(data))<|fim▁end|> |
# For more information see: |
<|file_name|>messages.js<|end_file_name|><|fim▁begin|>/*
* Returns Messages
*
* This contains all the text for the Returns component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.components.Returns.header',
defaultMessage: 'returns',
},
returnPolicy: {<|fim▁hole|> message: {
id: 'app.components.Returns.message',
defaultMessage: 'This item must be returned within 30 days of the ship date. See {policyLink} for details. Prices, promotions, styles and availability may vary by store and online.',
},
});<|fim▁end|> | id: 'app.components.Returns.returnPolicy',
defaultMessage: 'Return Policy',
}, |
<|file_name|>WinEventsWayland.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#if defined (HAVE_WAYLAND)
#include <boost/scoped_ptr.hpp>
#include "Application.h"
#include "xbmc/windowing/WindowingFactory.h"<|fim▁hole|>#include "WinEventsWayland.h"
#include "wayland/EventListener.h"
#include "wayland/InputFactory.h"
#include "wayland/EventLoop.h"
namespace xwe = xbmc::wayland::events;
namespace
{
class XBMCListener :
public xbmc::IEventListener
{
public:
virtual void OnEvent(XBMC_Event &event);
virtual void OnFocused();
virtual void OnUnfocused();
};
XBMCListener g_listener;
boost::scoped_ptr <xbmc::InputFactory> g_inputInstance;
boost::scoped_ptr <xwe::Loop> g_eventLoop;
}
void XBMCListener::OnEvent(XBMC_Event &e)
{
g_application.OnEvent(e);
}
void XBMCListener::OnFocused()
{
g_application.m_AppFocused = true;
g_Windowing.NotifyAppFocusChange(g_application.m_AppFocused);
}
void XBMCListener::OnUnfocused()
{
g_application.m_AppFocused = false;
g_Windowing.NotifyAppFocusChange(g_application.m_AppFocused);
}
CWinEventsWayland::CWinEventsWayland()
{
}
void CWinEventsWayland::RefreshDevices()
{
}
bool CWinEventsWayland::IsRemoteLowBattery()
{
return false;
}
/* This function reads the display connection and dispatches
* any events through the specified object listeners */
bool CWinEventsWayland::MessagePump()
{
if (!g_eventLoop.get())
return false;
g_eventLoop->Dispatch();
return true;
}
size_t CWinEventsWayland::GetQueueSize()
{
/* We can't query the size of the queue */
return 0;
}
void CWinEventsWayland::SetEventQueueStrategy(xwe::IEventQueueStrategy &strategy)
{
g_eventLoop.reset(new xwe::Loop(g_listener, strategy));
}
void CWinEventsWayland::DestroyEventQueueStrategy()
{
g_eventLoop.reset();
}
/* Once we know about a wayland seat, we can just create our manager
* object to encapsulate all of that state. When the seat goes away
* we just unset the manager object and it is all cleaned up at that
* point */
void CWinEventsWayland::SetWaylandSeat(IDllWaylandClient &clientLibrary,
IDllXKBCommon &xkbCommonLibrary,
struct wl_seat *s)
{
if (!g_eventLoop.get())
throw std::logic_error("Must have a wl_display set before setting "
"the wl_seat in CWinEventsWayland ");
g_inputInstance.reset(new xbmc::InputFactory(clientLibrary,
xkbCommonLibrary,
s,
*g_eventLoop,
*g_eventLoop));
}
void CWinEventsWayland::DestroyWaylandSeat()
{
g_inputInstance.reset();
}
/* When a surface becomes available, this function should be called
* to register it as the current one for processing input events on.
*
* It is a precondition violation to call this function before
* a seat has been registered */
void CWinEventsWayland::SetXBMCSurface(struct wl_surface *s)
{
if (!g_inputInstance.get())
throw std::logic_error("Must have a wl_seat set before setting "
"the wl_surface in CWinEventsWayland");
g_inputInstance->SetXBMCSurface(s);
}
#endif<|fim▁end|> | |
<|file_name|>match-vec-unreachable.rs<|end_file_name|><|fim▁begin|>fn main() {
let x: ~[(int, int)] = ~[];
match x {
[a, (2, 3), _] => (),
[(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern
_ => ()
}
match [~"foo", ~"bar", ~"baz"] {
[a, _, _, .._] => { println(a); }
[~"foo", ~"bar", ~"baz", ~"foo", ~"bar"] => { } //~ ERROR unreachable pattern<|fim▁hole|> }
match ['a', 'b', 'c'] {
['a', 'b', 'c', .._tail] => {}
['a', 'b', 'c'] => {} //~ ERROR unreachable pattern
_ => {}
}
}<|fim▁end|> | _ => { } |
<|file_name|>actorRegistry.ts<|end_file_name|><|fim▁begin|>/**
* Holds instances to Actor classes for instantiation
*/
import { ActorType } from '../../actor/actor';
/* tslint:disable-next-line interface-over-type-literal */
type ActorRegister = { [actorClassName: string]: ActorType };
export class ActorRegistry {
private static self: ActorRegistry = new ActorRegistry();
private registry: ActorRegister = {};
public static getInstance(): ActorRegistry {
return ActorRegistry.self;
}
constructor() {
if (ActorRegistry.self) {
throw new Error('Use getInstance to retrieve registry');
}
ActorRegistry.self = this;
}
/**
* Register an actor with the registry
* @param {ActorType} actor - The actor to register with the registry
*/
public register(actor: ActorType): void {
if (!this.registry[actor.name]) {
this.registry[actor.name] = actor;
}
}
/**
* Check to see if an actor exists in the registry
* @param {string} actor - The string name of the actor class
* @return {boolean} - Whether the actor exists in the registry
*/
public exists(actor: string): boolean {
return !!this.registry[actor];
}
/**
* Get the specified ActorType from the registry, or throw<|fim▁hole|> public get(actor: string): ActorType {
if (this.exists(actor)) {
return this.registry[actor];
} else {
throw new Error(`Actor ${actor} is not registered`);
}
}
/**
* Clear the repository
* NOTE: This is mostly for testing
*/
public clear(): void {
this.registry = {};
}
}<|fim▁end|> | * @param {string} actor - The string name of the actor class
* @return {ActorType} - The actor class, or throw
*/ |
<|file_name|>spatial_query.hpp<|end_file_name|><|fim▁begin|>// Boost.Geometry Index
//
// R-tree spatial query visitor implementation
//
// Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland.
//
// This file was modified by Oracle on 2019-2021.
// Modifications copyright (c) 2019-2021 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
//
// Use, modification and distribution is subject to 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_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_SPATIAL_QUERY_HPP
#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_SPATIAL_QUERY_HPP
#include <boost/geometry/index/detail/rtree/node/node_elements.hpp>
#include <boost/geometry/index/detail/predicates.hpp>
#include <boost/geometry/index/parameters.hpp>
namespace boost { namespace geometry { namespace index {
namespace detail { namespace rtree { namespace visitors {
template <typename MembersHolder, typename Predicates, typename OutIter>
struct spatial_query
{
typedef typename MembersHolder::parameters_type parameters_type;
typedef typename MembersHolder::translator_type translator_type;
typedef typename MembersHolder::allocators_type allocators_type;
typedef typename index::detail::strategy_type<parameters_type>::type strategy_type;
typedef typename MembersHolder::node node;
typedef typename MembersHolder::internal_node internal_node;
typedef typename MembersHolder::leaf leaf;
typedef typename allocators_type::node_pointer node_pointer;
typedef typename allocators_type::size_type size_type;
spatial_query(MembersHolder const& members, Predicates const& p, OutIter out_it)
: m_tr(members.translator())
, m_strategy(index::detail::get_strategy(members.parameters()))
, m_pred(p)
, m_out_iter(out_it)
, m_found_count(0)
{}
size_type apply(node_pointer ptr, size_type reverse_level)
{
namespace id = index::detail;
if (reverse_level > 0)
{
internal_node& n = rtree::get<internal_node>(*ptr);
// traverse nodes meeting predicates
for (auto const& p : rtree::elements(n))
{
// if node meets predicates (0 is dummy value)
if (id::predicates_check<id::bounds_tag>(m_pred, 0, p.first, m_strategy))
{
apply(p.second, reverse_level - 1);
}
}
}
else
{
leaf& n = rtree::get<leaf>(*ptr);
// get all values meeting predicates
for (auto const& v : rtree::elements(n))
{
// if value meets predicates
if (id::predicates_check<id::value_tag>(m_pred, v, m_tr(v), m_strategy))
{
*m_out_iter = v;
++m_out_iter;
++m_found_count;
}
}
}
return m_found_count;
}
size_type apply(MembersHolder const& members)
{
return apply(members.root, members.leafs_level);
}
private:
translator_type const& m_tr;
strategy_type m_strategy;
Predicates const& m_pred;
OutIter m_out_iter;
size_type m_found_count;
};
template <typename MembersHolder, typename Predicates>
class spatial_query_incremental
{
typedef typename MembersHolder::value_type value_type;
typedef typename MembersHolder::parameters_type parameters_type;
typedef typename MembersHolder::translator_type translator_type;
typedef typename MembersHolder::allocators_type allocators_type;
typedef typename index::detail::strategy_type<parameters_type>::type strategy_type;
typedef typename MembersHolder::node node;
typedef typename MembersHolder::internal_node internal_node;
typedef typename MembersHolder::leaf leaf;
typedef typename allocators_type::size_type size_type;
typedef typename allocators_type::const_reference const_reference;
typedef typename allocators_type::node_pointer node_pointer;
typedef typename rtree::elements_type<internal_node>::type::const_iterator internal_iterator;
typedef typename rtree::elements_type<leaf>::type leaf_elements;
typedef typename rtree::elements_type<leaf>::type::const_iterator leaf_iterator;
struct internal_data
{
internal_data(internal_iterator f, internal_iterator l, size_type rl)
: first(f), last(l), reverse_level(rl)
{}
internal_iterator first;
internal_iterator last;
size_type reverse_level;
};
public:
spatial_query_incremental()
: m_translator(nullptr)
// , m_strategy()
// , m_pred()
, m_values(nullptr)
, m_current()
{}
spatial_query_incremental(Predicates const& p)
: m_translator(nullptr)
// , m_strategy()
, m_pred(p)
, m_values(nullptr)
, m_current()
{}
spatial_query_incremental(MembersHolder const& members, Predicates const& p)
: m_translator(::boost::addressof(members.translator()))
, m_strategy(index::detail::get_strategy(members.parameters()))
, m_pred(p)
, m_values(nullptr)
, m_current()
{}
const_reference dereference() const
{
BOOST_GEOMETRY_INDEX_ASSERT(m_values, "not dereferencable");
return *m_current;
}
void initialize(MembersHolder const& members)
{
apply(members.root, members.leafs_level);
search_value();
}
void increment()
{
++m_current;
search_value();<|fim▁hole|>
bool is_end() const
{
return 0 == m_values;
}
friend bool operator==(spatial_query_incremental const& l, spatial_query_incremental const& r)
{
return (l.m_values == r.m_values) && (0 == l.m_values || l.m_current == r.m_current);
}
private:
void apply(node_pointer ptr, size_type reverse_level)
{
namespace id = index::detail;
if (reverse_level > 0)
{
internal_node& n = rtree::get<internal_node>(*ptr);
auto const& elements = rtree::elements(n);
m_internal_stack.push_back(internal_data(elements.begin(), elements.end(), reverse_level - 1));
}
else
{
leaf& n = rtree::get<leaf>(*ptr);
m_values = ::boost::addressof(rtree::elements(n));
m_current = rtree::elements(n).begin();
}
}
void search_value()
{
namespace id = index::detail;
for (;;)
{
// if leaf is choosen, move to the next value in leaf
if ( m_values )
{
if ( m_current != m_values->end() )
{
// return if next value is found
value_type const& v = *m_current;
if (id::predicates_check<id::value_tag>(m_pred, v, (*m_translator)(v), m_strategy))
{
return;
}
++m_current;
}
// no more values, clear current leaf
else
{
m_values = 0;
}
}
// if leaf isn't choosen, move to the next leaf
else
{
// return if there is no more nodes to traverse
if (m_internal_stack.empty())
{
return;
}
internal_data& current_data = m_internal_stack.back();
// no more children in current node, remove it from stack
if (current_data.first == current_data.last)
{
m_internal_stack.pop_back();
continue;
}
internal_iterator it = current_data.first;
++current_data.first;
// next node is found, push it to the stack
if (id::predicates_check<id::bounds_tag>(m_pred, 0, it->first, m_strategy))
{
apply(it->second, current_data.reverse_level);
}
}
}
}
const translator_type * m_translator;
strategy_type m_strategy;
Predicates m_pred;
std::vector<internal_data> m_internal_stack;
const leaf_elements * m_values;
leaf_iterator m_current;
};
}}} // namespace detail::rtree::visitors
}}} // namespace boost::geometry::index
#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_SPATIAL_QUERY_HPP<|fim▁end|> | } |
<|file_name|>GHRelease.java<|end_file_name|><|fim▁begin|>package org.kohsuke.github;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static java.lang.String.*;
/**
* Release in a github repository.
*
* @see GHRepository#getReleases() GHRepository#getReleases()
* @see GHRepository#listReleases() () GHRepository#listReleases()
* @see GHRepository#createRelease(String) GHRepository#createRelease(String)
*/
public class GHRelease extends GHObject {
GHRepository owner;
private String html_url;
private String assets_url;
private List<GHAsset> assets;
private String upload_url;
private String tag_name;
private String target_commitish;
private String name;
private String body;
private boolean draft;
private boolean prerelease;
private Date published_at;
private String tarball_url;
private String zipball_url;
private String discussion_url;
/**
* Gets discussion url. Only present if a discussion relating to the release exists
*
* @return the discussion url
*/
public String getDiscussionUrl() {
return discussion_url;
}
/**
* Gets assets url.
*
* @return the assets url
*/
public String getAssetsUrl() {
return assets_url;
}
/**
* Gets body.
*
* @return the body
*/
public String getBody() {
return body;
}
/**
* Is draft boolean.
*
* @return the boolean
*/
public boolean isDraft() {
return draft;
}
/**
* Sets draft.
*
* @param draft
* the draft
* @return the draft
* @throws IOException
* the io exception
* @deprecated Use {@link #update()}
*/
@Deprecated
public GHRelease setDraft(boolean draft) throws IOException {
return update().draft(draft).update();
}
public URL getHtmlUrl() {
return GitHubClient.parseURL(html_url);
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets name.
*
* @param name
* the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets owner.
*
* @return the owner
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior")
public GHRepository getOwner() {
return owner;
}
/**
* Sets owner.
*
* @param owner
* the owner
* @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding.
*/
@Deprecated
public void setOwner(GHRepository owner) {
throw new RuntimeException("Do not use this method.");
}
/**
* Is prerelease boolean.
*
* @return the boolean
*/
public boolean isPrerelease() {
return prerelease;
}
/**
* Gets published at.
*
* @return the published at
*/
public Date getPublished_at() {
return new Date(published_at.getTime());
}
/**
* Gets tag name.
*
* @return the tag name
*/
public String getTagName() {
return tag_name;
}
/**
* Gets target commitish.
*
* @return the target commitish
*/
public String getTargetCommitish() {
return target_commitish;
}
/**
* Gets upload url.
*
* @return the upload url
*/
public String getUploadUrl() {
return upload_url;
}
/**
* Gets zipball url.
*
* @return the zipball url
*/
public String getZipballUrl() {
return zipball_url;
}
/**
* Gets tarball url.
*
* @return the tarball url
*/
public String getTarballUrl() {
return tarball_url;
}
GHRelease wrap(GHRepository owner) {
this.owner = owner;
return this;
}
static GHRelease[] wrap(GHRelease[] releases, GHRepository owner) {
for (GHRelease release : releases) {
release.wrap(owner);
}
return releases;
}
/**
* Because github relies on SNI (http://en.wikipedia.org/wiki/Server_Name_Indication) this method will only work on
* Java 7 or greater. Options for fixing this for earlier JVMs can be found here
* http://stackoverflow.com/questions/12361090/server-name-indication-sni-on-java but involve more complicated
* handling of the HTTP requests to github's API.
*
* @param file
* the file
* @param contentType
* the content type
* @return the gh asset
* @throws IOException
* the io exception
*/
public GHAsset uploadAsset(File file, String contentType) throws IOException {
FileInputStream s = new FileInputStream(file);
try {
return uploadAsset(file.getName(), s, contentType);
} finally {
s.close();
}
}
/**<|fim▁hole|> * the filename
* @param stream
* the stream
* @param contentType
* the content type
* @return the gh asset
* @throws IOException
* the io exception
*/
public GHAsset uploadAsset(String filename, InputStream stream, String contentType) throws IOException {
Requester builder = owner.root().createRequest().method("POST");
String url = getUploadUrl();
// strip the helpful garbage from the url
url = url.substring(0, url.indexOf('{'));
url += "?name=" + URLEncoder.encode(filename, "UTF-8");
return builder.contentType(contentType).with(stream).withUrlPath(url).fetch(GHAsset.class).wrap(this);
}
/**
* Get the cached assets.
*
* @return the assets
*
* @deprecated This should be the default behavior of {@link #getAssets()} in a future release. This method is
* introduced in addition to enable a transition to using cached asset information while keeping the
* existing logic in place for backwards compatibility.
*/
@Deprecated
public List<GHAsset> assets() {
return Collections.unmodifiableList(assets);
}
/**
* Re-fetch the assets of this release.
*
* @return the assets
* @throws IOException
* the io exception
* @deprecated The behavior of this method will change in a future release. It will then provide cached assets as
* provided by {@link #assets()}. Use {@link #listAssets()} instead to fetch up-to-date information of
* assets.
*/
@Deprecated
public List<GHAsset> getAssets() throws IOException {
return listAssets().toList();
}
/**
* Re-fetch the assets of this release.
*
* @return the assets
* @throws IOException
* the io exception
*/
public PagedIterable<GHAsset> listAssets() throws IOException {
Requester builder = owner.root().createRequest();
return builder.withUrlPath(getApiTailUrl("assets")).toIterable(GHAsset[].class, item -> item.wrap(this));
}
/**
* Deletes this release.
*
* @throws IOException
* the io exception
*/
public void delete() throws IOException {
root().createRequest().method("DELETE").withUrlPath(owner.getApiTailUrl("releases/" + getId())).send();
}
/**
* Updates this release via a builder.
*
* @return the gh release updater
*/
public GHReleaseUpdater update() {
return new GHReleaseUpdater(this);
}
private String getApiTailUrl(String end) {
return owner.getApiTailUrl(format("releases/%s/%s", getId(), end));
}
}<|fim▁end|> | * Upload asset gh asset.
*
* @param filename |
<|file_name|>node_style.rs<|end_file_name|><|fim▁begin|>/* 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/. */
// Style retrieval from DOM elements.
use css::node_util::NodeUtil;
use layout::incremental::RestyleDamage;
use layout::wrapper::LayoutNode;
use extra::arc::Arc;
use style::ComputedValues;
/// Node mixin providing `style` method that returns a `NodeStyle`
pub trait StyledNode {
fn style<'a>(&'a self) -> &'a Arc<ComputedValues>;
fn restyle_damage(&self) -> RestyleDamage;
}
impl<'self> StyledNode for LayoutNode<'self> {
#[inline]
fn style<'a>(&'a self) -> &'a Arc<ComputedValues> {<|fim▁hole|>
fn restyle_damage(&self) -> RestyleDamage {
self.get_restyle_damage()
}
}<|fim▁end|> | self.get_css_select_results()
} |
<|file_name|>loadtrain.py<|end_file_name|><|fim▁begin|>import numpy as np
import fnmatch, os
import h5py
class Hdf5Loader():
def loadDirectory(self, dirname):
"""
Loads all hdf5 files in the directory dirname
@param dirname: The directory which contains the files to load
@returns: list of h5py File objects
"""
cachelist=os.listdir(dirname)
testlist=fnmatch.filter(cachelist,'*.hdf5')
for file_ in testlist:
print("Using {0}".format(file_))
files = [h5py.File(os.path.join(dirname, fn),'r') for fn in testlist]
return files
def getDatasets(self, dirname, dataset_list):
"""
Loads all hdf5 files in a given directory. It extracts all datasets
which are specified in :dataset_list and merges the datasets from
all files.
Finally it returns a numpy array for each dataset in the :dataset_list
@param dirname: The directory containing the hdf5 files
@param dataset_list: List of datasets to load
@returns: A list of numpy arrays loaded from the dataset files
"""
files = self.loadDirectory(dirname)
result = []
for dataset_name in dataset_list:
arr = np.concatenate([f[dataset_name] for f in files])
result.append(arr)
return result
class LoadData():
"""
This class extracts data from features and corresponding powervalues and returns them as array
"""
def __init__(self, sep=";", groundtruth_elements=2, skiprows=1, skipcols=1):
self.sep = sep
self.num_groundtruth_elements = groundtruth_elements
self.skiprows=1
self.skipcols = skipcols
def getFeatureCount(self, file_):
fd = open(file_, 'r')
<|fim▁hole|>
return count - self.num_groundtruth_elements
def getFeaturesData(self,csvname):
cols = range(self.skipcols, self.getFeatureCount(csvname))
print cols
log = np.loadtxt(csvname,delimiter=self.sep,skiprows=self.skiprows,usecols=cols)
return log
def getPowerData(self,csvname):
cols = [self.getFeatureCount(csvname)]
power = np.loadtxt(csvname,delimiter=self.sep,skiprows=self.skiprows,usecols=cols)
return power
def load_dir(self, dirname):
"""
Loads all files of a directory to a single feature and power data set
"""
cachelist=os.listdir(dirname)
testlist=fnmatch.filter(cachelist,'*.csv')
testFeatureDataLst = []
testPowerDataLst = []
"""Testdaten laden"""
for file_ in testlist:
testFeatureDataLst.append(self.getFeaturesData(os.path.join(dirname,file_)))
testPowerDataLst.append(self.getPowerData(os.path.join(dirname,file_)))
testFeatureData = np.concatenate(testFeatureDataLst)
testPowerData = np.concatenate(testPowerDataLst)
return testPowerData, testFeatureData<|fim▁end|> | fd.readline()
count = len(fd.readline().split(self.sep))
|
<|file_name|>salt-call.py<|end_file_name|><|fim▁begin|>__author__ = 'Jason Mehring'
#
# This module is only used with WingIDE debugger for testing code within
# The debugging environment
#
# Stage 1: bind /srv/...modules to cache/extmods. No sync will take place
# since files are bound
# BIND
# True : bind custom modules
# False : do not bind custom modules, but will attempt umounting then exit
# None : do not bind custom modules, and do not attempt umounting
BIND = None
import os
import sys
import shutil
import subprocess
import logging
if BIND is not None:
import salt.config
import salt.fileclient
import salt.fileserver
import salt.loader
import salt.modules.saltutil
import salt.pillar
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
from salt.modules.saltutil import (
_get_top_file_envs, _listdir_recursively, _list_emptydirs
)
from salt.ext.six import string_types
# Enable logging
log = logging.getLogger(__name__)
BASE_DIR = os.getcwd()
# Set salt pillar, grains and opts settings so they can be applied to modules
__opts__ = salt.config.minion_config('/etc/salt/minion')
__opts__['grains'] = salt.loader.grains(__opts__)
pillar = salt.pillar.get_pillar(
__opts__,
__opts__['grains'],
__opts__['id'],
__opts__['environment'],
)
__opts__['pillar'] = pillar.compile_pillar()
__salt__ = salt.loader.minion_mods(__opts__)
__grains__ = __opts__['grains']
__pillar__ = __opts__['pillar']
__context__ = {}
salt.modules.saltutil.__opts__ = __opts__
salt.modules.saltutil.__grains__ = __grains__
salt.modules.saltutil.__pillar__ = __pillar__
salt.modules.saltutil.__salt__ = __salt__
salt.modules.saltutil.__context__ = __context__
from salt.scripts import salt_call
def _bind(form, saltenv=None, umount=False):
'''
Bind the files in salt extmods directory within the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, string_types):
saltenv = saltenv.split(',')
ret = []
remote = set()
source = os.path.join('salt://_{0}'.format(form))
mod_dir = os.path.join(__opts__['extension_modules'], '{0}'.format(form))
if not os.path.isdir(mod_dir):
log.info('Creating module dir {0!r}'.format(mod_dir))
try:
os.makedirs(mod_dir)
except (IOError, OSError):
msg = 'Cannot create cache module directory {0}. Check permissions.'
log.error(msg.format(mod_dir))
for sub_env in saltenv:
log.info('Syncing {0} for environment {1!r}'.format(form, sub_env))
cache = []
log.info('Loading cache from {0}, for {1})'.format(source, sub_env))
# Grab only the desired files (.py, .pyx, .so)
cache.extend(
__salt__['cp.cache_dir'](
source, sub_env, include_pat=r'E@\.(pyx?|so)$'
)
)
local_cache_base_dir = os.path.join(
__opts__['cachedir'],
'files',
sub_env
)
log.debug('Local cache base dir: {0!r}'.format(local_cache_base_dir))
local_cache_dir = os.path.join(local_cache_base_dir, '_{0}'.format(form))
log.debug('Local cache dir: {0!r}'.format(local_cache_dir))
client = salt.fileclient.get_file_client(__opts__)
fileserver = salt.fileserver.Fileserver(__opts__)
for fn_ in cache:
relpath = os.path.relpath(fn_, local_cache_dir)
relname = os.path.splitext(relpath)[0].replace(os.sep, '.')
saltpath = os.path.relpath(fn_, local_cache_base_dir)
filenamed = fileserver.find_file(saltpath, sub_env)
remote.add(relpath)
dest = os.path.join(mod_dir, relpath)
if not os.path.isfile(dest):
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
shutil.copyfile(fn_, dest)
ret.append('{0}.{1}'.format(form, relname))
# Test to see if already mounted (bound)
cmd = ['findmnt', dest]
proc = subprocess.Popen(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT)
proc.wait()
if proc.returncode:
cmd = ['mount', '--bind', filenamed['path'], dest]
proc = subprocess.Popen(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT)
proc.wait()
elif umount:
cmd = ['umount', dest]
proc = subprocess.Popen(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT)
proc.wait()
touched = bool(ret)
if __opts__.get('clean_dynamic_modules', True):
current = set(_listdir_recursively(mod_dir))
for fn_ in current - remote:
full = os.path.join(mod_dir, fn_)
if os.path.ismount(full):
proc = subprocess.Popen(['umount', full])
proc.wait()
if os.path.isfile(full):
touched = True
try:
os.remove(full)
except OSError: pass
# Cleanup empty dirs
while True:
emptydirs = _list_emptydirs(mod_dir)
if not emptydirs:
break
for emptydir in emptydirs:
touched = True
shutil.rmtree(emptydir, ignore_errors=True)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.fopen(mod_file, 'a+') as ofile:
ofile.write('')
return ret
def bind_dirs(umount):
_bind('beacons', umount=umount)
_bind('modules', umount=umount)
_bind('states', umount=umount)
_bind('grains', umount=umount)
_bind('renderers', umount=umount)
_bind('returners', umount=umount)<|fim▁hole|> argv = sys.argv
def join_path(basepath, paths):
return [os.path.join(basepath, path) for path in paths]
if BIND or BIND is False:
umount = not BIND
path = BASE_DIR.split(os.sep)
srv_dir = '/srv'
if srv_dir.lstrip(os.sep) in path:
index = BASE_DIR.index(srv_dir)
basepath = os.sep.join(path[:6+1])
cur_dirs = join_path(basepath, os.listdir(basepath))
srv_dirs = join_path(srv_dir, os.listdir(srv_dir))
for path in cur_dirs:
if path not in srv_dirs:
basename = os.path.basename(path)
if basename in os.listdir(srv_dir):
dest = os.path.join(srv_dir, basename)
# Test to see if already mounted (bound)
cmd = ['findmnt', dest]
proc = subprocess.Popen(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT)
proc.wait()
if proc.returncode:
print 'mounting:', path, dest
cmd = ['mount', '--bind', path, dest]
proc = subprocess.Popen(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT)
proc.wait()
elif umount:
cmd = ['umount', dest]
proc = subprocess.Popen(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT)
proc.wait()
# Bind custom modules
bind_dirs(umount)
if not BIND:
sys.exit()
salt_call()<|fim▁end|> | _bind('outputters', umount=umount)
_bind('utils', umount=umount)
if __name__ == '__main__': |
<|file_name|>sparkline.rs<|end_file_name|><|fim▁begin|>use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
}
impl Ascii {
pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self {
Self {<|fim▁hole|> step,
}
}
}
impl fmt::Display for Ascii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇'];
let ticks_len = (ticks.len() - 1) as f64;
let sparkline: String = self
.data
.iter()
.step_by(self.step)
.map(|x| {
let mut i = ticks_len * (x - self.min);
if i > 0. {
i = (i / self.max).round();
}
ticks[i as usize]
})
.collect();
write!(f, "{}", sparkline)
}
}
#[test]
fn test_display() {
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 10.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 0., 1.],
step: 2,
};
assert_eq!(format!("{}", s), "▁▇");
}<|fim▁end|> | min,
max,
data, |
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>/* 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/. */
use attr::{AttrSelectorWithNamespace, ParsedAttrSelectorOperation, AttrSelectorOperator};
use attr::{ParsedCaseSensitivity, SELECTOR_WHITESPACE, NamespaceConstraint};
use cssparser::{ParseError, BasicParseError};
use cssparser::{Token, Parser as CssParser, parse_nth, ToCss, serialize_identifier, CssStringWriter};
use precomputed_hash::PrecomputedHash;
use servo_arc::{Arc, HeaderWithLength, ThinArc};
use smallvec::SmallVec;
use std::ascii::AsciiExt;
use std::borrow::{Borrow, Cow};
use std::cmp;
use std::fmt::{self, Display, Debug, Write};
use std::iter::Rev;
use std::ops::Add;
use std::slice;
use visitor::SelectorVisitor;
/// A trait that represents a pseudo-element.
pub trait PseudoElement : Sized + ToCss {
/// The `SelectorImpl` this pseudo-element is used for.
type Impl: SelectorImpl;
/// Whether the pseudo-element supports a given state selector to the right
/// of it.
fn supports_pseudo_class(
&self,
_pseudo_class: &<Self::Impl as SelectorImpl>::NonTSPseudoClass)
-> bool
{
false
}
}
fn to_ascii_lowercase(s: &str) -> Cow<str> {
if let Some(first_uppercase) = s.bytes().position(|byte| byte >= b'A' && byte <= b'Z') {
let mut string = s.to_owned();
string[first_uppercase..].make_ascii_lowercase();
string.into()
} else {
s.into()
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum SelectorParseError<'i, T> {
PseudoElementInComplexSelector,
NoQualifiedNameInAttributeSelector,
TooManyCompoundSelectorComponentsInNegation,
NegationSelectorComponentNotNamespace,
NegationSelectorComponentNotLocalName,
EmptySelector,
NonSimpleSelectorInNegation,
UnexpectedTokenInAttributeSelector,
PseudoElementExpectedColon,
PseudoElementExpectedIdent,
UnsupportedPseudoClass,
UnexpectedIdent(Cow<'i, str>),
ExpectedNamespace,
Custom(T),
}
impl<'a, T> Into<ParseError<'a, SelectorParseError<'a, T>>> for SelectorParseError<'a, T> {
fn into(self) -> ParseError<'a, SelectorParseError<'a, T>> {
ParseError::Custom(self)
}
}
macro_rules! with_all_bounds {
(
[ $( $InSelector: tt )* ]
[ $( $CommonBounds: tt )* ]
[ $( $FromStr: tt )* ]
) => {
fn from_cow_str<T>(cow: Cow<str>) -> T where T: $($FromStr)* {
match cow {
Cow::Borrowed(s) => T::from(s),
Cow::Owned(s) => T::from(s),
}
}
/// This trait allows to define the parser implementation in regards
/// of pseudo-classes/elements
///
/// NB: We need Clone so that we can derive(Clone) on struct with that
/// are parameterized on SelectorImpl. See
/// https://github.com/rust-lang/rust/issues/26925
pub trait SelectorImpl: Clone + Sized + 'static {
type AttrValue: $($InSelector)*;
type Identifier: $($InSelector)* + PrecomputedHash;
type ClassName: $($InSelector)* + PrecomputedHash;
type LocalName: $($InSelector)* + Borrow<Self::BorrowedLocalName> + PrecomputedHash;
type NamespaceUrl: $($CommonBounds)* + Default + Borrow<Self::BorrowedNamespaceUrl> + PrecomputedHash;
type NamespacePrefix: $($InSelector)* + Default;
type BorrowedNamespaceUrl: ?Sized + Eq;
type BorrowedLocalName: ?Sized + Eq;
/// non tree-structural pseudo-classes
/// (see: https://drafts.csswg.org/selectors/#structural-pseudos)
type NonTSPseudoClass: $($CommonBounds)* + Sized + ToCss + SelectorMethods<Impl = Self>;
/// pseudo-elements
type PseudoElement: $($CommonBounds)* + PseudoElement<Impl = Self>;
}
}
}
macro_rules! with_bounds {
( [ $( $CommonBounds: tt )* ] [ $( $FromStr: tt )* ]) => {
with_all_bounds! {
[$($CommonBounds)* + $($FromStr)* + Display]
[$($CommonBounds)*]
[$($FromStr)*]
}
}
}
with_bounds! {
[Clone + Eq]
[From<String> + for<'a> From<&'a str>]
}
pub trait Parser<'i> {
type Impl: SelectorImpl;
type Error: 'i;
/// This function can return an "Err" pseudo-element in order to support CSS2.1
/// pseudo-elements.
fn parse_non_ts_pseudo_class(&self, name: Cow<'i, str>)
-> Result<<Self::Impl as SelectorImpl>::NonTSPseudoClass,
ParseError<'i, SelectorParseError<'i, Self::Error>>> {
Err(ParseError::Custom(SelectorParseError::UnexpectedIdent(name)))
}
fn parse_non_ts_functional_pseudo_class<'t>
(&self, name: Cow<'i, str>, _arguments: &mut CssParser<'i, 't>)
-> Result<<Self::Impl as SelectorImpl>::NonTSPseudoClass,
ParseError<'i, SelectorParseError<'i, Self::Error>>>
{
Err(ParseError::Custom(SelectorParseError::UnexpectedIdent(name)))
}
fn parse_pseudo_element(&self, name: Cow<'i, str>)
-> Result<<Self::Impl as SelectorImpl>::PseudoElement,
ParseError<'i, SelectorParseError<'i, Self::Error>>> {
Err(ParseError::Custom(SelectorParseError::UnexpectedIdent(name)))
}
fn default_namespace(&self) -> Option<<Self::Impl as SelectorImpl>::NamespaceUrl> {
None
}
fn namespace_for_prefix(&self, _prefix: &<Self::Impl as SelectorImpl>::NamespacePrefix)
-> Option<<Self::Impl as SelectorImpl>::NamespaceUrl> {
None
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SelectorAndHashes<Impl: SelectorImpl> {
pub selector: Selector<Impl>,
pub hashes: AncestorHashes,
}
impl<Impl: SelectorImpl> SelectorAndHashes<Impl> {
pub fn new(selector: Selector<Impl>) -> Self {
let hashes = AncestorHashes::new(&selector);
Self::new_with_hashes(selector, hashes)
}
pub fn new_with_hashes(selector: Selector<Impl>, hashes: AncestorHashes) -> Self {
SelectorAndHashes {
selector: selector,
hashes: hashes,
}
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SelectorList<Impl: SelectorImpl>(pub Vec<SelectorAndHashes<Impl>>);
impl<Impl: SelectorImpl> SelectorList<Impl> {
/// Parse a comma-separated list of Selectors.
/// https://drafts.csswg.org/selectors/#grouping
///
/// Return the Selectors or Err if there is an invalid selector.
pub fn parse<'i, 't, P, E>(parser: &P, input: &mut CssParser<'i, 't>)
-> Result<Self, ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E> {
input.parse_comma_separated(|input| parse_selector(parser, input).map(SelectorAndHashes::new))
.map(SelectorList)
}
/// Creates a SelectorList from a Vec of selectors. Used in tests.
pub fn from_vec(v: Vec<Selector<Impl>>) -> Self {
SelectorList(v.into_iter().map(SelectorAndHashes::new).collect())
}
pub fn to_css_from_index<W>(&self, from_index: usize, dest: &mut W)
-> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter().skip(from_index);
let first = match iter.next() {
Some(f) => f,
None => return Ok(()),
};
first.selector.to_css(dest)?;
for selector_and_hashes in iter {
dest.write_str(", ")?;
selector_and_hashes.selector.to_css(dest)?;
}
Ok(())
}
}
/// Copied from Gecko, who copied it from WebKit. Note that increasing the
/// number of hashes here will adversely affect the cache hit when fast-
/// rejecting long lists of Rules with inline hashes.
const NUM_ANCESTOR_HASHES: usize = 4;
/// Ancestor hashes for the bloom filter. We precompute these and store them
/// inline with selectors to optimize cache performance during matching.
/// This matters a lot.
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct AncestorHashes(pub [u32; NUM_ANCESTOR_HASHES]);
impl AncestorHashes {
pub fn new<Impl: SelectorImpl>(s: &Selector<Impl>) -> Self {
Self::from_iter(s.iter())
}
pub fn from_iter<Impl: SelectorImpl>(iter: SelectorIter<Impl>) -> Self {
let mut hashes = [0; NUM_ANCESTOR_HASHES];
// Compute ancestor hashes for the bloom filter.
let mut hash_iter = AncestorIter::new(iter)
.map(|x| x.ancestor_hash())
.filter(|x| x.is_some())
.map(|x| x.unwrap());
for i in 0..NUM_ANCESTOR_HASHES {
hashes[i] = match hash_iter.next() {
Some(x) => x,
None => break,
}
}
AncestorHashes(hashes)
}
}
const HAS_PSEUDO_BIT: u32 = 1 << 30;
pub trait SelectorMethods {
type Impl: SelectorImpl;
fn visit<V>(&self, visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Self::Impl>;
}
impl<Impl: SelectorImpl> SelectorMethods for Selector<Impl> {
type Impl = Impl;
fn visit<V>(&self, visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Impl>,
{
let mut current = self.iter();
let mut combinator = None;
loop {
if !visitor.visit_complex_selector(current.clone(), combinator) {
return false;
}
for selector in &mut current {
if !selector.visit(visitor) {
return false;
}
}
combinator = current.next_sequence();
if combinator.is_none() {
break;
}
}
true
}
}
impl<Impl: SelectorImpl> SelectorMethods for Component<Impl> {
type Impl = Impl;
fn visit<V>(&self, visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Impl>,
{
use self::Component::*;
if !visitor.visit_simple_selector(self) {
return false;
}
match *self {
Negation(ref negated) => {
for component in negated.iter() {
if !component.visit(visitor) {
return false;
}
}
}
AttributeInNoNamespaceExists { ref local_name, ref local_name_lower } => {
if !visitor.visit_attribute_selector(
&NamespaceConstraint::Specific(&namespace_empty_string::<Impl>()),
local_name,
local_name_lower,
) {
return false;
}
}
AttributeInNoNamespace { ref local_name, ref local_name_lower, never_matches, .. }
if !never_matches => {
if !visitor.visit_attribute_selector(
&NamespaceConstraint::Specific(&namespace_empty_string::<Impl>()),
local_name,
local_name_lower,
) {
return false;
}
}
AttributeOther(ref attr_selector) if !attr_selector.never_matches => {
if !visitor.visit_attribute_selector(
&attr_selector.namespace(),
&attr_selector.local_name,
&attr_selector.local_name_lower,
) {
return false;
}
}
NonTSPseudoClass(ref pseudo_class) => {
if !pseudo_class.visit(visitor) {
return false;
}
},
_ => {}
}
true
}
}
pub fn namespace_empty_string<Impl: SelectorImpl>() -> Impl::NamespaceUrl {
// Rust type’s default, not default namespace
Impl::NamespaceUrl::default()
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct SpecificityAndFlags(u32);
impl SpecificityAndFlags {
fn specificity(&self) -> u32 {
self.0 & !HAS_PSEUDO_BIT
}
fn has_pseudo_element(&self) -> bool {
(self.0 & HAS_PSEUDO_BIT) != 0
}
}
/// A Selector stores a sequence of simple selectors and combinators. The
/// iterator classes allow callers to iterate at either the raw sequence level or
/// at the level of sequences of simple selectors separated by combinators. Most
/// callers want the higher-level iterator.
///
/// We store selectors internally left-to-right (in parsing order), but the
/// canonical iteration order is right-to-left (selector matching order). The
/// iterators abstract over these details.
#[derive(Clone, Eq, PartialEq)]
pub struct Selector<Impl: SelectorImpl>(ThinArc<SpecificityAndFlags, Component<Impl>>);
impl<Impl: SelectorImpl> Selector<Impl> {
pub fn specificity(&self) -> u32 {
self.0.header.header.specificity()
}
pub fn has_pseudo_element(&self) -> bool {
self.0.header.header.has_pseudo_element()
}
pub fn pseudo_element(&self) -> Option<&Impl::PseudoElement> {
if !self.has_pseudo_element() {
return None
}
for component in self.iter() {
if let Component::PseudoElement(ref pseudo) = *component {
return Some(pseudo)
}
}
debug_assert!(false, "has_pseudo_element lied!");
None
}
/// Whether this selector (pseudo-element part excluded) matches every element.
///
/// Used for "pre-computed" pseudo-elements in components/style/stylist.rs
pub fn is_universal(&self) -> bool {
self.iter_raw().all(|c| matches!(*c,
Component::ExplicitUniversalType |
Component::ExplicitAnyNamespace |
Component::Combinator(Combinator::PseudoElement) |
Component::PseudoElement(..)
))
}
/// Returns an iterator over the next sequence of simple selectors. When
/// a combinator is reached, the iterator will return None, and
/// next_sequence() may be called to continue to the next sequence.
pub fn iter(&self) -> SelectorIter<Impl> {
SelectorIter {
iter: self.iter_raw(),
next_combinator: None,
}
}
pub fn iter_from(&self, offset: usize) -> SelectorIter<Impl> {
// Note: selectors are stored left-to-right but logical order is right-to-left.
let iter = self.0.slice[..(self.0.slice.len() - offset)].iter().rev();
SelectorIter {
iter: iter,
next_combinator: None,
}
}
/// Returns an iterator over the entire sequence of simple selectors and combinators,
/// from right to left.
pub fn iter_raw(&self) -> Rev<slice::Iter<Component<Impl>>> {
self.iter_raw_rev().rev()
}
/// Returns an iterator over the entire sequence of simple selectors and combinators,
/// from left to right.
pub fn iter_raw_rev(&self) -> slice::Iter<Component<Impl>> {
self.0.slice.iter()
}
/// Creates a Selector from a vec of Components. Used in tests.
pub fn from_vec(vec: Vec<Component<Impl>>, specificity_and_flags: u32) -> Self {
let header = HeaderWithLength::new(SpecificityAndFlags(specificity_and_flags), vec.len());
Selector(Arc::into_thin(Arc::from_header_and_iter(header, vec.into_iter())))
}
}
#[derive(Clone)]
pub struct SelectorIter<'a, Impl: 'a + SelectorImpl> {
iter: Rev<slice::Iter<'a, Component<Impl>>>,
next_combinator: Option<Combinator>,
}
impl<'a, Impl: 'a + SelectorImpl> SelectorIter<'a, Impl> {
/// Prepares this iterator to point to the next sequence to the left,
/// returning the combinator if the sequence was found.
pub fn next_sequence(&mut self) -> Option<Combinator> {
self.next_combinator.take()
}
}
impl<'a, Impl: SelectorImpl> Iterator for SelectorIter<'a, Impl> {
type Item = &'a Component<Impl>;
fn next(&mut self) -> Option<Self::Item> {
debug_assert!(self.next_combinator.is_none(),
"You should call next_sequence!");
match self.iter.next() {
None => None,
Some(&Component::Combinator(c)) => {
self.next_combinator = Some(c);
None
},
Some(x) => Some(x),
}
}
}
impl<'a, Impl: SelectorImpl> fmt::Debug for SelectorIter<'a, Impl> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let iter = self.iter.clone().rev();
for component in iter {
component.to_css(f)?
}
Ok(())
}
}
/// An iterator over all simple selectors belonging to ancestors.
pub struct AncestorIter<'a, Impl: 'a + SelectorImpl>(SelectorIter<'a, Impl>);
impl<'a, Impl: 'a + SelectorImpl> AncestorIter<'a, Impl> {
/// Creates an AncestorIter. The passed-in iterator is assumed to point to
/// the beginning of the child sequence, which will be skipped.
fn new(inner: SelectorIter<'a, Impl>) -> Self {
let mut result = AncestorIter(inner);
result.skip_until_ancestor();
result
}
/// Skips a sequence of simple selectors and all subsequent sequences until
/// a non-pseudo-element ancestor combinator is reached.
fn skip_until_ancestor(&mut self) {
loop {
while self.0.next().is_some() {}
// If this is ever changed to stop at the "pseudo-element"
// combinator, we will need to fix the way we compute hashes for
// revalidation selectors.
if self.0.next_sequence().map_or(true, |x| matches!(x, Combinator::Child | Combinator::Descendant)) {
break;
}
}
}
}
impl<'a, Impl: SelectorImpl> Iterator for AncestorIter<'a, Impl> {
type Item = &'a Component<Impl>;
fn next(&mut self) -> Option<Self::Item> {
// Grab the next simple selector in the sequence if available.
let next = self.0.next();
if next.is_some() {
return next;
}
// See if there are more sequences. If so, skip any non-ancestor sequences.
if let Some(combinator) = self.0.next_sequence() {
if !matches!(combinator, Combinator::Child | Combinator::Descendant) {
self.skip_until_ancestor();
}
}
self.0.next()
}
}
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Combinator {
Child, // >
Descendant, // space
NextSibling, // +
LaterSibling, // ~
/// A dummy combinator we use to the left of pseudo-elements.
///
/// It serializes as the empty string, and acts effectively as a child
/// combinator in most cases. If we ever actually start using a child
/// combinator for this, we will need to fix up the way hashes are computed
/// for revalidation selectors.
PseudoElement,
}
impl Combinator {
/// Returns true if this combinator is a child or descendant combinator.
pub fn is_ancestor(&self) -> bool {
matches!(*self, Combinator::Child |
Combinator::Descendant |
Combinator::PseudoElement)
}
/// Returns true if this combinator is a pseudo-element combinator.
pub fn is_pseudo_element(&self) -> bool {
matches!(*self, Combinator::PseudoElement)
}
/// Returns true if this combinator is a next- or later-sibling combinator.
pub fn is_sibling(&self) -> bool {
matches!(*self, Combinator::NextSibling | Combinator::LaterSibling)
}
}
/// A CSS simple selector or combinator. We store both in the same enum for
/// optimal packing and cache performance, see [1].
///
/// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1357973
#[derive(Eq, PartialEq, Clone)]
pub enum Component<Impl: SelectorImpl> {
Combinator(Combinator),
ExplicitAnyNamespace,
ExplicitNoNamespace,
DefaultNamespace(Impl::NamespaceUrl),
Namespace(Impl::NamespacePrefix, Impl::NamespaceUrl),
ExplicitUniversalType,
LocalName(LocalName<Impl>),
ID(Impl::Identifier),
Class(Impl::ClassName),
AttributeInNoNamespaceExists {
local_name: Impl::LocalName,
local_name_lower: Impl::LocalName,
},
AttributeInNoNamespace {
local_name: Impl::LocalName,
local_name_lower: Impl::LocalName,
operator: AttrSelectorOperator,
value: Impl::AttrValue,
case_sensitivity: ParsedCaseSensitivity,
never_matches: bool,
},
// Use a Box in the less common cases with more data to keep size_of::<Component>() small.
AttributeOther(Box<AttrSelectorWithNamespace<Impl>>),
// Pseudo-classes
//
// CSS3 Negation only takes a simple simple selector, but we still need to
// treat it as a compound selector because it might be a type selector which
// we represent as a namespace and a localname.
//
// Note: if/when we upgrade this to CSS4, which supports combinators, we
// need to think about how this should interact with visit_complex_selector,
// and what the consumers of those APIs should do about the presence of
// combinators in negation.
Negation(Box<[Component<Impl>]>),
FirstChild, LastChild, OnlyChild,
Root,
Empty,
NthChild(i32, i32),
NthLastChild(i32, i32),
NthOfType(i32, i32),
NthLastOfType(i32, i32),
FirstOfType,
LastOfType,
OnlyOfType,
NonTSPseudoClass(Impl::NonTSPseudoClass),
PseudoElement(Impl::PseudoElement),
}
impl<Impl: SelectorImpl> Component<Impl> {
/// Compute the ancestor hash to check against the bloom filter.
pub fn ancestor_hash(&self) -> Option<u32> {
match *self {
Component::LocalName(LocalName { ref name, ref lower_name }) => {
// Only insert the local-name into the filter if it's all lowercase.
// Otherwise we would need to test both hashes, and our data structures
// aren't really set up for that.
if name == lower_name {
Some(name.precomputed_hash())
} else {
None
}
},
Component::DefaultNamespace(ref url) |
Component::Namespace(_, ref url) => {
Some(url.precomputed_hash())
},
Component::ID(ref id) => {
Some(id.precomputed_hash())
},
Component::Class(ref class) => {
Some(class.precomputed_hash())
},
_ => None,
}
}
/// Returns true if this is a combinator.
pub fn is_combinator(&self) -> bool {
matches!(*self, Component::Combinator(_))
}
/// Returns the value as a combinator if applicable, None otherwise.
pub fn as_combinator(&self) -> Option<Combinator> {
match *self {
Component::Combinator(c) => Some(c),
_ => None,
}
}
}
#[derive(Eq, PartialEq, Clone)]
pub struct LocalName<Impl: SelectorImpl> {
pub name: Impl::LocalName,
pub lower_name: Impl::LocalName,
}
impl<Impl: SelectorImpl> Debug for Selector<Impl> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Selector(")?;
self.to_css(f)?;
write!(f, ", specificity = 0x{:x})", self.specificity())
}
}
impl<Impl: SelectorImpl> Debug for Component<Impl> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_css(f) }
}
impl<Impl: SelectorImpl> Debug for AttrSelectorWithNamespace<Impl> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_css(f) }
}
impl<Impl: SelectorImpl> Debug for LocalName<Impl> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_css(f) }
}
impl<Impl: SelectorImpl> ToCss for SelectorList<Impl> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.to_css_from_index(/* from_index = */ 0, dest)
}
}
impl<Impl: SelectorImpl> ToCss for Selector<Impl> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
for item in self.iter_raw_rev() {
item.to_css(dest)?;
}
Ok(())
}
}
impl ToCss for Combinator {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
Combinator::Child => dest.write_str(" > "),
Combinator::Descendant => dest.write_str(" "),
Combinator::NextSibling => dest.write_str(" + "),
Combinator::LaterSibling => dest.write_str(" ~ "),
Combinator::PseudoElement => Ok(()),
}
}
}
impl<Impl: SelectorImpl> ToCss for Component<Impl> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
use self::Component::*;
match *self {
Combinator(ref c) => {
c.to_css(dest)
}
PseudoElement(ref p) => {
p.to_css(dest)
}
ID(ref s) => {
dest.write_char('#')?;
display_to_css_identifier(s, dest)
}
Class(ref s) => {
dest.write_char('.')?;
display_to_css_identifier(s, dest)
}
LocalName(ref s) => s.to_css(dest),
ExplicitUniversalType => dest.write_char('*'),
DefaultNamespace(_) => Ok(()),
ExplicitNoNamespace => dest.write_char('|'),
ExplicitAnyNamespace => dest.write_str("*|"),
Namespace(ref prefix, _) => {
display_to_css_identifier(prefix, dest)?;
dest.write_char('|')
}
AttributeInNoNamespaceExists { ref local_name, .. } => {
dest.write_char('[')?;
display_to_css_identifier(local_name, dest)?;
dest.write_char(']')
}
AttributeInNoNamespace { ref local_name, operator, ref value, case_sensitivity, .. } => {
dest.write_char('[')?;
display_to_css_identifier(local_name, dest)?;
operator.to_css(dest)?;
dest.write_char('"')?;
write!(CssStringWriter::new(dest), "{}", value)?;
dest.write_char('"')?;
match case_sensitivity {
ParsedCaseSensitivity::CaseSensitive |
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {},
ParsedCaseSensitivity::AsciiCaseInsensitive => dest.write_str(" i")?,
}
dest.write_char(']')
}
AttributeOther(ref attr_selector) => attr_selector.to_css(dest),
// Pseudo-classes
Negation(ref arg) => {
dest.write_str(":not(")?;
debug_assert!(single_simple_selector(arg));
for component in arg.iter() {
component.to_css(dest)?;
}
dest.write_str(")")
}
FirstChild => dest.write_str(":first-child"),
LastChild => dest.write_str(":last-child"),
OnlyChild => dest.write_str(":only-child"),
Root => dest.write_str(":root"),
Empty => dest.write_str(":empty"),
FirstOfType => dest.write_str(":first-of-type"),
LastOfType => dest.write_str(":last-of-type"),
OnlyOfType => dest.write_str(":only-of-type"),
NthChild(a, b) => write!(dest, ":nth-child({}n{:+})", a, b),
NthLastChild(a, b) => write!(dest, ":nth-last-child({}n{:+})", a, b),
NthOfType(a, b) => write!(dest, ":nth-of-type({}n{:+})", a, b),
NthLastOfType(a, b) => write!(dest, ":nth-last-of-type({}n{:+})", a, b),
NonTSPseudoClass(ref pseudo) => pseudo.to_css(dest),
}
}
}
impl<Impl: SelectorImpl> ToCss for AttrSelectorWithNamespace<Impl> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_char('[')?;
match self.namespace {
NamespaceConstraint::Specific((ref prefix, _)) => {
display_to_css_identifier(prefix, dest)?;
dest.write_char('|')?
}
NamespaceConstraint::Any => {
dest.write_str("*|")?
}
}
display_to_css_identifier(&self.local_name, dest)?;
match self.operation {
ParsedAttrSelectorOperation::Exists => {},
ParsedAttrSelectorOperation::WithValue {
operator, case_sensitivity, ref expected_value
} => {
operator.to_css(dest)?;
dest.write_char('"')?;
write!(CssStringWriter::new(dest), "{}", expected_value)?;
dest.write_char('"')?;
match case_sensitivity {
ParsedCaseSensitivity::CaseSensitive |
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {},
ParsedCaseSensitivity::AsciiCaseInsensitive => dest.write_str(" i")?,
}
},
}
dest.write_char(']')
}
}
impl<Impl: SelectorImpl> ToCss for LocalName<Impl> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
display_to_css_identifier(&self.name, dest)
}
}
/// Serialize the output of Display as a CSS identifier
fn display_to_css_identifier<T: Display, W: fmt::Write>(x: &T, dest: &mut W) -> fmt::Result {
// FIXME(SimonSapin): it is possible to avoid this heap allocation
// by creating a stream adapter like cssparser::CssStringWriter
// that holds and writes to `&mut W` and itself implements `fmt::Write`.
//
// I haven’t done this yet because it would require somewhat complex and fragile state machine
// to support in `fmt::Write::write_char` cases that,
// in `serialize_identifier` (which has the full value as a `&str` slice),
// can be expressed as
// `string.starts_with("--")`, `string == "-"`, `string.starts_with("-")`, etc.
//
// And I don’t even know if this would be a performance win: jemalloc is good at what it does
// and the state machine might be slower than `serialize_identifier` as currently written.
let string = x.to_string();
serialize_identifier(&string, dest)
}
const MAX_10BIT: u32 = (1u32 << 10) - 1;
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
struct Specificity {
id_selectors: u32,
class_like_selectors: u32,
element_selectors: u32,
}
impl Add for Specificity {
type Output = Specificity;
fn add(self, rhs: Specificity) -> Specificity {
Specificity {
id_selectors: self.id_selectors + rhs.id_selectors,
class_like_selectors:
self.class_like_selectors + rhs.class_like_selectors,
element_selectors:
self.element_selectors + rhs.element_selectors,
}
}
}
impl Default for Specificity {
fn default() -> Specificity {
Specificity {
id_selectors: 0,
class_like_selectors: 0,
element_selectors: 0,
}
}
}
impl From<u32> for Specificity {
fn from(value: u32) -> Specificity {
assert!(value <= MAX_10BIT << 20 | MAX_10BIT << 10 | MAX_10BIT);
Specificity {
id_selectors: value >> 20,
class_like_selectors: (value >> 10) & MAX_10BIT,
element_selectors: value & MAX_10BIT,
}
}
}
impl From<Specificity> for u32 {
fn from(specificity: Specificity) -> u32 {
cmp::min(specificity.id_selectors, MAX_10BIT) << 20
| cmp::min(specificity.class_like_selectors, MAX_10BIT) << 10
| cmp::min(specificity.element_selectors, MAX_10BIT)
}
}
fn specificity<Impl>(iter: SelectorIter<Impl>) -> u32
where Impl: SelectorImpl
{
complex_selector_specificity(iter).into()
}
fn complex_selector_specificity<Impl>(mut iter: SelectorIter<Impl>)
-> Specificity
where Impl: SelectorImpl
{
fn simple_selector_specificity<Impl>(simple_selector: &Component<Impl>,
specificity: &mut Specificity)
where Impl: SelectorImpl
{
match *simple_selector {
Component::Combinator(..) => unreachable!(),
Component::PseudoElement(..) |
Component::LocalName(..) => {
specificity.element_selectors += 1
}
Component::ID(..) => {
specificity.id_selectors += 1
}
Component::Class(..) |
Component::AttributeInNoNamespace { .. } |
Component::AttributeInNoNamespaceExists { .. } |
Component::AttributeOther(..) |
Component::FirstChild | Component::LastChild |
Component::OnlyChild | Component::Root |
Component::Empty |
Component::NthChild(..) |
Component::NthLastChild(..) |
Component::NthOfType(..) |
Component::NthLastOfType(..) |
Component::FirstOfType | Component::LastOfType |
Component::OnlyOfType |
Component::NonTSPseudoClass(..) => {
specificity.class_like_selectors += 1
}
Component::ExplicitUniversalType |
Component::ExplicitAnyNamespace |
Component::ExplicitNoNamespace |
Component::DefaultNamespace(..) |
Component::Namespace(..) => {
// Does not affect specificity
}
Component::Negation(ref negated) => {
for ss in negated.iter() {
simple_selector_specificity(&ss, specificity);
}
}
}
}
let mut specificity = Default::default();
loop {
for simple_selector in &mut iter {
simple_selector_specificity(&simple_selector, &mut specificity);
}
if iter.next_sequence().is_none() {
break;
}
}
specificity
}
/// We make this large because the result of parsing a selector is fed into a new
/// Arc-ed allocation, so any spilled vec would be a wasted allocation. Also,
/// Components are large enough that we don't have much cache locality benefit
/// from reserving stack space for fewer of them.
type ParseVec<Impl> = SmallVec<[Component<Impl>; 32]>;
/// Build up a Selector.
/// selector : simple_selector_sequence [ combinator simple_selector_sequence ]* ;
///
/// `Err` means invalid selector.
fn parse_selector<'i, 't, P, E, Impl>(
parser: &P,
input: &mut CssParser<'i, 't>)
-> Result<Selector<Impl>, ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
let mut sequence = ParseVec::new();
let mut parsed_pseudo_element;
'outer_loop: loop {
// Parse a sequence of simple selectors.
parsed_pseudo_element =
parse_compound_selector(parser, input, &mut sequence,
/* inside_negation = */ false)?;
if parsed_pseudo_element {
break;
}
// Parse a combinator.
let combinator;
let mut any_whitespace = false;
loop {
let position = input.position();
match input.next_including_whitespace() {
Err(_e) => break 'outer_loop,
Ok(Token::WhiteSpace(_)) => any_whitespace = true,
Ok(Token::Delim('>')) => {
combinator = Combinator::Child;
break
}
Ok(Token::Delim('+')) => {
combinator = Combinator::NextSibling;
break
}
Ok(Token::Delim('~')) => {
combinator = Combinator::LaterSibling;
break
}
Ok(_) => {
input.reset(position);
if any_whitespace {
combinator = Combinator::Descendant;
break
} else {
break 'outer_loop
}
}
}
}
sequence.push(Component::Combinator(combinator));
}
let mut spec = SpecificityAndFlags(specificity(SelectorIter {
iter: sequence.iter().rev(),
next_combinator: None,
}));
if parsed_pseudo_element {
spec.0 |= HAS_PSEUDO_BIT;
}
let header = HeaderWithLength::new(spec, sequence.len());
let complex = Selector(Arc::into_thin(Arc::from_header_and_iter(header, sequence.into_iter())));
Ok(complex)
}
impl<Impl: SelectorImpl> Selector<Impl> {
/// Parse a selector, without any pseudo-element.
pub fn parse<'i, 't, P, E>(parser: &P, input: &mut CssParser<'i, 't>)
-> Result<Self, ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>
{
let selector = parse_selector(parser, input)?;
if selector.has_pseudo_element() {
return Err(ParseError::Custom(SelectorParseError::PseudoElementInComplexSelector))
}
Ok(selector)
}
}
/// * `Err(())`: Invalid selector, abort
/// * `Ok(None)`: Not a type selector, could be something else. `input` was not consumed.
/// * `Ok(Some(vec))`: Length 0 (`*|*`), 1 (`*|E` or `ns|*`) or 2 (`|E` or `ns|E`)
fn parse_type_selector<'i, 't, P, E, Impl>(parser: &P, input: &mut CssParser<'i, 't>,
sequence: &mut ParseVec<Impl>)
-> Result<bool, ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
match parse_qualified_name(parser, input, /* in_attr_selector = */ false)? {
None => Ok(false),
Some((namespace, local_name)) => {
match namespace {
QNamePrefix::ImplicitAnyNamespace => {}
QNamePrefix::ImplicitDefaultNamespace(url) => {
sequence.push(Component::DefaultNamespace(url))
}
QNamePrefix::ExplicitNamespace(prefix, url) => {
sequence.push(Component::Namespace(prefix, url))
}
QNamePrefix::ExplicitNoNamespace => {
sequence.push(Component::ExplicitNoNamespace)
}
QNamePrefix::ExplicitAnyNamespace => {
sequence.push(Component::ExplicitAnyNamespace)
}
QNamePrefix::ImplicitNoNamespace => {
unreachable!() // Not returned with in_attr_selector = false
}
}
match local_name {
Some(name) => {
sequence.push(Component::LocalName(LocalName {
lower_name: from_cow_str(to_ascii_lowercase(&name)),
name: from_cow_str(name),
}))
}
None => {
sequence.push(Component::ExplicitUniversalType)
}
}
Ok(true)
}
}
}
#[derive(Debug)]
enum SimpleSelectorParseResult<Impl: SelectorImpl> {
SimpleSelector(Component<Impl>),
PseudoElement(Impl::PseudoElement),
}
#[derive(Debug)]
enum QNamePrefix<Impl: SelectorImpl> {
ImplicitNoNamespace, // `foo` in attr selectors
ImplicitAnyNamespace, // `foo` in type selectors, without a default ns
ImplicitDefaultNamespace(Impl::NamespaceUrl), // `foo` in type selectors, with a default ns
ExplicitNoNamespace, // `|foo`
ExplicitAnyNamespace, // `*|foo`
ExplicitNamespace(Impl::NamespacePrefix, Impl::NamespaceUrl), // `prefix|foo`
}
/// * `Err(())`: Invalid selector, abort
/// * `Ok(None)`: Not a simple selector, could be something else. `input` was not consumed.
/// * `Ok(Some((namespace, local_name)))`: `None` for the local name means a `*` universal selector
fn parse_qualified_name<'i, 't, P, E, Impl>
(parser: &P, input: &mut CssParser<'i, 't>,
in_attr_selector: bool)
-> Result<Option<(QNamePrefix<Impl>, Option<Cow<'i, str>>)>,
ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
let default_namespace = |local_name| {
let namespace = match parser.default_namespace() {
Some(url) => QNamePrefix::ImplicitDefaultNamespace(url),
None => QNamePrefix::ImplicitAnyNamespace,
};
Ok(Some((namespace, local_name)))
};
let explicit_namespace = |input: &mut CssParser<'i, 't>, namespace| {
match input.next_including_whitespace() {
Ok(Token::Delim('*')) if !in_attr_selector => {
Ok(Some((namespace, None)))
},
Ok(Token::Ident(local_name)) => {
Ok(Some((namespace, Some(local_name))))
},
Ok(t) => Err(ParseError::Basic(BasicParseError::UnexpectedToken(t))),
Err(e) => Err(ParseError::Basic(e)),
}
};
let position = input.position();
match input.next_including_whitespace() {
Ok(Token::Ident(value)) => {
let position = input.position();
match input.next_including_whitespace() {
Ok(Token::Delim('|')) => {
let prefix = from_cow_str(value);
let result = parser.namespace_for_prefix(&prefix);
let url = result.ok_or(ParseError::Custom(SelectorParseError::ExpectedNamespace))?;
explicit_namespace(input, QNamePrefix::ExplicitNamespace(prefix, url))
},
_ => {
input.reset(position);
if in_attr_selector {
Ok(Some((QNamePrefix::ImplicitNoNamespace, Some(value))))
} else {
default_namespace(Some(value))
}
}
}
},
Ok(Token::Delim('*')) => {
let position = input.position();
match input.next_including_whitespace() {
Ok(Token::Delim('|')) => {
explicit_namespace(input, QNamePrefix::ExplicitAnyNamespace)
}
result => {
input.reset(position);
if in_attr_selector {
match result {
Ok(t) => Err(ParseError::Basic(BasicParseError::UnexpectedToken(t))),
Err(e) => Err(ParseError::Basic(e)),
}
} else {
default_namespace(None)
}
},
}
},
Ok(Token::Delim('|')) => {
explicit_namespace(input, QNamePrefix::ExplicitNoNamespace)
}
_ => {
input.reset(position);
Ok(None)
}
}
}
fn parse_attribute_selector<'i, 't, P, E, Impl>(parser: &P, input: &mut CssParser<'i, 't>)
-> Result<Component<Impl>,
ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
let namespace;
let local_name;
match parse_qualified_name(parser, input, /* in_attr_selector = */ true)? {
None => return Err(ParseError::Custom(SelectorParseError::NoQualifiedNameInAttributeSelector)),
Some((_, None)) => unreachable!(),
Some((ns, Some(ln))) => {
local_name = ln;
namespace = match ns {
QNamePrefix::ImplicitNoNamespace |
QNamePrefix::ExplicitNoNamespace => {
None
}
QNamePrefix::ExplicitNamespace(prefix, url) => {
Some(NamespaceConstraint::Specific((prefix, url)))
}
QNamePrefix::ExplicitAnyNamespace => {
Some(NamespaceConstraint::Any)
}
QNamePrefix::ImplicitAnyNamespace |
QNamePrefix::ImplicitDefaultNamespace(_) => {
unreachable!() // Not returned with in_attr_selector = true
}
}
}
}
let operator;
let value;
let never_matches;
match input.next() {
// [foo]
Err(_) => {
let local_name_lower = from_cow_str(to_ascii_lowercase(&local_name));
let local_name = from_cow_str(local_name);
if let Some(namespace) = namespace {
return Ok(Component::AttributeOther(Box::new(AttrSelectorWithNamespace {
namespace: namespace,
local_name: local_name,
local_name_lower: local_name_lower,
operation: ParsedAttrSelectorOperation::Exists,
never_matches: false,
})))
} else {
return Ok(Component::AttributeInNoNamespaceExists {
local_name: local_name,
local_name_lower: local_name_lower,
})
}
}
// [foo=bar]
Ok(Token::Delim('=')) => {
value = input.expect_ident_or_string()?;
never_matches = false;
operator = AttrSelectorOperator::Equal;
}
// [foo~=bar]
Ok(Token::IncludeMatch) => {
value = input.expect_ident_or_string()?;
never_matches = value.is_empty() || value.contains(SELECTOR_WHITESPACE);
operator = AttrSelectorOperator::Includes;
}
// [foo|=bar]
Ok(Token::DashMatch) => {
value = input.expect_ident_or_string()?;
never_matches = false;
operator = AttrSelectorOperator::DashMatch;
}
// [foo^=bar]
Ok(Token::PrefixMatch) => {
value = input.expect_ident_or_string()?;
never_matches = value.is_empty();
operator = AttrSelectorOperator::Prefix;
}
// [foo*=bar]
Ok(Token::SubstringMatch) => {
value = input.expect_ident_or_string()?;
never_matches = value.is_empty();
operator = AttrSelectorOperator::Substring;
}
// [foo$=bar]
Ok(Token::SuffixMatch) => {
value = input.expect_ident_or_string()?;
never_matches = value.is_empty();
operator = AttrSelectorOperator::Suffix;
}
_ => return Err(SelectorParseError::UnexpectedTokenInAttributeSelector.into())
}
let mut case_sensitivity = parse_attribute_flags(input)?;
let value = from_cow_str(value);
let local_name_lower;
{
let local_name_lower_cow = to_ascii_lowercase(&local_name);
if let ParsedCaseSensitivity::CaseSensitive = case_sensitivity {
if namespace.is_none() &&
include!(concat!(env!("OUT_DIR"), "/ascii_case_insensitive_html_attributes.rs"))
.contains(&*local_name_lower_cow)
{
case_sensitivity =
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
}
}
local_name_lower = from_cow_str(local_name_lower_cow);
}
let local_name = from_cow_str(local_name);
if let Some(namespace) = namespace {
Ok(Component::AttributeOther(Box::new(AttrSelectorWithNamespace {
namespace: namespace,
local_name: local_name,
local_name_lower: local_name_lower,
never_matches: never_matches,
operation: ParsedAttrSelectorOperation::WithValue {
operator: operator,
case_sensitivity: case_sensitivity,
expected_value: value,
}
})))
} else {
Ok(Component::AttributeInNoNamespace {
local_name: local_name,
local_name_lower: local_name_lower,
operator: operator,
value: value,
case_sensitivity: case_sensitivity,
never_matches: never_matches,
})
}
}
fn parse_attribute_flags<'i, 't, E>(input: &mut CssParser<'i, 't>)
-> Result<ParsedCaseSensitivity,
ParseError<'i, SelectorParseError<'i, E>>> {
match input.next() {
Err(_) => Ok(ParsedCaseSensitivity::CaseSensitive),
Ok(Token::Ident(ref value)) if value.eq_ignore_ascii_case("i") => {
Ok(ParsedCaseSensitivity::AsciiCaseInsensitive)
}
Ok(t) => Err(ParseError::Basic(BasicParseError::UnexpectedToken(t)))
}
}
/// Level 3: Parse **one** simple_selector. (Though we might insert a second
/// implied "<defaultns>|*" type selector.)
fn parse_negation<'i, 't, P, E, Impl>(parser: &P,
input: &mut CssParser<'i, 't>)
-> Result<Component<Impl>,
ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
let mut v = ParseVec::new();
parse_compound_selector(parser, input, &mut v, /* inside_negation = */ true)?;
if single_simple_selector(&v) {
Ok(Component::Negation(v.into_vec().into_boxed_slice()))
} else {
Err(ParseError::Custom(SelectorParseError::NonSimpleSelectorInNegation))
}
}
// A single type selector can be represented as two components
fn single_simple_selector<Impl: SelectorImpl>(v: &[Component<Impl>]) -> bool {
v.len() == 1 || (
v.len() == 2 &&
match v[1] {
Component::LocalName(_) | Component::ExplicitUniversalType => {
debug_assert!(matches!(v[0],
Component::ExplicitAnyNamespace |
Component::ExplicitNoNamespace |
Component::DefaultNamespace(_) |
Component::Namespace(..)
));
true
}
_ => false,
}
)
}
/// simple_selector_sequence
/// : [ type_selector | universal ] [ HASH | class | attrib | pseudo | negation ]*
/// | [ HASH | class | attrib | pseudo | negation ]+
///
/// `Err(())` means invalid selector.
///
/// The boolean represent whether a pseudo-element has been parsed.
fn parse_compound_selector<'i, 't, P, E, Impl>(
parser: &P,
input: &mut CssParser<'i, 't>,
mut sequence: &mut ParseVec<Impl>,
inside_negation: bool)
-> Result<bool, ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
// Consume any leading whitespace.
loop {
let position = input.position();
if !matches!(input.next_including_whitespace(), Ok(Token::WhiteSpace(_))) {
input.reset(position);
break
}
}
let mut empty = true;
if !parse_type_selector(parser, input, &mut sequence)? {
if let Some(url) = parser.default_namespace() {
// If there was no explicit type selector, but there is a
// default namespace, there is an implicit "<defaultns>|*" type
// selector.
//
// Note that this doesn't apply to :not() and :matches() per spec.
if !inside_negation {
sequence.push(Component::DefaultNamespace(url))
}
}
} else {
empty = false;
}
let mut pseudo = false;
loop {
match parse_one_simple_selector(parser, input, inside_negation)? {
None => break,
Some(SimpleSelectorParseResult::SimpleSelector(s)) => {
sequence.push(s);
empty = false
}
Some(SimpleSelectorParseResult::PseudoElement(p)) => {
// Try to parse state to its right.
let mut state_selectors = ParseVec::new();
loop {
match input.next_including_whitespace() {
Ok(Token::Colon) => {},
Ok(Token::WhiteSpace(_)) | Err(_) => break,
_ => return Err(SelectorParseError::PseudoElementExpectedColon.into()),
}
// TODO(emilio): Functional pseudo-classes too?
// We don't need it for now.
let name = match input.next_including_whitespace() {
Ok(Token::Ident(name)) => name,
_ => return Err(SelectorParseError::PseudoElementExpectedIdent.into()),
};
let pseudo_class =
P::parse_non_ts_pseudo_class(parser, name)?;
if !p.supports_pseudo_class(&pseudo_class) {
return Err(SelectorParseError::UnsupportedPseudoClass.into());
}
state_selectors.push(Component::NonTSPseudoClass(pseudo_class));
}
if !sequence.is_empty() {
sequence.push(Component::Combinator(Combinator::PseudoElement));
}
sequence.push(Component::PseudoElement(p));
for state_selector in state_selectors {
sequence.push(state_selector);
}
pseudo = true;
empty = false;
break
}
}
}
if empty {
// An empty selector is invalid.
Err(ParseError::Custom(SelectorParseError::EmptySelector))
} else {
Ok(pseudo)
}
}
fn parse_functional_pseudo_class<'i, 't, P, E, Impl>(parser: &P,
input: &mut CssParser<'i, 't>,
name: Cow<'i, str>,
inside_negation: bool)
-> Result<Component<Impl>,
ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
match_ignore_ascii_case! { &name,
"nth-child" => return parse_nth_pseudo_class(input, Component::NthChild),
"nth-of-type" => return parse_nth_pseudo_class(input, Component::NthOfType),
"nth-last-child" => return parse_nth_pseudo_class(input, Component::NthLastChild),
"nth-last-of-type" => return parse_nth_pseudo_class(input, Component::NthLastOfType),
"not" => {
if inside_negation {
return Err(ParseError::Custom(SelectorParseError::UnexpectedIdent("not".into())));
}
return parse_negation(parser, input)
},
_ => {}
}
P::parse_non_ts_functional_pseudo_class(parser, name, input)
.map(Component::NonTSPseudoClass)
}
fn parse_nth_pseudo_class<'i, 't, Impl, F, E>(input: &mut CssParser<'i, 't>, selector: F)
-> Result<Component<Impl>,
ParseError<'i, SelectorParseError<'i, E>>>
where Impl: SelectorImpl, F: FnOnce(i32, i32) -> Component<Impl> {
let (a, b) = parse_nth(input)?;
Ok(selector(a, b))
}
/// Parse a simple selector other than a type selector.
///
/// * `Err(())`: Invalid selector, abort
/// * `Ok(None)`: Not a simple selector, could be something else. `input` was not consumed.
/// * `Ok(Some(_))`: Parsed a simple selector or pseudo-element
fn parse_one_simple_selector<'i, 't, P, E, Impl>(parser: &P,
input: &mut CssParser<'i, 't>,
inside_negation: bool)
-> Result<Option<SimpleSelectorParseResult<Impl>>,
ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
let start_position = input.position();
match input.next_including_whitespace() {
Ok(Token::IDHash(id)) => {
let id = Component::ID(from_cow_str(id));
Ok(Some(SimpleSelectorParseResult::SimpleSelector(id)))
}
Ok(Token::Delim('.')) => {
match input.next_including_whitespace() {
Ok(Token::Ident(class)) => {
let class = Component::Class(from_cow_str(class));
Ok(Some(SimpleSelectorParseResult::SimpleSelector(class)))
}
Ok(t) => Err(ParseError::Basic(BasicParseError::UnexpectedToken(t))),
Err(e) => Err(ParseError::Basic(e)),
}
}
Ok(Token::SquareBracketBlock) => {
let attr = input.parse_nested_block(|input| parse_attribute_selector(parser, input))?;
Ok(Some(SimpleSelectorParseResult::SimpleSelector(attr)))
}
Ok(Token::Colon) => {
match input.next_including_whitespace() {
Ok(Token::Ident(name)) => {
// Supported CSS 2.1 pseudo-elements only.
// ** Do not add to this list! **
if name.eq_ignore_ascii_case("before") ||
name.eq_ignore_ascii_case("after") ||
name.eq_ignore_ascii_case("first-line") ||
name.eq_ignore_ascii_case("first-letter") {
let pseudo_element = P::parse_pseudo_element(parser, name)?;
Ok(Some(SimpleSelectorParseResult::PseudoElement(pseudo_element)))
} else {
let pseudo_class = parse_simple_pseudo_class(parser, name)?;
Ok(Some(SimpleSelectorParseResult::SimpleSelector(pseudo_class)))
}
}
Ok(Token::Function(name)) => {
let pseudo = input.parse_nested_block(|input| {
parse_functional_pseudo_class(parser, input, name, inside_negation)
})?;
Ok(Some(SimpleSelectorParseResult::SimpleSelector(pseudo)))
}
Ok(Token::Colon) => {
match input.next_including_whitespace() {
Ok(Token::Ident(name)) => {
let pseudo = P::parse_pseudo_element(parser, name)?;
Ok(Some(SimpleSelectorParseResult::PseudoElement(pseudo)))
}
Ok(t) => Err(ParseError::Basic(BasicParseError::UnexpectedToken(t))),
Err(e) => Err(ParseError::Basic(e)),
}
}
Ok(t) => Err(ParseError::Basic(BasicParseError::UnexpectedToken(t))),
Err(e) => Err(ParseError::Basic(e)),
}
}
_ => {
input.reset(start_position);
Ok(None)
}
}
}
fn parse_simple_pseudo_class<'i, P, E, Impl>(parser: &P, name: Cow<'i, str>)
-> Result<Component<Impl>,
ParseError<'i, SelectorParseError<'i, E>>>
where P: Parser<'i, Impl=Impl, Error=E>, Impl: SelectorImpl
{
(match_ignore_ascii_case! { &name,
"first-child" => Ok(Component::FirstChild),
"last-child" => Ok(Component::LastChild),
"only-child" => Ok(Component::OnlyChild),
"root" => Ok(Component::Root),
"empty" => Ok(Component::Empty),
"first-of-type" => Ok(Component::FirstOfType),
"last-of-type" => Ok(Component::LastOfType),
"only-of-type" => Ok(Component::OnlyOfType),
_ => Err(())
}).or_else(|()| {
P::parse_non_ts_pseudo_class(parser, name)
.map(Component::NonTSPseudoClass)
})
}
// NB: pub module in order to access the DummyParser
#[cfg(test)]
pub mod tests {
use cssparser::{Parser as CssParser, ToCss, serialize_identifier, ParserInput};
use parser;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use super::*;
#[derive(PartialEq, Clone, Debug, Eq)]
pub enum PseudoClass {
Hover,
Active,
Lang(String),
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum PseudoElement {
Before,
After,
}
impl parser::PseudoElement for PseudoElement {
type Impl = DummySelectorImpl;
fn supports_pseudo_class(&self, pc: &PseudoClass) -> bool {
match *pc {
PseudoClass::Hover => true,
PseudoClass::Active |
PseudoClass::Lang(..) => false,
}
}
}
impl ToCss for PseudoClass {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
PseudoClass::Hover => dest.write_str(":hover"),
PseudoClass::Active => dest.write_str(":active"),
PseudoClass::Lang(ref lang) => {
dest.write_str(":lang(")?;
serialize_identifier(lang, dest)?;
dest.write_char(')')
}
}
}
}
impl ToCss for PseudoElement {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
PseudoElement::Before => dest.write_str("::before"),
PseudoElement::After => dest.write_str("::after"),
}
}
}
impl SelectorMethods for PseudoClass {
type Impl = DummySelectorImpl;
fn visit<V>(&self, _visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Self::Impl> { true }
}
#[derive(Clone, PartialEq, Debug)]
pub struct DummySelectorImpl;
#[derive(Default)]
pub struct DummyParser {
default_ns: Option<DummyAtom>,
ns_prefixes: HashMap<DummyAtom, DummyAtom>,
}
impl SelectorImpl for DummySelectorImpl {
type AttrValue = DummyAtom;
type Identifier = DummyAtom;
type ClassName = DummyAtom;
type LocalName = DummyAtom;
type NamespaceUrl = DummyAtom;
type NamespacePrefix = DummyAtom;
type BorrowedLocalName = DummyAtom;
type BorrowedNamespaceUrl = DummyAtom;
type NonTSPseudoClass = PseudoClass;
type PseudoElement = PseudoElement;
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct DummyAtom(String);
impl fmt::Display for DummyAtom {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
<String as fmt::Display>::fmt(&self.0, fmt)
}
}
impl From<String> for DummyAtom {
fn from(string: String) -> Self {
DummyAtom(string)
}
}
impl<'a> From<&'a str> for DummyAtom {
fn from(string: &'a str) -> Self {
DummyAtom(string.into())
}
}
impl PrecomputedHash for DummyAtom {
fn precomputed_hash(&self) -> u32 {
return 0
}
}
impl<'i> Parser<'i> for DummyParser {
type Impl = DummySelectorImpl;
type Error = ();
fn parse_non_ts_pseudo_class(&self, name: Cow<'i, str>)
-> Result<PseudoClass,
ParseError<'i, SelectorParseError<'i, ()>>> {
match_ignore_ascii_case! { &name,
"hover" => Ok(PseudoClass::Hover),
"active" => Ok(PseudoClass::Active),
_ => Err(SelectorParseError::Custom(()).into())
}
}
fn parse_non_ts_functional_pseudo_class<'t>(&self, name: Cow<'i, str>,
parser: &mut CssParser<'i, 't>)
-> Result<PseudoClass,
ParseError<'i, SelectorParseError<'i, ()>>> {
match_ignore_ascii_case! { &name,
"lang" => Ok(PseudoClass::Lang(try!(parser.expect_ident_or_string()).into_owned())),
_ => Err(SelectorParseError::Custom(()).into())
}
}
fn parse_pseudo_element(&self, name: Cow<'i, str>)
-> Result<PseudoElement,
ParseError<'i, SelectorParseError<'i, ()>>> {
match_ignore_ascii_case! { &name,
"before" => Ok(PseudoElement::Before),
"after" => Ok(PseudoElement::After),
_ => Err(SelectorParseError::Custom(()).into())
}
}
fn default_namespace(&self) -> Option<DummyAtom> {
self.default_ns.clone()
}
fn namespace_for_prefix(&self, prefix: &DummyAtom) -> Option<DummyAtom> {
self.ns_prefixes.get(prefix).cloned()
}
}
fn parse<'i>(input: &'i str) -> Result<SelectorList<DummySelectorImpl>,
ParseError<'i, SelectorParseError<'i, ()>>> {
parse_ns(input, &DummyParser::default())
}
fn parse_ns<'i>(input: &'i str, parser: &DummyParser)
-> Result<SelectorList<DummySelectorImpl>,
ParseError<'i, SelectorParseError<'i, ()>>> {
let mut parser_input = ParserInput::new(input);
let result = SelectorList::parse(parser, &mut CssParser::new(&mut parser_input));
if let Ok(ref selectors) = result {
assert_eq!(selectors.0.len(), 1);
assert_eq!(selectors.0[0].selector.to_css_string(), input);
}
result
}
fn specificity(a: u32, b: u32, c: u32) -> u32 {
a << 20 | b << 10 | c
}
#[test]
fn test_empty() {
let mut input = ParserInput::new(":empty");
let list = SelectorList::parse(&DummyParser::default(), &mut CssParser::new(&mut input));
assert!(list.is_ok());
}
const MATHML: &'static str = "http://www.w3.org/1998/Math/MathML";
const SVG: &'static str = "http://www.w3.org/2000/svg";
#[test]
fn test_parsing() {
assert!(parse("").is_err()) ;
assert!(parse(":lang(4)").is_err()) ;
assert!(parse(":lang(en US)").is_err()) ;
assert_eq!(parse("EeÉ"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::LocalName(LocalName {
name: DummyAtom::from("EeÉ"),
lower_name: DummyAtom::from("eeÉ") })
), specificity(0, 0, 1))
))));
assert_eq!(parse("|e"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ExplicitNoNamespace,
Component::LocalName(LocalName {
name: DummyAtom::from("e"),
lower_name: DummyAtom::from("e")
})), specificity(0, 0, 1))
))));
// https://github.com/servo/servo/issues/16020
assert_eq!(parse("*|e"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ExplicitAnyNamespace,
Component::LocalName(LocalName {
name: DummyAtom::from("e"),
lower_name: DummyAtom::from("e")
})
), specificity(0, 0, 1))
))));
assert_eq!(parse("*"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ExplicitUniversalType,
), specificity(0, 0, 0))
))));
assert_eq!(parse("|*"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ExplicitNoNamespace,
Component::ExplicitUniversalType,
), specificity(0, 0, 0))
))));
assert_eq!(parse("*|*"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ExplicitAnyNamespace,
Component::ExplicitUniversalType,
), specificity(0, 0, 0))
))));
assert_eq!(parse(".foo:lang(en-US)"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::Class(DummyAtom::from("foo")),
Component::NonTSPseudoClass(PseudoClass::Lang("en-US".to_owned()))
), specificity(0, 2, 0))
))));
assert_eq!(parse("#bar"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ID(DummyAtom::from("bar"))
), specificity(1, 0, 0))
))));
assert_eq!(parse("e.foo#bar"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::LocalName(LocalName {
name: DummyAtom::from("e"),
lower_name: DummyAtom::from("e")
}),
Component::Class(DummyAtom::from("foo")),
Component::ID(DummyAtom::from("bar"))
), specificity(1, 1, 1))
))));
assert_eq!(parse("e.foo #bar"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::LocalName(LocalName {
name: DummyAtom::from("e"),
lower_name: DummyAtom::from("e")
}),
Component::Class(DummyAtom::from("foo")),
Component::Combinator(Combinator::Descendant),
Component::ID(DummyAtom::from("bar")),
), specificity(1, 1, 1))
))));
// Default namespace does not apply to attribute selectors
// https://github.com/mozilla/servo/pull/1652
let mut parser = DummyParser::default();
assert_eq!(parse_ns("[Foo]", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::AttributeInNoNamespaceExists {
local_name: DummyAtom::from("Foo"),
local_name_lower: DummyAtom::from("foo"),
}
), specificity(0, 1, 0))
))));
assert!(parse_ns("svg|circle", &parser).is_err());
parser.ns_prefixes.insert(DummyAtom("svg".into()), DummyAtom(SVG.into()));
assert_eq!(parse_ns("svg|circle", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::Namespace(DummyAtom("svg".into()), SVG.into()),
Component::LocalName(LocalName {
name: DummyAtom::from("circle"),
lower_name: DummyAtom::from("circle"),
})
), specificity(0, 0, 1))
))));
assert_eq!(parse_ns("svg|*", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::Namespace(DummyAtom("svg".into()), SVG.into()),
Component::ExplicitUniversalType,
), specificity(0, 0, 0))
))));
// Default namespace does not apply to attribute selectors
// https://github.com/mozilla/servo/pull/1652
// but it does apply to implicit type selectors
// https://github.com/servo/rust-selectors/pull/82
parser.default_ns = Some(MATHML.into());
assert_eq!(parse_ns("[Foo]", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::DefaultNamespace(MATHML.into()),
Component::AttributeInNoNamespaceExists {
local_name: DummyAtom::from("Foo"),
local_name_lower: DummyAtom::from("foo"),
},
), specificity(0, 1, 0))
))));
// Default namespace does apply to type selectors
assert_eq!(parse_ns("e", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::DefaultNamespace(MATHML.into()),
Component::LocalName(LocalName {
name: DummyAtom::from("e"),
lower_name: DummyAtom::from("e") }),
), specificity(0, 0, 1))
))));
assert_eq!(parse_ns("*", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::DefaultNamespace(MATHML.into()),
Component::ExplicitUniversalType,
), specificity(0, 0, 0))
))));
assert_eq!(parse_ns("*|*", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ExplicitAnyNamespace,
Component::ExplicitUniversalType,
), specificity(0, 0, 0))
))));
// Default namespace applies to universal and type selectors inside :not and :matches,
// but not otherwise.
assert_eq!(parse_ns(":not(.cl)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::DefaultNamespace(MATHML.into()),
Component::Negation(vec![
Component::Class(DummyAtom::from("cl"))
].into_boxed_slice()),
), specificity(0, 1, 0))
))));
assert_eq!(parse_ns(":not(*)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::DefaultNamespace(MATHML.into()),
Component::Negation(vec![
Component::DefaultNamespace(MATHML.into()),
Component::ExplicitUniversalType,
].into_boxed_slice()),
), specificity(0, 0, 0))
))));
assert_eq!(parse_ns(":not(e)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::DefaultNamespace(MATHML.into()),
Component::Negation(vec![
Component::DefaultNamespace(MATHML.into()),
Component::LocalName(LocalName {
name: DummyAtom::from("e"),
lower_name: DummyAtom::from("e")
}),
].into_boxed_slice())
), specificity(0, 0, 1))
))));
assert_eq!(parse("[attr |= \"foo\"]"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::AttributeInNoNamespace {
local_name: DummyAtom::from("attr"),
local_name_lower: DummyAtom::from("attr"),
operator: AttrSelectorOperator::DashMatch,
value: DummyAtom::from("foo"),
never_matches: false,
case_sensitivity: ParsedCaseSensitivity::CaseSensitive,
}
), specificity(0, 1, 0))
))));
// https://github.com/mozilla/servo/issues/1723
assert_eq!(parse("::before"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::PseudoElement(PseudoElement::Before),
), specificity(0, 0, 1) | HAS_PSEUDO_BIT)
))));
assert_eq!(parse("::before:hover"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::PseudoElement(PseudoElement::Before),
Component::NonTSPseudoClass(PseudoClass::Hover),
), specificity(0, 1, 1) | HAS_PSEUDO_BIT)
))));
assert_eq!(parse("::before:hover:hover"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::PseudoElement(PseudoElement::Before),
Component::NonTSPseudoClass(PseudoClass::Hover),
Component::NonTSPseudoClass(PseudoClass::Hover),
), specificity(0, 2, 1) | HAS_PSEUDO_BIT)
))));
assert!(parse("::before:hover:active").is_err());
assert!(parse("::before:hover .foo").is_err());
assert!(parse("::before .foo").is_err());
assert!(parse("::before ~ bar").is_err());
assert!(parse("::before:active").is_err());
<|fim▁hole|> assert!(parse(":: before").is_err());
assert_eq!(parse("div ::after"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::LocalName(LocalName {
name: DummyAtom::from("div"),
lower_name: DummyAtom::from("div") }),
Component::Combinator(Combinator::Descendant),
Component::Combinator(Combinator::PseudoElement),
Component::PseudoElement(PseudoElement::After),
), specificity(0, 0, 2) | HAS_PSEUDO_BIT)
))));
assert_eq!(parse("#d1 > .ok"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(
Component::ID(DummyAtom::from("d1")),
Component::Combinator(Combinator::Child),
Component::Class(DummyAtom::from("ok")),
), (1 << 20) + (1 << 10) + (0 << 0))
))));
parser.default_ns = None;
assert!(parse(":not(#provel.old)").is_err());
assert!(parse(":not(#provel > old)").is_err());
assert!(parse("table[rules]:not([rules = \"none\"]):not([rules = \"\"])").is_ok());
assert_eq!(parse(":not(#provel)"), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(Component::Negation(vec!(
Component::ID(DummyAtom::from("provel")),
).into_boxed_slice()
)), specificity(1, 0, 0))
))));
assert_eq!(parse_ns(":not(svg|circle)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(Component::Negation(
vec![
Component::Namespace(DummyAtom("svg".into()), SVG.into()),
Component::LocalName(LocalName {
name: DummyAtom::from("circle"),
lower_name: DummyAtom::from("circle")
}),
].into_boxed_slice()
)), specificity(0, 0, 1))
))));
// https://github.com/servo/servo/issues/16017
assert_eq!(parse_ns(":not(*)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(Component::Negation(
vec![
Component::ExplicitUniversalType,
].into_boxed_slice()
)), specificity(0, 0, 0))
))));
assert_eq!(parse_ns(":not(|*)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(Component::Negation(
vec![
Component::ExplicitNoNamespace,
Component::ExplicitUniversalType,
].into_boxed_slice()
)), specificity(0, 0, 0))
))));
assert_eq!(parse_ns(":not(*|*)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(Component::Negation(
vec![
Component::ExplicitAnyNamespace,
Component::ExplicitUniversalType,
].into_boxed_slice()
)), specificity(0, 0, 0))
))));
assert_eq!(parse_ns(":not(svg|*)", &parser), Ok(SelectorList::from_vec(vec!(
Selector::from_vec(vec!(Component::Negation(
vec![
Component::Namespace(DummyAtom("svg".into()), SVG.into()),
Component::ExplicitUniversalType,
].into_boxed_slice()
)), specificity(0, 0, 0))
))));
}
#[test]
fn test_pseudo_iter() {
let selector = &parse("q::before").unwrap().0[0].selector;
assert!(!selector.is_universal());
let mut iter = selector.iter();
assert_eq!(iter.next(), Some(&Component::PseudoElement(PseudoElement::Before)));
assert_eq!(iter.next(), None);
let combinator = iter.next_sequence();
assert_eq!(combinator, Some(Combinator::PseudoElement));
assert!(matches!(iter.next(), Some(&Component::LocalName(..))));
assert_eq!(iter.next(), None);
assert_eq!(iter.next_sequence(), None);
}
#[test]
fn test_universal() {
let selector = &parse("*|*::before").unwrap().0[0].selector;
assert!(selector.is_universal());
}
#[test]
fn test_empty_pseudo_iter() {
let selector = &parse("::before").unwrap().0[0].selector;
assert!(selector.is_universal());
let mut iter = selector.iter();
assert_eq!(iter.next(), Some(&Component::PseudoElement(PseudoElement::Before)));
assert_eq!(iter.next(), None);
assert_eq!(iter.next_sequence(), None);
}
struct TestVisitor {
seen: Vec<String>,
}
impl SelectorVisitor for TestVisitor {
type Impl = DummySelectorImpl;
fn visit_simple_selector(&mut self, s: &Component<DummySelectorImpl>) -> bool {
let mut dest = String::new();
s.to_css(&mut dest).unwrap();
self.seen.push(dest);
true
}
}
#[test]
fn visitor() {
let mut test_visitor = TestVisitor { seen: vec![], };
parse(":not(:hover) ~ label").unwrap().0[0].selector.visit(&mut test_visitor);
assert!(test_visitor.seen.contains(&":hover".into()));
let mut test_visitor = TestVisitor { seen: vec![], };
parse("::before:hover").unwrap().0[0].selector.visit(&mut test_visitor);
assert!(test_visitor.seen.contains(&":hover".into()));
}
}<|fim▁end|> | // https://github.com/servo/servo/issues/15335 |
<|file_name|>gapic_batch_controller_v1.ts<|end_file_name|><|fim▁begin|>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
import * as protos from '../protos/protos';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {SinonStub} from 'sinon';
import {describe, it} from 'mocha';
import * as batchcontrollerModule from '../src';
import {PassThrough} from 'stream';
import {protobuf, LROperation, operationsProtos} from 'google-gax';
function generateSampleMessage<T extends object>(instance: T) {
const filledObject = (
instance.constructor as typeof protobuf.Message
).toObject(instance as protobuf.Message<T>, {defaults: true});
return (instance.constructor as typeof protobuf.Message).fromObject(
filledObject
) as T;
}
function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) {
return error
? sinon.stub().rejects(error)
: sinon.stub().resolves([response]);
}
function stubSimpleCallWithCallback<ResponseType>(
response?: ResponseType,
error?: Error
) {
return error
? sinon.stub().callsArgWith(2, error)
: sinon.stub().callsArgWith(2, null, response);
}
function stubLongRunningCall<ResponseType>(
response?: ResponseType,
callError?: Error,
lroError?: Error
) {
const innerStub = lroError
? sinon.stub().rejects(lroError)
: sinon.stub().resolves([response]);
const mockOperation = {
promise: innerStub,
};
return callError
? sinon.stub().rejects(callError)
: sinon.stub().resolves([mockOperation]);
}
function stubLongRunningCallWithCallback<ResponseType>(
response?: ResponseType,
callError?: Error,
lroError?: Error
) {
const innerStub = lroError
? sinon.stub().rejects(lroError)
: sinon.stub().resolves([response]);
const mockOperation = {
promise: innerStub,
};
return callError
? sinon.stub().callsArgWith(2, callError)
: sinon.stub().callsArgWith(2, null, mockOperation);
}
function stubPageStreamingCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
const pagingStub = sinon.stub();
if (responses) {
for (let i = 0; i < responses.length; ++i) {
pagingStub.onCall(i).callsArgWith(2, null, responses[i]);
}
}
const transformStub = error
? sinon.stub().callsArgWith(2, error)
: pagingStub;
const mockStream = new PassThrough({
objectMode: true,
transform: transformStub,
});
// trigger as many responses as needed
if (responses) {
for (let i = 0; i < responses.length; ++i) {
setImmediate(() => {
mockStream.write({});
});
}
setImmediate(() => {
mockStream.end();
});
} else {
setImmediate(() => {
mockStream.write({});
});
setImmediate(() => {
mockStream.end();
});
}
return sinon.stub().returns(mockStream);
}
function stubAsyncIterationCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
let counter = 0;
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
async next() {
if (error) {
return Promise.reject(error);
}
if (counter >= responses!.length) {
return Promise.resolve({done: true, value: undefined});
}
return Promise.resolve({done: false, value: responses![counter++]});
},
};
},
};
return sinon.stub().returns(asyncIterable);
}
describe('v1.BatchControllerClient', () => {
it('has servicePath', () => {
const servicePath =
batchcontrollerModule.v1.BatchControllerClient.servicePath;
assert(servicePath);
});
it('has apiEndpoint', () => {
const apiEndpoint =
batchcontrollerModule.v1.BatchControllerClient.apiEndpoint;
assert(apiEndpoint);
});
it('has port', () => {
const port = batchcontrollerModule.v1.BatchControllerClient.port;
assert(port);
assert(typeof port === 'number');
});
it('should create a client with no option', () => {
const client = new batchcontrollerModule.v1.BatchControllerClient();
assert(client);
});
it('should create a client with gRPC fallback', () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
fallback: true,
});
assert(client);
});
it('has initialize method and supports deferred initialization', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
assert.strictEqual(client.batchControllerStub, undefined);
await client.initialize();
assert(client.batchControllerStub);
});
it('has close method for the initialized client', done => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
assert(client.batchControllerStub);
client.close().then(() => {
done();
});
});
it('has close method for the non-initialized client', done => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
assert.strictEqual(client.batchControllerStub, undefined);
client.close().then(() => {
done();
});
});
it('has getProjectId method', async () => {
const fakeProjectId = 'fake-project-id';
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.auth.getProjectId = sinon.stub().resolves(fakeProjectId);
const result = await client.getProjectId();
assert.strictEqual(result, fakeProjectId);
assert((client.auth.getProjectId as SinonStub).calledWithExactly());
});
it('has getProjectId method with callback', async () => {
const fakeProjectId = 'fake-project-id';
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.auth.getProjectId = sinon
.stub()
.callsArgWith(0, null, fakeProjectId);
const promise = new Promise((resolve, reject) => {
client.getProjectId((err?: Error | null, projectId?: string | null) => {
if (err) {
reject(err);
} else {
resolve(projectId);
}
});
});
const result = await promise;
assert.strictEqual(result, fakeProjectId);
});
describe('getBatch', () => {
it('invokes getBatch without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.GetBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.dataproc.v1.Batch()
);
client.innerApiCalls.getBatch = stubSimpleCall(expectedResponse);
const [response] = await client.getBatch(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getBatch without error using callback', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.GetBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.dataproc.v1.Batch()
);
client.innerApiCalls.getBatch =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getBatch(
request,
(
err?: Error | null,
result?: protos.google.cloud.dataproc.v1.IBatch | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getBatch with error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.GetBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getBatch = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.getBatch(request), expectedError);
assert(
(client.innerApiCalls.getBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getBatch with closed client', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.GetBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedError = new Error('The client has already been closed.');
client.close();
await assert.rejects(client.getBatch(request), expectedError);
});
});
describe('deleteBatch', () => {
it('invokes deleteBatch without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.DeleteBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteBatch = stubSimpleCall(expectedResponse);
const [response] = await client.deleteBatch(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes deleteBatch without error using callback', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.DeleteBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteBatch =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.deleteBatch(
request,
(
err?: Error | null,
result?: protos.google.protobuf.IEmpty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes deleteBatch with error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.DeleteBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.deleteBatch = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.deleteBatch(request), expectedError);
assert(
(client.innerApiCalls.deleteBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes deleteBatch with closed client', async () => {<|fim▁hole|> credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.DeleteBatchRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedError = new Error('The client has already been closed.');
client.close();
await assert.rejects(client.deleteBatch(request), expectedError);
});
});
describe('createBatch', () => {
it('invokes createBatch without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.CreateBatchRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.createBatch = stubLongRunningCall(expectedResponse);
const [operation] = await client.createBatch(request);
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createBatch without error using callback', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.CreateBatchRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.createBatch =
stubLongRunningCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.createBatch(
request,
(
err?: Error | null,
result?: LROperation<
protos.google.cloud.dataproc.v1.IBatch,
protos.google.cloud.dataproc.v1.IBatchOperationMetadata
> | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const operation = (await promise) as LROperation<
protos.google.cloud.dataproc.v1.IBatch,
protos.google.cloud.dataproc.v1.IBatchOperationMetadata
>;
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes createBatch with call error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.CreateBatchRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createBatch = stubLongRunningCall(
undefined,
expectedError
);
await assert.rejects(client.createBatch(request), expectedError);
assert(
(client.innerApiCalls.createBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createBatch with LRO error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.CreateBatchRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createBatch = stubLongRunningCall(
undefined,
undefined,
expectedError
);
const [operation] = await client.createBatch(request);
await assert.rejects(operation.promise(), expectedError);
assert(
(client.innerApiCalls.createBatch as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes checkCreateBatchProgress without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedResponse = generateSampleMessage(
new operationsProtos.google.longrunning.Operation()
);
expectedResponse.name = 'test';
expectedResponse.response = {type_url: 'url', value: Buffer.from('')};
expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')};
client.operationsClient.getOperation = stubSimpleCall(expectedResponse);
const decodedOperation = await client.checkCreateBatchProgress(
expectedResponse.name
);
assert.deepStrictEqual(decodedOperation.name, expectedResponse.name);
assert(decodedOperation.metadata);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
it('invokes checkCreateBatchProgress with error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedError = new Error('expected');
client.operationsClient.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.checkCreateBatchProgress(''), expectedError);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
});
describe('listBatches', () => {
it('invokes listBatches without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
];
client.innerApiCalls.listBatches = stubSimpleCall(expectedResponse);
const [response] = await client.listBatches(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listBatches as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listBatches without error using callback', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
];
client.innerApiCalls.listBatches =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listBatches(
request,
(
err?: Error | null,
result?: protos.google.cloud.dataproc.v1.IBatch[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listBatches as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listBatches with error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listBatches = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listBatches(request), expectedError);
assert(
(client.innerApiCalls.listBatches as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listBatchesStream without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
];
client.descriptors.page.listBatches.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listBatchesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.dataproc.v1.Batch[] = [];
stream.on('data', (response: protos.google.cloud.dataproc.v1.Batch) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listBatches.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listBatches, request)
);
assert.strictEqual(
(client.descriptors.page.listBatches.createStream as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listBatchesStream with error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listBatches.createStream = stubPageStreamingCall(
undefined,
expectedError
);
const stream = client.listBatchesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.dataproc.v1.Batch[] = [];
stream.on('data', (response: protos.google.cloud.dataproc.v1.Batch) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listBatches.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listBatches, request)
);
assert.strictEqual(
(client.descriptors.page.listBatches.createStream as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listBatches without error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
generateSampleMessage(new protos.google.cloud.dataproc.v1.Batch()),
];
client.descriptors.page.listBatches.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.cloud.dataproc.v1.IBatch[] = [];
const iterable = client.listBatchesAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(client.descriptors.page.listBatches.asyncIterate as SinonStub).getCall(
0
).args[1],
request
);
assert.strictEqual(
(client.descriptors.page.listBatches.asyncIterate as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listBatches with error', async () => {
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.dataproc.v1.ListBatchesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listBatches.asyncIterate = stubAsyncIterationCall(
undefined,
expectedError
);
const iterable = client.listBatchesAsync(request);
await assert.rejects(async () => {
const responses: protos.google.cloud.dataproc.v1.IBatch[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(client.descriptors.page.listBatches.asyncIterate as SinonStub).getCall(
0
).args[1],
request
);
assert.strictEqual(
(client.descriptors.page.listBatches.asyncIterate as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('Path templates', () => {
describe('batch', () => {
const fakePath = '/rendered/path/batch';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
batch: 'batchValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.batchPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.batchPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('batchPath', () => {
const result = client.batchPath(
'projectValue',
'locationValue',
'batchValue'
);
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.batchPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromBatchName', () => {
const result = client.matchProjectFromBatchName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.batchPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromBatchName', () => {
const result = client.matchLocationFromBatchName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(client.pathTemplates.batchPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchBatchFromBatchName', () => {
const result = client.matchBatchFromBatchName(fakePath);
assert.strictEqual(result, 'batchValue');
assert(
(client.pathTemplates.batchPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('location', () => {
const fakePath = '/rendered/path/location';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.locationPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.locationPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('locationPath', () => {
const result = client.locationPath('projectValue', 'locationValue');
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.locationPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromLocationName', () => {
const result = client.matchProjectFromLocationName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.locationPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromLocationName', () => {
const result = client.matchLocationFromLocationName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(client.pathTemplates.locationPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('project', () => {
const fakePath = '/rendered/path/project';
const expectedParameters = {
project: 'projectValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.projectPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.projectPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('projectPath', () => {
const result = client.projectPath('projectValue');
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.projectPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromProjectName', () => {
const result = client.matchProjectFromProjectName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.projectPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('projectLocationAutoscalingPolicy', () => {
const fakePath = '/rendered/path/projectLocationAutoscalingPolicy';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
autoscaling_policy: 'autoscalingPolicyValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.projectLocationAutoscalingPolicyPathTemplate.render =
sinon.stub().returns(fakePath);
client.pathTemplates.projectLocationAutoscalingPolicyPathTemplate.match =
sinon.stub().returns(expectedParameters);
it('projectLocationAutoscalingPolicyPath', () => {
const result = client.projectLocationAutoscalingPolicyPath(
'projectValue',
'locationValue',
'autoscalingPolicyValue'
);
assert.strictEqual(result, fakePath);
assert(
(
client.pathTemplates.projectLocationAutoscalingPolicyPathTemplate
.render as SinonStub
)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromProjectLocationAutoscalingPolicyName', () => {
const result =
client.matchProjectFromProjectLocationAutoscalingPolicyName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(
client.pathTemplates.projectLocationAutoscalingPolicyPathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromProjectLocationAutoscalingPolicyName', () => {
const result =
client.matchLocationFromProjectLocationAutoscalingPolicyName(
fakePath
);
assert.strictEqual(result, 'locationValue');
assert(
(
client.pathTemplates.projectLocationAutoscalingPolicyPathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchAutoscalingPolicyFromProjectLocationAutoscalingPolicyName', () => {
const result =
client.matchAutoscalingPolicyFromProjectLocationAutoscalingPolicyName(
fakePath
);
assert.strictEqual(result, 'autoscalingPolicyValue');
assert(
(
client.pathTemplates.projectLocationAutoscalingPolicyPathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('projectLocationWorkflowTemplate', () => {
const fakePath = '/rendered/path/projectLocationWorkflowTemplate';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
workflow_template: 'workflowTemplateValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.projectLocationWorkflowTemplatePathTemplate.render =
sinon.stub().returns(fakePath);
client.pathTemplates.projectLocationWorkflowTemplatePathTemplate.match =
sinon.stub().returns(expectedParameters);
it('projectLocationWorkflowTemplatePath', () => {
const result = client.projectLocationWorkflowTemplatePath(
'projectValue',
'locationValue',
'workflowTemplateValue'
);
assert.strictEqual(result, fakePath);
assert(
(
client.pathTemplates.projectLocationWorkflowTemplatePathTemplate
.render as SinonStub
)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromProjectLocationWorkflowTemplateName', () => {
const result =
client.matchProjectFromProjectLocationWorkflowTemplateName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(
client.pathTemplates.projectLocationWorkflowTemplatePathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromProjectLocationWorkflowTemplateName', () => {
const result =
client.matchLocationFromProjectLocationWorkflowTemplateName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(
client.pathTemplates.projectLocationWorkflowTemplatePathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchWorkflowTemplateFromProjectLocationWorkflowTemplateName', () => {
const result =
client.matchWorkflowTemplateFromProjectLocationWorkflowTemplateName(
fakePath
);
assert.strictEqual(result, 'workflowTemplateValue');
assert(
(
client.pathTemplates.projectLocationWorkflowTemplatePathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('projectRegionAutoscalingPolicy', () => {
const fakePath = '/rendered/path/projectRegionAutoscalingPolicy';
const expectedParameters = {
project: 'projectValue',
region: 'regionValue',
autoscaling_policy: 'autoscalingPolicyValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.projectRegionAutoscalingPolicyPathTemplate.render =
sinon.stub().returns(fakePath);
client.pathTemplates.projectRegionAutoscalingPolicyPathTemplate.match =
sinon.stub().returns(expectedParameters);
it('projectRegionAutoscalingPolicyPath', () => {
const result = client.projectRegionAutoscalingPolicyPath(
'projectValue',
'regionValue',
'autoscalingPolicyValue'
);
assert.strictEqual(result, fakePath);
assert(
(
client.pathTemplates.projectRegionAutoscalingPolicyPathTemplate
.render as SinonStub
)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromProjectRegionAutoscalingPolicyName', () => {
const result =
client.matchProjectFromProjectRegionAutoscalingPolicyName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(
client.pathTemplates.projectRegionAutoscalingPolicyPathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchRegionFromProjectRegionAutoscalingPolicyName', () => {
const result =
client.matchRegionFromProjectRegionAutoscalingPolicyName(fakePath);
assert.strictEqual(result, 'regionValue');
assert(
(
client.pathTemplates.projectRegionAutoscalingPolicyPathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchAutoscalingPolicyFromProjectRegionAutoscalingPolicyName', () => {
const result =
client.matchAutoscalingPolicyFromProjectRegionAutoscalingPolicyName(
fakePath
);
assert.strictEqual(result, 'autoscalingPolicyValue');
assert(
(
client.pathTemplates.projectRegionAutoscalingPolicyPathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('projectRegionWorkflowTemplate', () => {
const fakePath = '/rendered/path/projectRegionWorkflowTemplate';
const expectedParameters = {
project: 'projectValue',
region: 'regionValue',
workflow_template: 'workflowTemplateValue',
};
const client = new batchcontrollerModule.v1.BatchControllerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.projectRegionWorkflowTemplatePathTemplate.render =
sinon.stub().returns(fakePath);
client.pathTemplates.projectRegionWorkflowTemplatePathTemplate.match =
sinon.stub().returns(expectedParameters);
it('projectRegionWorkflowTemplatePath', () => {
const result = client.projectRegionWorkflowTemplatePath(
'projectValue',
'regionValue',
'workflowTemplateValue'
);
assert.strictEqual(result, fakePath);
assert(
(
client.pathTemplates.projectRegionWorkflowTemplatePathTemplate
.render as SinonStub
)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromProjectRegionWorkflowTemplateName', () => {
const result =
client.matchProjectFromProjectRegionWorkflowTemplateName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(
client.pathTemplates.projectRegionWorkflowTemplatePathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchRegionFromProjectRegionWorkflowTemplateName', () => {
const result =
client.matchRegionFromProjectRegionWorkflowTemplateName(fakePath);
assert.strictEqual(result, 'regionValue');
assert(
(
client.pathTemplates.projectRegionWorkflowTemplatePathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchWorkflowTemplateFromProjectRegionWorkflowTemplateName', () => {
const result =
client.matchWorkflowTemplateFromProjectRegionWorkflowTemplateName(
fakePath
);
assert.strictEqual(result, 'workflowTemplateValue');
assert(
(
client.pathTemplates.projectRegionWorkflowTemplatePathTemplate
.match as SinonStub
)
.getCall(-1)
.calledWith(fakePath)
);
});
});
});
});<|fim▁end|> | const client = new batchcontrollerModule.v1.BatchControllerClient({ |
<|file_name|>Computer.js<|end_file_name|><|fim▁begin|>import Off from './Off';
import On from './On';
// ==============================
// CONCRETE CONTEXT
// ==============================
export default class Computer {
constructor() {
this._currentState = null;
this._states = {
off: new Off(),
on: new On()
};
}
power() {
this._currentState.power(this);
}
<|fim▁hole|> return this._currentState;
}
setCurrentState(state) {
this._currentState = state;
}
getStates() {
return this._states;
}
}<|fim▁end|> | getCurrentState() { |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># ===========================================================================
# This file contain some utilities for the course
# ===========================================================================
from __future__ import print_function, division, absolute_import
import os
import sys
import time
import shutil
from six.moves.urllib.request import urlopen
from six.moves.urllib.error import URLError, HTTPError
import tarfile
import platform
import numpy as np
# Under Python 2, 'urlretrieve' relies on FancyURLopener from legacy
# urllib module, known to have issues with proxy management
if sys.version_info[0] == 2:
def urlretrieve(url, filename, reporthook=None, data=None):
'''
This function is adpated from: https://github.com/fchollet/keras
Original work Copyright (c) 2014-2015 keras contributors
'''
def chunk_read(response, chunk_size=8192, reporthook=None):
total_size = response.info().get('Content-Length').strip()
total_size = int(total_size)
count = 0
while 1:
chunk = response.read(chunk_size)
if not chunk:
break
count += 1
if reporthook:
reporthook(count, chunk_size, total_size)
yield chunk
response = urlopen(url, data)
with open(filename, 'wb') as fd:
for chunk in chunk_read(response, reporthook=reporthook):
fd.write(chunk)
else:
from six.moves.urllib.request import urlretrieve
class Progbar(object):
'''
This function is adpated from: https://github.com/fchollet/keras
Original work Copyright (c) 2014-2015 keras contributors
Modified work Copyright 2016-2017 TrungNT
'''
def __init__(self, target, title=''):
'''
@param target: total number of steps expected
'''
self.width = 39
self.target = target
self.sum_values = {}
self.unique_values = []
self.start = time.time()
self.total_width = 0
self.seen_so_far = 0
self.title = title
def update(self, current, values=[]):
'''
@param current: index of current step
@param values: list of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
'''
for k, v in values:
if k not in self.sum_values:
self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far]
self.unique_values.append(k)
else:
self.sum_values[k][0] += v * (current - self.seen_so_far)
self.sum_values[k][1] += (current - self.seen_so_far)
self.seen_so_far = current
now = time.time()
prev_total_width = self.total_width
sys.stdout.write("\b" * prev_total_width)
sys.stdout.write("\r")
numdigits = int(np.floor(np.log10(self.target))) + 1
barstr = '%s %%%dd/%%%dd [' % (self.title, numdigits, numdigits)
bar = barstr % (current, self.target)
prog = float(current) / self.target
prog_width = int(self.width * prog)
if prog_width > 0:
bar += ('=' * (prog_width - 1))
if current < self.target:
bar += '>'
else:
bar += '='
bar += ('.' * (self.width - prog_width))
bar += ']'
sys.stdout.write(bar)
self.total_width = len(bar)
if current:
time_per_unit = (now - self.start) / current
else:
time_per_unit = 0
eta = time_per_unit * (self.target - current)
info = ''
if current < self.target:
info += ' - ETA: %ds' % eta
else:
info += ' - %ds' % (now - self.start)
for k in self.unique_values:
info += ' - %s:' % k
if type(self.sum_values[k]) is list:
avg = self.sum_values[k][0] / max(1, self.sum_values[k][1])
if abs(avg) > 1e-3:
info += ' %.4f' % avg
else:
info += ' %.4e' % avg
else:
info += ' %s' % self.sum_values[k]
self.total_width += len(info)
if prev_total_width > self.total_width:
info += ((prev_total_width - self.total_width) * " ")
sys.stdout.write(info)
if current >= self.target:
if "Linux" in platform.platform():
sys.stdout.write("\n\n")
else:
sys.stdout.write("\n")
sys.stdout.flush()
def add(self, n, values=[]):
self.update(self.seen_so_far + n, values)
def get_file(fname, origin, untar=False, datadir=None):
'''
This function is adpated from: https://github.com/fchollet/keras
Original work Copyright (c) 2014-2015 keras contributors
Modified work Copyright 2016-2017 TrungNT
Return
------
file path of the downloaded file
'''
# ====== check valid datadir ====== #
if datadir is None:
datadir = os.path.join(os.path.expanduser('~'), '.bay2')
if not os.path.exists(datadir):
os.mkdir(datadir)<|fim▁hole|> elif not os.path.exists(datadir):
raise ValueError('Cannot find folder at path:' + str(datadir))
# ====== download the file ====== #
if untar:
untar_fpath = os.path.join(datadir, fname)
fpath = untar_fpath + '.tar.gz'
else:
fpath = os.path.join(datadir, fname)
if not os.path.exists(fpath):
print('Downloading data from', origin)
global _progbar
_progbar = None
def dl_progress(count, block_size, total_size):
global _progbar
if _progbar is None:
_progbar = Progbar(total_size)
else:
_progbar.update(count * block_size)
error_msg = 'URL fetch failure on {}: {} -- {}'
try:
try:
urlretrieve(origin, fpath, dl_progress)
except URLError as e:
raise Exception(error_msg.format(origin, e.errno, e.reason))
except HTTPError as e:
raise Exception(error_msg.format(origin, e.code, e.msg))
except (Exception, KeyboardInterrupt) as e:
if os.path.exists(fpath):
os.remove(fpath)
raise
_progbar = None
if untar:
if not os.path.exists(untar_fpath):
print('Untaring file...')
tfile = tarfile.open(fpath, 'r:gz')
try:
tfile.extractall(path=datadir)
except (Exception, KeyboardInterrupt) as e:
if os.path.exists(untar_fpath):
if os.path.isfile(untar_fpath):
os.remove(untar_fpath)
else:
shutil.rmtree(untar_fpath)
raise
tfile.close()
return untar_fpath
return fpath<|fim▁end|> | |
<|file_name|>SrcAbsoluteURLRule.js<|end_file_name|><|fim▁begin|>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
// This is a very simple test, and could be made more robust.
// All we do is check for the presence of "http://" or "https://"<|fim▁hole|>// at the start of the string.
var description = 'Relative src URLs can break (i.e. if recipients are outside the company network) and make your content unavailable to view.';
exports.default = function (props) {
if (props.hasOwnProperty('src')) {
if (!/^https?:\/\//.test(props['src'])) {
return new Error(description);
}
}
};<|fim▁end|> | |
<|file_name|>mobile-detect.js<|end_file_name|><|fim▁begin|>define(["mobile-detect"], function(MobileDetect){
function Factory(){
var md = new MobileDetect(window.navigator.userAgent);<|fim▁hole|> return md.mobile();
}
};
}
return [Factory];
});<|fim▁end|> |
return {
isMobile : function(){ |
<|file_name|>jquery-extend.js<|end_file_name|><|fim▁begin|>define('util', ['jquery'], function($){
$.extend({
restGet: function(url, data, callback){
$.get(url, data, function(data){
if(data.success){
callback(data);
} else {
if(data.redirect){
location.href = data.redirect;
}
else if(data.message){
$.showError('notify', data.message);
}
}
});
},
restPost: function(url, data, callback){
$.post(url, data, function(data){
if(data.success){
callback(data);
} else {
<|fim▁hole|> }
else if(data.message){
$.showError('notify', data.message);
}
}
});
},
showError: function(id, message){
$("#" + id).append('<div class="alert alert-error fade in"><a href="#" data-dismiss="alert" class="close">×</a><strong>错误:</strong><span></span></div>')
$("#" + id +" > div > span").text(message);
$("#" + id +" > .alert").alert();
setTimeout(function(){
$("#" + id +" > .alert").alert('close');
}, 3000);
},
showSuccess: function(id, message){
$("#" + id).append('<div class="alert alert-success fade in"><a href="#" data-dismiss="alert" class="close">×</a><span></span></div>')
$("#" + id +" > div > span").text(message);
$("#" + id +" > .alert").alert();
setTimeout(function(){
$("#" + id +" > .alert").alert('close');
}, 3000);
},
backdrop: function(state){
if(state == 'show'){
$("body").append("<div class='modal-backdrop fade in'></div>");
} else if(state == 'hide'){
$(".modal-backdrop").remove();
};
},
});
$.fn.extend({
edata: function(id){
return this.attr("data-" + id);
},
reset: function(){
var id = this.attr('id');
document.getElementById(id).reset();
},
is_disabled: function(){
return this.attr("disabled") == "disabled";
},
});
return $;
});<|fim▁end|> | if(data.redirect){
location.href = data.redirect;
|
<|file_name|>TestPojoPageTwo.java<|end_file_name|><|fim▁begin|>/**
* CommonFramework
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* 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 com.blackducksoftware.tools.commonframework.standard.protex.report.template;
// TODO: Auto-generated Javadoc
/**
* Pojo representing the second sheet of our test template .
*
* @author akamen
*/
public class TestPojoPageTwo extends TestPojo {
/** The value1page2. */
public String value1page2;
/** The value2page2. */
public String value2page2;
/**
* Gets the value2 page2.
*
* @return the value2 page2
*/
public String getValue2Page2() {
return value2page2;
}
/**
* Sets the value2page2.
*
* @param value2page2
* the new value2page2<|fim▁hole|> this.value2page2 = value2page2;
}
/**
* Gets the value1 page2.
*
* @return the value1 page2
*/
public String getValue1Page2() {
return value1page2;
}
/**
* Sets the value1page2.
*
* @param value1page2
* the new value1page2
*/
public void setValue1page2(String value1page2) {
this.value1page2 = value1page2;
}
}<|fim▁end|> | */
public void setValue2page2(String value2page2) { |
<|file_name|>enumerations.py<|end_file_name|><|fim▁begin|>#===- enumerations.py - Python LLVM Enumerations -------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
r"""
LLVM Enumerations
=================
This file defines enumerations from LLVM.
Each enumeration is exposed as a list of 2-tuples. These lists are consumed by
dedicated types elsewhere in the package. The enumerations are centrally
defined in this file so they are easier to locate and maintain.
"""
__all__ = [
'Attributes',
'OpCodes',
'TypeKinds',
'Linkages',
'Visibility',
'CallConv',
'IntPredicate',
'RealPredicate',
'LandingPadClauseTy',
]
Attributes = [
('ZExt', 1 << 0),
('MSExt', 1 << 1),
('NoReturn', 1 << 2),
('InReg', 1 << 3),
('StructRet', 1 << 4),
('NoUnwind', 1 << 5),
('NoAlias', 1 << 6),
('ByVal', 1 << 7),
('Nest', 1 << 8),
('ReadNone', 1 << 9),
('ReadOnly', 1 << 10),
('NoInline', 1 << 11),
('AlwaysInline', 1 << 12),
('OptimizeForSize', 1 << 13),
('StackProtect', 1 << 14),
('StackProtectReq', 1 << 15),
('Alignment', 31 << 16),
('NoCapture', 1 << 21),
('NoRedZone', 1 << 22),
('ImplicitFloat', 1 << 23),
('Naked', 1 << 24),
('InlineHint', 1 << 25),
('StackAlignment', 7 << 26),
('ReturnsTwice', 1 << 29),
('UWTable', 1 << 30),
('NonLazyBind', 1 << 31),
]
OpCodes = [
('Ret', 1),
('Br', 2),
('Switch', 3),
('IndirectBr', 4),
('Invoke', 5),
('Unreachable', 7),
('Add', 8),
('FAdd', 9),
('Sub', 10),
('FSub', 11),
('Mul', 12),
('FMul', 13),
('UDiv', 14),
('SDiv', 15),
('FDiv', 16),
('URem', 17),
('SRem', 18),
('FRem', 19),
('Shl', 20),
('LShr', 21),
('AShr', 22),
('And', 23),
('Or', 24),
('Xor', 25),
('Alloca', 26),
('Load', 27),
('Store', 28),
('GetElementPtr', 29),
('Trunc', 30),
('ZExt', 31),
('SExt', 32),
('FPToUI', 33),
('FPToSI', 34),
('UIToFP', 35),
('SIToFP', 36),
('FPTrunc', 37),
('FPExt', 38),
('PtrToInt', 39),
('IntToPtr', 40),
('BitCast', 41),
('ICmp', 42),
('FCmpl', 43),
('PHI', 44),<|fim▁hole|> ('UserOp2', 48),
('AArg', 49),
('ExtractElement', 50),
('InsertElement', 51),
('ShuffleVector', 52),
('ExtractValue', 53),
('InsertValue', 54),
('Fence', 55),
('AtomicCmpXchg', 56),
('AtomicRMW', 57),
('Resume', 58),
('LandingPad', 59),
]
TypeKinds = [
('Void', 0),
('Half', 1),
('Float', 2),
('Double', 3),
('X86_FP80', 4),
('FP128', 5),
('PPC_FP128', 6),
('Label', 7),
('Integer', 8),
('Function', 9),
('Struct', 10),
('Array', 11),
('Pointer', 12),
('Vector', 13),
('Metadata', 14),
('X86_MMX', 15),
]
Linkages = [
('External', 0),
('AvailableExternally', 1),
('LinkOnceAny', 2),
('LinkOnceODR', 3),
('WeakAny', 4),
('WeakODR', 5),
('Appending', 6),
('Internal', 7),
('Private', 8),
('DLLImport', 9),
('DLLExport', 10),
('ExternalWeak', 11),
('Ghost', 12),
('Common', 13),
('LinkerPrivate', 14),
('LinkerPrivateWeak', 15),
('LinkerPrivateWeakDefAuto', 16),
]
Visibility = [
('Default', 0),
('Hidden', 1),
('Protected', 2),
]
CallConv = [
('CCall', 0),
('FastCall', 8),
('ColdCall', 9),
('X86StdcallCall', 64),
('X86FastcallCall', 65),
]
IntPredicate = [
('EQ', 32),
('NE', 33),
('UGT', 34),
('UGE', 35),
('ULT', 36),
('ULE', 37),
('SGT', 38),
('SGE', 39),
('SLT', 40),
('SLE', 41),
]
RealPredicate = [
('PredicateFalse', 0),
('OEQ', 1),
('OGT', 2),
('OGE', 3),
('OLT', 4),
('OLE', 5),
('ONE', 6),
('ORD', 7),
('UNO', 8),
('UEQ', 9),
('UGT', 10),
('UGE', 11),
('ULT', 12),
('ULE', 13),
('UNE', 14),
('PredicateTrue', 15),
]
LandingPadClauseTy = [
('Catch', 0),
('Filter', 1),
]<|fim▁end|> | ('Call', 45),
('Select', 46),
('UserOp1', 47), |
<|file_name|>autocomplete_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
# Copyright (c) 2001-2018, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, division, unicode_literals
from tests.check_utils import api_get, api_post, api_delete, api_put, _dt
import json
import pytest
import jmespath
from navitiacommon import models
from tyr import app
@pytest.fixture
def create_autocomplete_parameter():
with app.app_context():
autocomplete_param = models.AutocompleteParameter('idf', 'OSM', 'BANO', 'FUSIO', 'OSM', [8, 9])
models.db.session.add(autocomplete_param)
models.db.session.commit()
# we also create 3 datasets, one for bano, 2 for osm
for i, dset_type in enumerate(['bano', 'osm', 'osm']):
job = models.Job()
dataset = models.DataSet()
dataset.type = dset_type
dataset.family_type = 'autocomplete_{}'.format(dataset.type)
dataset.name = '/path/to/dataset_{}'.format(i)
models.db.session.add(dataset)
job.autocomplete_params_id = autocomplete_param.id
job.data_sets.append(dataset)
job.state = 'done'
models.db.session.add(job)
models.db.session.commit()
@pytest.fixture
def create_two_autocomplete_parameters():
with app.app_context():
autocomplete_param1 = models.AutocompleteParameter('europe', 'OSM', 'BANO', 'OSM', 'OSM', [8, 9])
autocomplete_param2 = models.AutocompleteParameter('france', 'OSM', 'OSM', 'FUSIO', 'OSM', [8, 9])
models.db.session.add(autocomplete_param1)
models.db.session.add(autocomplete_param2)
models.db.session.commit()
@pytest.fixture
def autocomplete_parameter_json():
return {
"name": "peru",
"street": "OSM",
"address": "BANO",
"poi": "FUSIO",
"admin": "OSM",
"admin_level": [8],
}
def test_get_autocomplete_parameters_empty():
resp = api_get('/v0/autocomplete_parameters/')
assert resp == []
def test_get_all_autocomplete(create_autocomplete_parameter):
resp = api_get('/v0/autocomplete_parameters/')
assert len(resp) == 1
assert resp[0]['name'] == 'idf'
assert resp[0]['street'] == 'OSM'
assert resp[0]['address'] == 'BANO'
assert resp[0]['poi'] == 'FUSIO'
assert resp[0]['admin'] == 'OSM'
assert resp[0]['admin_level'] == [8, 9]
def test_get_autocomplete_by_name(create_two_autocomplete_parameters):
resp = api_get('/v0/autocomplete_parameters/')
assert len(resp) == 2
resp = api_get('/v0/autocomplete_parameters/france')
assert resp['name'] == 'france'
assert resp['street'] == 'OSM'
assert resp['address'] == 'OSM'
assert resp['poi'] == 'FUSIO'
assert resp['admin'] == 'OSM'
assert resp['admin_level'] == [8, 9]
def test_post_autocomplete(autocomplete_parameter_json):
resp = api_post(
'/v0/autocomplete_parameters',
data=json.dumps(autocomplete_parameter_json),
content_type='application/json',
)
assert resp['name'] == 'peru'
assert resp['street'] == 'OSM'
assert resp['address'] == 'BANO'
assert resp['poi'] == 'FUSIO'
assert resp['admin'] == 'OSM'<|fim▁hole|>
def test_post_autocomplete_cosmo():
resp = api_post(
'/v0/autocomplete_parameters',
data=json.dumps({"name": "bobette", "admin": "COSMOGONY"}),
content_type='application/json',
)
assert resp['name'] == 'bobette'
assert resp['street'] == 'OSM'
assert resp['address'] == 'BANO'
assert resp['poi'] == 'OSM'
assert resp['admin'] == 'COSMOGONY'
assert resp['admin_level'] == []
def test_put_autocomplete(create_two_autocomplete_parameters, autocomplete_parameter_json):
resp = api_get('/v0/autocomplete_parameters/france')
assert resp['name'] == 'france'
assert resp['street'] == 'OSM'
assert resp['address'] == 'OSM'
assert resp['poi'] == 'FUSIO'
assert resp['admin'] == 'OSM'
assert resp['admin_level'] == [8, 9]
resp = api_put(
'/v0/autocomplete_parameters/france',
data=json.dumps(autocomplete_parameter_json),
content_type='application/json',
)
assert resp['street'] == 'OSM'
assert resp['address'] == 'BANO'
assert resp['poi'] == 'FUSIO'
assert resp['admin'] == 'OSM'
assert resp['admin_level'] == [8]
def test_delete_autocomplete(create_two_autocomplete_parameters):
resp = api_get('/v0/autocomplete_parameters/')
assert len(resp) == 2
resp = api_get('/v0/autocomplete_parameters/france')
assert resp['name'] == 'france'
_, status = api_delete('/v0/autocomplete_parameters/france', check=False, no_json=True)
assert status == 204
_, status = api_get('/v0/autocomplete_parameters/france', check=False)
assert status == 404
resp = api_get('/v0/autocomplete_parameters/')
assert len(resp) == 1
def test_get_last_datasets_autocomplete(create_autocomplete_parameter):
"""
we query the loaded datasets of idf
we loaded 3 datasets, but by default we should get one by family_type, so one for bano, one for osm
"""
resp = api_get('/v0/autocomplete_parameters/idf/last_datasets')
assert len(resp) == 2
bano = next((d for d in resp if d['type'] == 'bano'), None)
assert bano
assert bano['family_type'] == 'autocomplete_bano'
assert bano['name'] == '/path/to/dataset_0'
osm = next((d for d in resp if d['type'] == 'osm'), None)
assert osm
assert osm['family_type'] == 'autocomplete_osm'
assert osm['name'] == '/path/to/dataset_2' # we should have the last one
# if we ask for the 2 last datasets per type, we got all of them
resp = api_get('/v0/autocomplete_parameters/idf/last_datasets?count=2')
assert len(resp) == 3
@pytest.fixture
def minimal_poi_types_json():
return {
"poi_types": [
{"id": "amenity:bicycle_rental", "name": "Station VLS"},
{"id": "amenity:parking", "name": "Parking"},
],
"rules": [
{
"osm_tags_filters": [{"key": "amenity", "value": "bicycle_rental"}],
"poi_type_id": "amenity:bicycle_rental",
},
{"osm_tags_filters": [{"key": "amenity", "value": "parking"}], "poi_type_id": "amenity:parking"},
],
}
def test_autocomplete_poi_types(create_two_autocomplete_parameters, minimal_poi_types_json):
resp = api_get('/v0/autocomplete_parameters/france')
assert resp['name'] == 'france'
# POST a minimal conf
resp = api_post(
'/v0/autocomplete_parameters/france/poi_types',
data=json.dumps(minimal_poi_types_json),
content_type='application/json',
)
def test_minimal_conf(resp):
assert len(resp['poi_types']) == 2
assert len(resp['rules']) == 2
bss_type = jmespath.search("poi_types[?id=='amenity:bicycle_rental']", resp)
assert len(bss_type) == 1
assert bss_type[0]['name'] == 'Station VLS'
bss_rule = jmespath.search("rules[?poi_type_id=='amenity:bicycle_rental']", resp)
assert len(bss_rule) == 1
assert bss_rule[0]['osm_tags_filters'][0]['value'] == 'bicycle_rental'
# check that it's not the "default" conf
assert not jmespath.search("poi_types[?id=='amenity:townhall']", resp)
# check that the conf is correctly set on france
test_minimal_conf(resp)
# check that the conf on europe is still empty
resp = api_get('/v0/autocomplete_parameters/europe/poi_types')
assert not resp
# check GET of newly defined france conf
resp = api_get('/v0/autocomplete_parameters/france/poi_types')
test_minimal_conf(resp)
# check DELETE of france conf
resp, code = api_delete('/v0/autocomplete_parameters/france/poi_types', check=False, no_json=True)
assert not resp
assert code == 204
# check get of conf on france is now empty
resp = api_get('/v0/autocomplete_parameters/france/poi_types')
assert not resp
# check that tyr refuses incorrect conf
resp, code = api_post(
'/v0/autocomplete_parameters/france/poi_types',
data=json.dumps({'poi_types': [{'id': 'bob', 'name': 'Bob'}]}),
content_type='application/json',
check=False,
)
assert code == 400
assert resp['status'] == 'error'
assert 'rules' in resp['message']<|fim▁end|> | assert resp['admin_level'] == [8]
|
<|file_name|>settings.controller.js<|end_file_name|><|fim▁begin|>'use strict';
angular.module('refugeesApp')<|fim▁hole|> .controller('SettingsController', function ($scope, Principal, Auth, Language, $translate) {
$scope.success = null;
$scope.error = null;
Principal.identity().then(function(account) {
$scope.settingsAccount = copyAccount(account);
});
$scope.save = function () {
Auth.updateAccount($scope.settingsAccount).then(function() {
$scope.error = null;
$scope.success = 'OK';
Principal.identity(true).then(function(account) {
$scope.settingsAccount = copyAccount(account);
});
Language.getCurrent().then(function(current) {
if ($scope.settingsAccount.langKey !== current) {
$translate.use($scope.settingsAccount.langKey);
}
});
}).catch(function() {
$scope.success = null;
$scope.error = 'ERROR';
});
};
/**
* Store the "settings account" in a separate variable, and not in the shared "account" variable.
*/
var copyAccount = function (account) {
return {
activated: account.activated,
email: account.email,
firstName: account.firstName,
langKey: account.langKey,
lastName: account.lastName,
login: account.login
}
}
});<|fim▁end|> | |
<|file_name|>TrackSubscriber1.java<|end_file_name|><|fim▁begin|><|fim▁hole|>import java.util.concurrent.TimeUnit;
import rx.*;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;
public class TrackSubscriber1 {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
RxJavaHooks.setOnObservableStart((observable, onSubscribe) -> {
if (!onSubscribe.getClass().getName().toLowerCase().contains("map")) {
return onSubscribe;
}
System.out.println("Started");
return (Observable.OnSubscribe<Object>)observer -> {
class SignalTracker extends Subscriber<Object> {
@Override public void onNext(Object o) {
// handle onNext before or aftern notifying the downstream
observer.onNext(o);
}
@Override public void onError(Throwable t) {
// handle onError
observer.onError(t);
}
@Override public void onCompleted() {
// handle onComplete
System.out.println("Completed");
observer.onCompleted();
}
}
SignalTracker t = new SignalTracker();
onSubscribe.call(t);
};
});
Observable<Integer> observable = Observable.range(1, 5)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(integer -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return integer * 3;
});
observable.subscribe(System.out::println);
Thread.sleep(6000L);
}
}<|fim▁end|> | package hu.akarnokd.rxjava;
|
<|file_name|>test_stft.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy import linalg
from numpy.testing import assert_almost_equal, assert_array_almost_equal
from nose.tools import assert_true
from mne.time_frequency.stft import stft, istft, stftfreq, stft_norm2
def test_stft():
"Test stft and istft tight frame property"
sfreq = 1000. # Hz
f = 7. # Hz
for T in [253, 256]: # try with even and odd numbers
t = np.arange(T).astype(np.float)
x = np.sin(2 * np.pi * f * t / sfreq)
x = np.array([x, x + 1.])
wsize = 128
tstep = 4
X = stft(x, wsize, tstep)
xp = istft(X, tstep, Tx=T)
freqs = stftfreq(wsize, sfreq=1000)
max_freq = freqs[np.argmax(np.sum(np.abs(X[0]) ** 2, axis=1))]
assert_true(X.shape[1] == len(freqs))
assert_true(np.all(freqs >= 0.))
assert_true(np.abs(max_freq - f) < 1.)<|fim▁hole|>
# norm conservation thanks to tight frame property
assert_almost_equal(np.sqrt(stft_norm2(X)),
[linalg.norm(xx) for xx in x], decimal=2)
# Try with empty array
x = np.zeros((0, T))
X = stft(x, wsize, tstep)
xp = istft(X, tstep, T)
assert_true(xp.shape == x.shape)<|fim▁end|> |
assert_array_almost_equal(x, xp, decimal=6) |
<|file_name|>CommandException.java<|end_file_name|><|fim▁begin|>/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.web.commands;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.web.JRInteractiveException;
/**
* @author Narcis Marcu ([email protected])
*/
public class CommandException extends JRInteractiveException
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
public CommandException(String message) {
super(message);
}
public CommandException(Throwable t) {
super(t);
}
public CommandException(String message, Throwable t) {
super(message, t);
}
public CommandException(String messageKey, Object[] args, Throwable t)<|fim▁hole|> {
super(messageKey, args, t);
}
public CommandException(String messageKey, Object[] args)
{
super(messageKey, args);
}
}<|fim▁end|> | |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from catkin_pkg.python_setup import generate_distutils_setup
from setuptools import setup
d = generate_distutils_setup(
packages=['catkin'],
package_dir={'': 'python'},
scripts=[
'bin/catkin_find',<|fim▁hole|> 'bin/catkin_make_isolated',
'bin/catkin_test_results',
'bin/catkin_topological_order',
],
)
setup(**d)<|fim▁end|> | 'bin/catkin_init_workspace',
'bin/catkin_make', |
<|file_name|>findModel.test.ts<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { CoreNavigationCommands } from 'vs/editor/browser/controller/coreCommands';
import { ICodeEditor, IActiveCodeEditor } from 'vs/editor/browser/editorBrowser';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { PieceTreeTextBufferBuilder } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder';
import { TextModel } from 'vs/editor/common/model/textModel';
import { FindModelBoundToEditorModel } from 'vs/editor/contrib/find/findModel';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import { withTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
import { UndoRedoService } from 'vs/platform/undoRedo/common/undoRedoService';
import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService';
import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService';
suite('FindModel', () => {
function findTest(testName: string, callback: (editor: IActiveCodeEditor) => void): void {
test(testName, () => {
const textArr = [
'// my cool header',
'#include "cool.h"',
'#include <iostream>',
'',
'int main() {',
' cout << "hello world, Hello!" << endl;',
' cout << "hello world again" << endl;',
' cout << "Hello world again" << endl;',
' cout << "helloworld again" << endl;',
'}',
'// blablablaciao',
''
];
withTestCodeEditor(textArr, {}, (editor) => callback(editor as IActiveCodeEditor));
const text = textArr.join('\n');
const ptBuilder = new PieceTreeTextBufferBuilder();
ptBuilder.acceptChunk(text.substr(0, 94));
ptBuilder.acceptChunk(text.substr(94, 101));
ptBuilder.acceptChunk(text.substr(195, 59));
const factory = ptBuilder.finish();
withTestCodeEditor([],
{
model: new TextModel(factory, TextModel.DEFAULT_CREATION_OPTIONS, null, null, new UndoRedoService(new TestDialogService(), new TestNotificationService()))
},
(editor) => callback(editor as IActiveCodeEditor)
);
});
}
function fromRange(rng: Range): number[] {
return [rng.startLineNumber, rng.startColumn, rng.endLineNumber, rng.endColumn];
}
function _getFindState(editor: ICodeEditor) {
let model = editor.getModel()!;
let currentFindMatches: Range[] = [];
let allFindMatches: Range[] = [];
for (let dec of model.getAllDecorations()) {
if (dec.options.className === 'currentFindMatch') {
currentFindMatches.push(dec.range);
allFindMatches.push(dec.range);
} else if (dec.options.className === 'findMatch') {
allFindMatches.push(dec.range);
}
}
currentFindMatches.sort(Range.compareRangesUsingStarts);
allFindMatches.sort(Range.compareRangesUsingStarts);
return {
highlighted: currentFindMatches.map(fromRange),
findDecorations: allFindMatches.map(fromRange)
};
}
function assertFindState(editor: ICodeEditor, cursor: number[], highlighted: number[] | null, findDecorations: number[][]): void {
assert.deepEqual(fromRange(editor.getSelection()!), cursor, 'cursor');
let expectedState = {
highlighted: highlighted ? [highlighted] : [],
findDecorations: findDecorations
};
assert.deepEqual(_getFindState(editor), expectedState, 'state');
}
findTest('incremental find from beginning of file', (editor) => {
editor.setPosition({ lineNumber: 1, column: 1 });
let findState = new FindReplaceState();
let findModel = new FindModelBoundToEditorModel(editor, findState);
// simulate typing the search string
findState.change({ searchString: 'H' }, true);
assertFindState(
editor,
[1, 12, 1, 13],
[1, 12, 1, 13],
[
[1, 12, 1, 13],
[2, 16, 2, 17],
[6, 14, 6, 15],
[6, 27, 6, 28],
[7, 14, 7, 15],
[8, 14, 8, 15],
[9, 14, 9, 15]
]
);
// simulate typing the search string
findState.change({ searchString: 'He' }, true);
assertFindState(
editor,
[1, 12, 1, 14],
[1, 12, 1, 14],
[
[1, 12, 1, 14],
[6, 14, 6, 16],
[6, 27, 6, 29],
[7, 14, 7, 16],
[8, 14, 8, 16],
[9, 14, 9, 16]
]
);
// simulate typing the search string
findState.change({ searchString: 'Hello' }, true);
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
// simulate toggling on `matchCase`
findState.change({ matchCase: true }, true);
assertFindState(
editor,
[6, 27, 6, 32],
[6, 27, 6, 32],
[
[6, 27, 6, 32],
[8, 14, 8, 19]
]
);
// simulate typing the search string
findState.change({ searchString: 'hello' }, true);
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[9, 14, 9, 19]
]
);
// simulate toggling on `wholeWord`
findState.change({ wholeWord: true }, true);
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19]
]
);
// simulate toggling off `matchCase`
findState.change({ matchCase: false }, true);
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
// simulate toggling off `wholeWord`
findState.change({ wholeWord: false }, true);
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
// simulate adding a search scope
findState.change({ searchScope: new Range(8, 1, 10, 1) }, true);
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
// simulate removing the search scope
findState.change({ searchScope: null }, true);
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find model removes its decorations', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assert.equal(findState.matchesCount, 5);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
findModel.dispose();
findState.dispose();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
});
findTest('find model updates state matchesCount', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assert.equal(findState.matchesCount, 5);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
findState.change({ searchString: 'helloo' }, false);
assert.equal(findState.matchesCount, 0);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('find model reacts to position change', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
editor.trigger('mouse', CoreNavigationCommands.MoveTo.id, {
position: new Position(6, 20)
});
assertFindState(
editor,
[6, 20, 6, 20],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
findState.change({ searchString: 'Hello' }, true);
assertFindState(
editor,
[6, 27, 6, 32],
[6, 27, 6, 32],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find model next', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[6, 27, 6, 32],
[6, 27, 6, 32],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find model next stays in scope', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', wholeWord: true, searchScope: new Range(7, 1, 9, 1) }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find model prev', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[6, 27, 6, 32],
[6, 27, 6, 32],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find model prev stays in scope', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', wholeWord: true, searchScope: new Range(7, 1, 9, 1) }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find model next/prev with no matches', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'helloo', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('find model next/prev respects cursor position', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
editor.trigger('mouse', CoreNavigationCommands.MoveTo.id, {
position: new Position(6, 20)
});
assertFindState(
editor,
[6, 20, 6, 20],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[6, 27, 6, 32],
[6, 27, 6, 32],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('find ^', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '^', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[1, 1, 1, 1],
[2, 1, 2, 1],
[3, 1, 3, 1],
[4, 1, 4, 1],
[5, 1, 5, 1],
[6, 1, 6, 1],
[7, 1, 7, 1],
[8, 1, 8, 1],
[9, 1, 9, 1],
[10, 1, 10, 1],
[11, 1, 11, 1],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[2, 1, 2, 1],
[2, 1, 2, 1],
[
[1, 1, 1, 1],
[2, 1, 2, 1],
[3, 1, 3, 1],
[4, 1, 4, 1],
[5, 1, 5, 1],
[6, 1, 6, 1],
[7, 1, 7, 1],
[8, 1, 8, 1],
[9, 1, 9, 1],
[10, 1, 10, 1],
[11, 1, 11, 1],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[3, 1, 3, 1],
[3, 1, 3, 1],
[
[1, 1, 1, 1],
[2, 1, 2, 1],
[3, 1, 3, 1],
[4, 1, 4, 1],
[5, 1, 5, 1],
[6, 1, 6, 1],
[7, 1, 7, 1],
[8, 1, 8, 1],
[9, 1, 9, 1],
[10, 1, 10, 1],
[11, 1, 11, 1],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('find $', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '$', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[1, 18, 1, 18],
[2, 18, 2, 18],
[3, 20, 3, 20],
[4, 1, 4, 1],
[5, 13, 5, 13],
[6, 43, 6, 43],
[7, 41, 7, 41],
[8, 41, 8, 41],
[9, 40, 9, 40],
[10, 2, 10, 2],
[11, 17, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[1, 18, 1, 18],
[1, 18, 1, 18],
[
[1, 18, 1, 18],
[2, 18, 2, 18],
[3, 20, 3, 20],
[4, 1, 4, 1],
[5, 13, 5, 13],
[6, 43, 6, 43],
[7, 41, 7, 41],
[8, 41, 8, 41],
[9, 40, 9, 40],
[10, 2, 10, 2],
[11, 17, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[2, 18, 2, 18],
[2, 18, 2, 18],
[
[1, 18, 1, 18],
[2, 18, 2, 18],
[3, 20, 3, 20],
[4, 1, 4, 1],
[5, 13, 5, 13],
[6, 43, 6, 43],
[7, 41, 7, 41],
[8, 41, 8, 41],
[9, 40, 9, 40],
[10, 2, 10, 2],
[11, 17, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[3, 20, 3, 20],
[3, 20, 3, 20],
[
[1, 18, 1, 18],
[2, 18, 2, 18],
[3, 20, 3, 20],
[4, 1, 4, 1],
[5, 13, 5, 13],
[6, 43, 6, 43],
[7, 41, 7, 41],
[8, 41, 8, 41],
[9, 40, 9, 40],
[10, 2, 10, 2],
[11, 17, 11, 17],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('find next ^$', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '^$', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[4, 1, 4, 1],
[4, 1, 4, 1],
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[12, 1, 12, 1],
[12, 1, 12, 1],
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[4, 1, 4, 1],
[4, 1, 4, 1],
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('find .*', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '.*', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('find next ^.*$', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '^.*$', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[1, 1, 1, 18],
[1, 1, 1, 18],
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[2, 1, 2, 18],
[2, 1, 2, 18],
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('find prev ^.*$', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '^.*$', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[12, 1, 12, 1],
[12, 1, 12, 1],
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[11, 1, 11, 17],
[11, 1, 11, 17],
[
[1, 1, 1, 18],
[2, 1, 2, 18],
[3, 1, 3, 20],
[4, 1, 4, 1],
[5, 1, 5, 13],
[6, 1, 6, 43],
[7, 1, 7, 41],
[8, 1, 8, 41],
[9, 1, 9, 40],
[10, 1, 10, 2],
[11, 1, 11, 17],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('find prev ^$', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: '^$', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[12, 1, 12, 1],
[12, 1, 12, 1],
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[4, 1, 4, 1],
[4, 1, 4, 1],
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.moveToPrevMatch();
assertFindState(
editor,
[12, 1, 12, 1],
[12, 1, 12, 1],
[
[4, 1, 4, 1],
[12, 1, 12, 1],
]
);
findModel.dispose();
findState.dispose();
});
findTest('replace hello', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', replaceString: 'hi', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
editor.trigger('mouse', CoreNavigationCommands.MoveTo.id, {
position: new Position(6, 20)
});
assertFindState(
editor,
[6, 20, 6, 20],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[6, 27, 6, 32],
[6, 27, 6, 32],
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, hi!" << endl;');
findModel.replace();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[6, 14, 6, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hi world again" << endl;');
findModel.replace();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "hi world again" << endl;');
findModel.replace();
assertFindState(
editor,
[6, 16, 6, 16],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hi world, hi!" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('replace bla', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'bla', replaceString: 'ciao' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[11, 4, 11, 7],
[11, 7, 11, 10],
[11, 10, 11, 13]
]
);
findModel.replace();
assertFindState(
editor,
[11, 4, 11, 7],
[11, 4, 11, 7],
[
[11, 4, 11, 7],
[11, 7, 11, 10],
[11, 10, 11, 13]
]
);
assert.equal(editor.getModel()!.getLineContent(11), '// blablablaciao');
findModel.replace();
assertFindState(
editor,
[11, 8, 11, 11],
[11, 8, 11, 11],
[
[11, 8, 11, 11],
[11, 11, 11, 14]
]
);
assert.equal(editor.getModel()!.getLineContent(11), '// ciaoblablaciao');
findModel.replace();
assertFindState(
editor,
[11, 12, 11, 15],
[11, 12, 11, 15],
[
[11, 12, 11, 15]
]
);
assert.equal(editor.getModel()!.getLineContent(11), '// ciaociaoblaciao');
findModel.replace();
assertFindState(
editor,
[11, 16, 11, 16],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(11), '// ciaociaociaociao');
findModel.dispose();
findState.dispose();
});
findTest('replaceAll hello', (editor) => {
let findState = new FindReplaceState();<|fim▁hole|> assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
editor.trigger('mouse', CoreNavigationCommands.MoveTo.id, {
position: new Position(6, 20)
});
assertFindState(
editor,
[6, 20, 6, 20],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, Hello!" << endl;');
findModel.replaceAll();
assertFindState(
editor,
[6, 17, 6, 17],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hi world, hi!" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hi world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "hi world again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('replaceAll two spaces with one space', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: ' ', replaceString: ' ' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 1, 6, 3],
[6, 3, 6, 5],
[7, 1, 7, 3],
[7, 3, 7, 5],
[8, 1, 8, 3],
[8, 3, 8, 5],
[9, 1, 9, 3],
[9, 3, 9, 5]
]
);
findModel.replaceAll();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 1, 6, 3],
[7, 1, 7, 3],
[8, 1, 8, 3],
[9, 1, 9, 3]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, Hello!" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hello world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "Hello world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(9), ' cout << "helloworld again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('replaceAll bla', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'bla', replaceString: 'ciao' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[11, 4, 11, 7],
[11, 7, 11, 10],
[11, 10, 11, 13]
]
);
findModel.replaceAll();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(11), '// ciaociaociaociao');
findModel.dispose();
findState.dispose();
});
findTest('replaceAll bla with \\t\\n', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'bla', replaceString: '<\\n\\t>', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[11, 4, 11, 7],
[11, 7, 11, 10],
[11, 10, 11, 13]
]
);
findModel.replaceAll();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(11), '// <');
assert.equal(editor.getModel()!.getLineContent(12), '\t><');
assert.equal(editor.getModel()!.getLineContent(13), '\t><');
assert.equal(editor.getModel()!.getLineContent(14), '\t>ciao');
findModel.dispose();
findState.dispose();
});
findTest('issue #3516: "replace all" moves page/cursor/focus/scroll to the place of the last replacement', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'include', replaceString: 'bar' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[2, 2, 2, 9],
[3, 2, 3, 9]
]
);
findModel.replaceAll();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(2), '#bar "cool.h"');
assert.equal(editor.getModel()!.getLineContent(3), '#bar <iostream>');
findModel.dispose();
findState.dispose();
});
findTest('listens to model content changes', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', replaceString: 'hi', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
editor!.getModel()!.setValue('hello\nhi');
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('selectAllMatches', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', replaceString: 'hi', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.selectAllMatches();
assert.deepEqual(editor!.getSelections()!.map(s => s.toString()), [
new Selection(6, 14, 6, 19),
new Selection(6, 27, 6, 32),
new Selection(7, 14, 7, 19),
new Selection(8, 14, 8, 19)
].map(s => s.toString()));
assertFindState(
editor,
[6, 14, 6, 19],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('issue #14143 selectAllMatches should maintain primary cursor if feasible', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', replaceString: 'hi', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
editor.setSelection(new Range(7, 14, 7, 19));
findModel.selectAllMatches();
assert.deepEqual(editor!.getSelections()!.map(s => s.toString()), [
new Selection(7, 14, 7, 19),
new Selection(6, 14, 6, 19),
new Selection(6, 27, 6, 32),
new Selection(8, 14, 8, 19)
].map(s => s.toString()));
assert.deepEqual(editor!.getSelection()!.toString(), new Selection(7, 14, 7, 19).toString());
assertFindState(
editor,
[7, 14, 7, 19],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('issue #1914: NPE when there is only one find match', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'cool.h' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[2, 11, 2, 17]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[2, 11, 2, 17],
[2, 11, 2, 17],
[
[2, 11, 2, 17]
]
);
findModel.moveToNextMatch();
assertFindState(
editor,
[2, 11, 2, 17],
[2, 11, 2, 17],
[
[2, 11, 2, 17]
]
);
findModel.dispose();
findState.dispose();
});
findTest('replace when search string has look ahed regex', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello(?=\\sworld)', replaceString: 'hi', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.replace();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hi world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hi world again" << endl;');
findModel.replace();
assertFindState(
editor,
[8, 16, 8, 16],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "hi world again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('replace when search string has look ahed regex and cursor is at the last find match', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello(?=\\sworld)', replaceString: 'hi', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
editor.trigger('mouse', CoreNavigationCommands.MoveTo.id, {
position: new Position(8, 14)
});
assertFindState(
editor,
[8, 14, 8, 14],
null,
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.replace();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "Hello world again" << endl;');
findModel.replace();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19],
]
);
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "hi world again" << endl;');
findModel.replace();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[7, 14, 7, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hi world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[7, 16, 7, 16],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hi world again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('replaceAll when search string has look ahed regex', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello(?=\\sworld)', replaceString: 'hi', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.replaceAll();
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hi world, Hello!" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hi world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "hi world again" << endl;');
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('replace when search string has look ahed regex and replace string has capturing groups', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hel(lo)(?=\\sworld)', replaceString: 'hi$1', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.replace();
assertFindState(
editor,
[6, 14, 6, 19],
[6, 14, 6, 19],
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[7, 14, 7, 19],
[7, 14, 7, 19],
[
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hilo world, Hello!" << endl;');
findModel.replace();
assertFindState(
editor,
[8, 14, 8, 19],
[8, 14, 8, 19],
[
[8, 14, 8, 19]
]
);
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hilo world again" << endl;');
findModel.replace();
assertFindState(
editor,
[8, 18, 8, 18],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "hilo world again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('replaceAll when search string has look ahed regex and replace string has capturing groups', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'wo(rl)d(?=.*;$)', replaceString: 'gi$1', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 20, 6, 25],
[7, 20, 7, 25],
[8, 20, 8, 25],
[9, 19, 9, 24]
]
);
findModel.replaceAll();
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello girl, Hello!" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hello girl again" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "Hello girl again" << endl;');
assert.equal(editor.getModel()!.getLineContent(9), ' cout << "hellogirl again" << endl;');
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('replaceAll when search string is multiline and has look ahed regex and replace string has capturing groups', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'wo(rl)d(.*;\\n)(?=.*hello)', replaceString: 'gi$1$2', isRegex: true, matchCase: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 20, 7, 1],
[8, 20, 9, 1]
]
);
findModel.replaceAll();
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hello girl, Hello!" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "Hello girl again" << endl;');
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('replaceAll preserving case', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', replaceString: 'goodbye', isRegex: false, matchCase: false, preserveCase: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19],
[9, 14, 9, 19],
]
);
findModel.replaceAll();
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "goodbye world, Goodbye!" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "goodbye world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << "Goodbye world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(9), ' cout << "goodbyeworld again" << endl;');
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
findModel.dispose();
findState.dispose();
});
findTest('issue #18711 replaceAll with empty string', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', replaceString: '', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[6, 27, 6, 32],
[7, 14, 7, 19],
[8, 14, 8, 19]
]
);
findModel.replaceAll();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << " world, !" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << " world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(8), ' cout << " world again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('issue #32522 replaceAll with ^ on more than 1000 matches', (editor) => {
let initialText = '';
for (let i = 0; i < 1100; i++) {
initialText += 'line' + i + '\n';
}
editor!.getModel()!.setValue(initialText);
let findState = new FindReplaceState();
findState.change({ searchString: '^', replaceString: 'a ', isRegex: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
findModel.replaceAll();
let expectedText = '';
for (let i = 0; i < 1100; i++) {
expectedText += 'a line' + i + '\n';
}
expectedText += 'a ';
assert.equal(editor!.getModel()!.getValue(), expectedText);
findModel.dispose();
findState.dispose();
});
findTest('issue #19740 Find and replace capture group/backreference inserts `undefined` instead of empty string', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello(z)?', replaceString: 'hi$1', isRegex: true, matchCase: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[6, 14, 6, 19],
[7, 14, 7, 19],
[9, 14, 9, 19]
]
);
findModel.replaceAll();
assertFindState(
editor,
[1, 1, 1, 1],
null,
[]
);
assert.equal(editor.getModel()!.getLineContent(6), ' cout << "hi world, Hello!" << endl;');
assert.equal(editor.getModel()!.getLineContent(7), ' cout << "hi world again" << endl;');
assert.equal(editor.getModel()!.getLineContent(9), ' cout << "hiworld again" << endl;');
findModel.dispose();
findState.dispose();
});
findTest('issue #27083. search scope works even if it is a single line', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', wholeWord: true, searchScope: new Range(7, 1, 8, 1) }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assertFindState(
editor,
[1, 1, 1, 1],
null,
[
[7, 14, 7, 19]
]
);
findModel.dispose();
findState.dispose();
});
findTest('issue #3516: Control behavior of "Next" operations (not looping back to beginning)', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello', loop: false }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assert.equal(findState.matchesCount, 5);
// Test next operations
assert.equal(findState.matchesPosition, 0);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), false);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 2);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 3);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 4);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 5);
assert.equal(findState.canNavigateForward(), false);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 5);
assert.equal(findState.canNavigateForward(), false);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 5);
assert.equal(findState.canNavigateForward(), false);
assert.equal(findState.canNavigateBack(), true);
// Test previous operations
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 4);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 3);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 2);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), false);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), false);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), false);
});
findTest('issue #3516: Control behavior of "Next" operations (looping back to beginning)', (editor) => {
let findState = new FindReplaceState();
findState.change({ searchString: 'hello' }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
assert.equal(findState.matchesCount, 5);
// Test next operations
assert.equal(findState.matchesPosition, 0);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 2);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 3);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 4);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 5);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToNextMatch();
assert.equal(findState.matchesPosition, 2);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
// Test previous operations
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 5);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 4);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 3);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 2);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
findModel.moveToPrevMatch();
assert.equal(findState.matchesPosition, 1);
assert.equal(findState.canNavigateForward(), true);
assert.equal(findState.canNavigateBack(), true);
});
});<|fim▁end|> | findState.change({ searchString: 'hello', replaceString: 'hi', wholeWord: true }, false);
let findModel = new FindModelBoundToEditorModel(editor, findState);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.