prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>pages_6.js<|end_file_name|><|fim▁begin|>var searchData=
[
['revision_20history_20of_20cmsis_2dpack',['Revision History of CMSIS-Pack',['../pack_revisionHistory.html',1,'index']]]<|fim▁hole|><|fim▁end|> | ]; |
<|file_name|>box.py<|end_file_name|><|fim▁begin|>"""Box geometry."""
from __future__ import division
from .helpers import poparg
class Box(object):
"""A Box holds the geometry of a box with a position and a size.
Because of how it is typically used, it takes a single dictionary of
arguments. The dictionary of arguments has arguments popped from it, and
others ignored::
<|fim▁hole|> >>> b.center
(105.0, 200)
>>> b.size
(10, 50)
>>> args
{'foo': 17}
The center and size are available as individual components also::
>>> b.cx
105.0
>>> b.cy
200
>>> b.w
10
>>> b.h
50
You can ask about the edges of the box as coordinates (top, bottom, left,
right) or points (north, south, east, west)::
>>> b.north
(105.0, 175.0)
>>> b.south
(105.0, 225.0)
>>> b.top
175.0
>>> b.bottom
225.0
"""
def __init__(self, args):
other_box = poparg(args, box=None)
if other_box is not None:
# Copy all the attributes of the other box.
self.__dict__.update(other_box.__dict__)
return
size = poparg(args, size=None)
assert size, "Have to specify a size!"
pos_name = pos = None
arg_names = "left center right top topleft topright".split()
for arg_name in arg_names:
arg = poparg(args, **{arg_name: None})
if arg is not None:
assert pos is None, "Got duplicate position: %s" % pos_name
pos_name = arg_name
pos = arg
# Can specify position as pos=('topright', (100,200))
pos_arg = poparg(args, pos=None)
if pos_arg is not None:
assert pos is None, "Got duplicate position: pos"
pos_name, pos = pos_arg
if pos_name == 'left':
center = (pos[0]+size[0]/2, pos[1])
elif pos_name == 'right':
center = (pos[0]-size[0]/2, pos[1])
elif pos_name == 'center':
center = pos
elif pos_name == 'top':
center = (pos[0], pos[1]+size[1]/2)
elif pos_name == 'topleft':
center = (pos[0]+size[0]/2, pos[1]+size[1]/2)
elif pos_name == 'topright':
center = (pos[0]-size[0]/2, pos[1]+size[1]/2)
else:
assert False, "Have to specify a position!"
self.cx, self.cy = center
self.w, self.h = size
self.rise = poparg(args, rise=0)
self.set = poparg(args, set=999999)
self.fade = poparg(args, fade=0)
def __repr__(self):
return "<Box ={0.w}x{0.h} @{0.cx},{0.cy}>".format(self)
def __eq__(self, other):
if not isinstance(other, Box):
return False
return (
self.center == other.center and
self.size == other.size and
self.rise == other.rise and
self.set == other.set and
self.fade == other.fade
)
def __ne__(self, other):
return not self == other
def translate(self, dx, dy):
"""Create a new box just like this one, but translated.
`dx` and `dy` are deltas for the center point. The returned box is
the same as this one, but the center has moved::
>>> b = Box(dict(size=(10,20), center=(100,200)))
>>> b2 = b.translate(1, 2)
>>> b2.center
(101, 202)
>>> b2.size
(10, 20)
The original box is unchanged::
>>> b.center
(100, 200)
"""
box = Box(dict(box=self))
box.cx += dx
box.cy += dy
return box
def scale(self, sx, sy=None):
"""Make a new box that is scaled from this one."""
sy = sy or sx
cx = self.cx * sx
cy = self.cy * sy
w = self.w * sx
h = self.h * sy
return Box(dict(size=(w, h), center=(cx, cy)))
def union(self, other):
"""Create a new box that covers self and other."""
left = min(self.left, other.left)
right = max(self.right, other.right)
top = min(self.top, other.top)
bottom = max(self.bottom, other.bottom)
width = right - left
height = bottom - top
box = Box(dict(size=(width, height), topleft=(left, top)))
return box
@property
def center(self):
"""The center point of the box."""
return self.cx, self.cy
@property
def size(self):
"""The width and height as a pair."""
return self.w, self.h
@property
def top(self):
"""The y-coodinate of the top edge."""
return self.cy - self.h/2
@property
def bottom(self):
"""The y-coordinate of the bottom edge."""
return self.cy + self.h/2
@property
def left(self):
"""The x-coordinate of the left edge."""
return self.cx - self.w/2
@property
def right(self):
"""The x-coordinate of the right edge."""
return self.cx + self.w/2
@property
def north(self):
"""The point at the north of the box."""
return self.cx, self.top
@property
def south(self):
"""The point at the south of the box."""
return self.cx, self.bottom
@property
def east(self):
"""The point at the east of the box."""
return self.right, self.cy
@property
def west(self):
"""The point at the west of the box."""
return self.left, self.cy<|fim▁end|> | >>> args = {'foo': 17, 'size': (10, 50), 'left': (100, 200)}
>>> b = Box(args) |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
import InfinityRoute from "../../../../mixins/infinity-route";
export default Ember.Route.extend(InfinityRoute, AuthenticatedRouteMixin, {
_listName: 'model',
model: function() {
return this.infinityModel("report", { perPage: 10, startingPage: 1});
},
actions: {
remove: function(model) {
if(confirm('Are you sure?')) {
model.destroyRecord();
}<|fim▁hole|> var filter = { perPage: 10, startingPage: 1};
this.get('controller').set('model', this.infinityModel("report", filter))
}
}
});<|fim▁end|> | },
search: function () {
this.set('_listName', 'model.content');
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// WARNING: This file is regenerated by the `cargo func new` command.
// Only the `azure_functions::export!` macro invocation will be preserved.
// Export the modules that define Azure Functions here.
azure_functions::export! {
greet,<|fim▁hole|><|fim▁end|> | greet_with_json,
} |
<|file_name|>hq-category-test.js<|end_file_name|><|fim▁begin|>import {
moduleForComponent,
test<|fim▁hole|>moduleForComponent('hq-category', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar']
});
test('it renders', function(assert) {
assert.expect(2);
// Creates the component instance
var component = this.subject();
assert.equal(component._state, 'preRender');
// Renders the component to the page
this.render();
assert.equal(component._state, 'inDOM');
});<|fim▁end|> | } from 'ember-qunit';
|
<|file_name|>volume_axes.py<|end_file_name|><|fim▁begin|>from traits.api import Bool, Float, Tuple
from tvtk.api import tvtk
from .volume_scene_member import ABCVolumeSceneMember
# Convenience for the trait definitions below
FloatPair = Tuple(Float, Float)
class VolumeAxes(ABCVolumeSceneMember):
""" An object which builds a CubeAxesActor for a scene containing a Volume.
"""
# If True, show the minor tick marks on the CubeAxesActor
show_axis_minor_ticks = Bool(False)<|fim▁hole|> # Which axes should have a scale shown?
visible_axis_scales = Tuple(Bool, Bool, Bool)
#--------------------------------------------------------------------------
# ABCVolumeSceneMember interface
#--------------------------------------------------------------------------
def add_actors_to_scene(self, scene_model, volume_actor):
# Some axes with ticks
if any(self.visible_axis_scales):
bounds = volume_actor.bounds
x_vis, y_vis, z_vis = self.visible_axis_scales
x_range, y_range, z_range = self.visible_axis_ranges
cube_axes = tvtk.CubeAxesActor(
bounds=bounds,
camera=scene_model.camera,
tick_location='outside',
x_title='', x_units='',
y_title='', y_units='',
z_title='', z_units='',
x_axis_visibility=x_vis,
y_axis_visibility=y_vis,
z_axis_visibility=z_vis,
x_axis_range=x_range,
y_axis_range=y_range,
z_axis_range=z_range,
x_axis_minor_tick_visibility=self.show_axis_minor_ticks,
y_axis_minor_tick_visibility=self.show_axis_minor_ticks,
z_axis_minor_tick_visibility=self.show_axis_minor_ticks,
)
scene_model.renderer.add_actor(cube_axes)
#--------------------------------------------------------------------------
# Default values
#--------------------------------------------------------------------------
def _visible_axis_ranges_default(self):
return ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0))
def _visible_axis_scales_default(self):
return (False, False, False)<|fim▁end|> |
# What are the physical value ranges for each axis?
visible_axis_ranges = Tuple(FloatPair, FloatPair, FloatPair)
|
<|file_name|>IlonaPositioningApplicationContext.java<|end_file_name|><|fim▁begin|>package uni.miskolc.ips.ilona.positioning.web;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import uni.miskolc.ips.ilona.measurement.model.measurement.MeasurementDistanceCalculator;
import uni.miskolc.ips.ilona.measurement.model.measurement.MeasurementDistanceCalculatorImpl;
import uni.miskolc.ips.ilona.measurement.model.measurement.wifi.VectorIntersectionWiFiRSSIDistance;
import uni.miskolc.ips.ilona.positioning.service.PositioningService;
import uni.miskolc.ips.ilona.positioning.service.gateway.MeasurementGateway;
import uni.miskolc.ips.ilona.positioning.service.gateway.MeasurementGatewaySIConfig;
import uni.miskolc.ips.ilona.positioning.service.impl.classification.bayes.NaiveBayesPositioningService;
import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNPositioning;
import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNSimplePositioning;
import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNWeightedPositioning;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "uni.miskolc.ips.ilona.positioning.controller")
public class IlonaPositioningApplicationContext extends WebMvcConfigurerAdapter {
@Bean
public VectorIntersectionWiFiRSSIDistance wifiDistanceCalculator() {
return new VectorIntersectionWiFiRSSIDistance();
}
@Bean
public MeasurementDistanceCalculator measurementDistanceCalculator() {
//TODO
double wifiDistanceWeight = 1.0;
double magnetometerDistanceWeight = 0.5;
double gpsDistanceWeight = 0.0;
double bluetoothDistanceWeight = 1.0;
double rfidDistanceWeight = 0.0;
return new MeasurementDistanceCalculatorImpl(wifiDistanceCalculator(), wifiDistanceWeight, magnetometerDistanceWeight, gpsDistanceWeight, bluetoothDistanceWeight, rfidDistanceWeight);
}
@Bean
public KNNPositioning positioningService() {
//TODO
MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator();
ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class);
MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class);
int k = 3;
return new KNNSimplePositioning(distanceCalculator, measurementGateway, k);
}
@Bean
public KNNPositioning knnpositioningService() {
//TODO
/* MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator();
MeasurementGateway measurementGateway = null;
int k = 3;
return new KNNSimplePositioning(distanceCalculator, measurementGateway, k);
*/
return positioningService();
}
@Bean
public KNNPositioning knnWpositioningService() {
//TODO
MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator();
ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class);
MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class);
int k = 3;
return new KNNWeightedPositioning(distanceCalculator, measurementGateway, k);
}
@Bean
public PositioningService naivebayespositioningService() {
//TODO
int maxMeasurementDistance = 50;
ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class);
MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class);
MeasurementDistanceCalculator measDistanceCalculator = measurementDistanceCalculator();
return new NaiveBayesPositioningService(measurementGateway, measDistanceCalculator, maxMeasurementDistance);
}
@Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
return bean;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");<|fim▁hole|>
}<|fim▁end|> | registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/");
} |
<|file_name|>amr_corpus_reader.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
return [p.rsplit('-',1)[0] for p in s.split()]
def format_amr(l):
amr_s = ' '.join(l)
amr_g = Hgraph.from_string(amr_s)
return amr_g
def read_to_empty(f):
lines = []
while True:
l = f.readline().strip()
if not l: return lines
lines.append(l)
def format_constituents(l):
return nltk.tree.ParentedTree("\n".join(l))
def format_alignments(l, amr):
"""
Parse alignment descriptions from file
"""
r = []
for a in l:
m = re.match(r'(\S+)\s+:(\S+)\s+(\S+)\s+(.+)\-(\d+)', a)
if m:
var = m.group(1)
role = m.group(2)
filler = m.group(3).replace('"','')
token = m.group(4)
token_id = int(m.group(5)) - 1
else: <|fim▁hole|> var = None
role = "ROOT"
filler = amr.roots[0].replace('"','')
token = m.group(1)
token_id = int(m.group(2)) - 1
else:
sys.exit(1)
amr_triple = (var, role, (filler,))
r.append((amr_triple, token_id))
return r
textlinematcher = re.compile("^(\d+)\.(.*?)\((.*)\)?$")
def format_text(l):
match = textlinematcher.match(l.strip())
if not match:
raise ValueError, "Not a valid text line in Ulf corpus: \n %s \n"%l
s_no = int(match.group(1))
text = match.group(2).strip().split(" ")
s_id = match.group(3).strip()
return s_id, s_no, text
def plain_corpus(f):
while True:
x = read_to_empty(f)
if not x:
raise StopIteration
amr = format_amr(x)
yield amr
def aligned_corpus(f):
"""
Read the next parsed sentence from an input file using the aligned AMR/tagged string format.
"""
while True:
l = f.readline()
if not l:
raise StopIteration
while l.strip().startswith("#") or l.strip().startswith("==") or not l.strip():
l = f.readline()
if not l:
raise IOError, "AMR data file ended unexpectedly."
sent_id = int(l)
l = f.readline()
amr = format_amr(read_to_empty(f))
tagged = format_tagged(f.readline())
l = f.readline()
alignments = format_alignments(read_to_empty(f), amr)
p = SentenceWithHgraph(sent_id, sent_id, amr, tagged, None, alignments)
yield p
def ulf_corpus(f):
"""
Read the next parsed sentence from an input file using Ulf's format.
"""
while True:
l = f.readline()
if not l:
raise StopIteration
while l.strip().startswith("#") or not l.strip():
l = f.readline()
if not l:
raise IOError, "AMR data file ended unexpectedly- sentence without AMR."
sent_id, sent_no, tagged = format_text(l.strip())
l = f.readline()
amr = format_amr(read_to_empty(f))
p = SentenceWithHgraph(sent_id, sent_no, amr, tagged, None, None)
yield p
def metadata_amr_corpus(f):
"""
Read the next parsed sentence from an input file using the AMR meta data format.
"""
metadata = []
sentence = ""
sent_id = ""
buff = []
idmatcher = re.compile("# ::id ([^ ]+) ")
sentmatcher = re.compile("# ::snt (.*)")
count = 1
parser = amr_graph_description_parser.GraphDescriptionParser()
while True:
l = f.readline()
if not l:
raise StopIteration
l = l.strip()
if not l:
if buff:
amr = parser.parse_string(" ".join(buff))
yield SentenceWithHgraph(sent_id, count, amr, sentence, metadata = metadata)
count += 1
buff = []
metadata = []
sentence = ""
sent_id = ""
elif l.startswith("#"):
metadata.append(l)
match = idmatcher.match(l)
if match:
sent_id = match.group(1)
match = sentmatcher.match(l)
if match:
sentence = match.group(1)
else:
buff.append(l)
class SentenceWithHgraph():
"""
A data structure to hold Hgraph <-> sentence pairs with
PTB parses and token to Hgraph edge elignments.
"""
def __init__(self, sent_id, sent_no, amr, tagged, ptb = None, edge_alignments = None, metadata = None):
self.sent_no = sent_no
self.sent_id = sent_id
self.amr = amr
self.tagged = tagged
self.ptb = ptb
self.alignments = edge_alignments
self.metadata = metadata
#in_f = open(sys.argv[1],'r')
#corpus = metadata_amr_corpus(in_f)<|fim▁end|> | m = re.match(r'ROOT\s+([^\-]+)\-(\d+)', a)
if m:
|
<|file_name|>IndexHits.java<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.graphdb.index;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
/**
* An {@link Iterator} with additional {@link #size()} and {@link #close()}
* methods on it, used for iterating over index query results. It is first and
* foremost an {@link Iterator}, but also an {@link Iterable} JUST so that it
* can be used in a for-each loop. The <code>iterator()</code> method
* <i>always</i> returns <code>this</code>.
*
* The size is calculated before-hand so that calling it is always fast.
*
* When you're done with the result and haven't reached the end of the
* iteration {@link #close()} must be called. Results which are looped through
* entirely closes automatically. Typical use:
*
* <pre>
* IndexHits<Node> hits = index.get( "key", "value" );
* try
* {
* for ( Node node : hits )
* {
* // do something with the hit
* }
* }
* finally
* {
* hits.close();
* }
* </pre>
*
* @param <T> the type of items in the Iterator.
*/
public interface IndexHits<T> extends Iterator<T>, Iterable<T>
{
/**
* Returns the size of this iterable, in most scenarios this value is accurate
* while in some scenarios near-accurate.
*
* There's no cost in calling this method. It's considered near-accurate if this
* {@link IndexHits} object has been returned when inside a {@link Transaction}
* which has index modifications, of a certain nature. Also entities
* ({@link Node}s/{@link Relationship}s) which have been deleted from the graph,
* but are still in the index will also affect the accuracy of the returned size.
*
* @return the near-accurate size if this iterable.
*/
int size();<|fim▁hole|> * anymore. It's necessary to call it so that underlying indexes can dispose
* of allocated resources for this search result.
*
* You can however skip to call this method if you loop through the whole
* result, then close() will be called automatically. Even if you loop
* through the entire result and then call this method it will silently
* ignore any consequtive call (for convenience).
*/
void close();
/**
* Returns the first and only item from the result iterator, or {@code null}
* if there was none. If there were more than one item in the result a
* {@link NoSuchElementException} will be thrown. This method must be called
* first in the iteration and will grab the first item from the iteration,
* so the result is considered broken after this call.
*
* @return the first and only item, or {@code null} if none.
*/
T getSingle();
/**
* Returns the score of the most recently fetched item from this iterator
* (from {@link #next()}). The range of the returned values is up to the
* {@link Index} implementation to dictate.
* @return the score of the most recently fetched item from this iterator.
*/
float currentScore();
}<|fim▁end|> |
/**
* Closes the underlying search result. This method should be called
* whenever you've got what you wanted from the result and won't use it |
<|file_name|>GBA.cpp<|end_file_name|><|fim▁begin|>#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include "../../Port.h"
#include "../../NLS.h"
#include "../GBA.h"
#include "../GBAGlobals.h"
#include "../GBAinline.h"
#include "../GBACheats.h"
#include "GBACpu.h"
#include "../GBAGfx.h"
#include "../GBASound.h"
#include "../EEprom.h"
#include "../Flash.h"
#include "../Sram.h"
#include "../bios.h"
#include "../elf.h"
#include "../RTC.h"
#include "../agbprint.h"
#include "../../common/System.h"
#include "../../common/SystemGlobals.h"
#include "../../common/Util.h"
#include "../../common/movie.h"
#include "../../common/vbalua.h"
#ifdef PROFILING
#include "../prof/prof.h"
#endif
#ifdef __GNUC__
#define _stricmp strcasecmp
#endif
static inline void interp_rate()
{ /* empty for now */ }
int32 SWITicks = 0;
int32 IRQTicks = 0;
u32 mastercode = 0;
int32 layerEnableDelay = 0;
bool8 busPrefetch = false;
bool8 busPrefetchEnable = false;
u32 busPrefetchCount = 0;
u32 cpuPrefetch[2];
int32 cpuDmaTicksToUpdate = 0;
int32 cpuDmaCount = 0;
bool8 cpuDmaHack = 0;
u32 cpuDmaLast = 0;
int32 dummyAddress = 0;
int32 gbaSaveType = 0; // used to remember the save type on reset
bool8 intState = false;
bool8 stopState = false;
bool8 holdState = false;
int32 holdType = 0;
bool8 cpuSramEnabled = true;
bool8 cpuFlashEnabled = true;
bool8 cpuEEPROMEnabled = true;
bool8 cpuEEPROMSensorEnabled = false;
#ifdef SDL
bool8 cpuBreakLoop = false;
#endif
// These don't seem to affect determinism
int32 cpuNextEvent = 0;
int32 cpuTotalTicks = 0;
#ifdef PROFILING
int profilingTicks = 0;
int profilingTicksReload = 0;
static profile_segment *profilSegment = NULL;
#endif
#ifdef BKPT_SUPPORT
u8 freezeWorkRAM[0x40000];
u8 freezeInternalRAM[0x8000];
u8 freezeVRAM[0x18000];
u8 freezePRAM[0x400];
u8 freezeOAM[0x400];
bool debugger_last;
#endif
int32 lcdTicks = (useBios && !skipBios) ? 1008 : 208;
u8 timerOnOffDelay = 0;
u16 timer0Value = 0;
bool8 timer0On = false;
int32 timer0Ticks = 0;
int32 timer0Reload = 0;
int32 timer0ClockReload = 0;
u16 timer1Value = 0;
bool8 timer1On = false;
int32 timer1Ticks = 0;
int32 timer1Reload = 0;
int32 timer1ClockReload = 0;
u16 timer2Value = 0;
bool8 timer2On = false;
int32 timer2Ticks = 0;
int32 timer2Reload = 0;
int32 timer2ClockReload = 0;
u16 timer3Value = 0;
bool8 timer3On = false;
int32 timer3Ticks = 0;
int32 timer3Reload = 0;
int32 timer3ClockReload = 0;
u32 dma0Source = 0;
u32 dma0Dest = 0;
u32 dma1Source = 0;
u32 dma1Dest = 0;
u32 dma2Source = 0;
u32 dma2Dest = 0;
u32 dma3Source = 0;
u32 dma3Dest = 0;
void (*cpuSaveGameFunc)(u32, u8) = flashSaveDecide;
void (*renderLine)() = mode0RenderLine;
bool8 fxOn = false;
bool8 windowOn = false;
char buffer[1024];
FILE *out = NULL;
const int32 TIMER_TICKS[4] = { 0, 6, 8, 10 };
extern bool8 cpuIsMultiBoot;
extern const u32 objTilesAddress[3] = { 0x010000, 0x014000, 0x014000 };
const u8 gamepakRamWaitState[4] = { 4, 3, 2, 8 };
const u8 gamepakWaitState[4] = { 4, 3, 2, 8 };
const u8 gamepakWaitState0[2] = { 2, 1 };
const u8 gamepakWaitState1[2] = { 4, 1 };
const u8 gamepakWaitState2[2] = { 8, 1 };
const bool8 isInRom[16] =
{ false, false, false, false, false, false, false, false,
true, true, true, true, true, true, false, false };
u8 memoryWait[16] =
{ 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 0 };
u8 memoryWait32[16] =
{ 0, 0, 5, 0, 0, 1, 1, 0, 7, 7, 9, 9, 13, 13, 4, 0 };
u8 memoryWaitSeq[16] =
{ 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4, 0 };
u8 memoryWaitSeq32[16] =
{ 0, 0, 5, 0, 0, 1, 1, 0, 5, 5, 9, 9, 17, 17, 4, 0 };
// The videoMemoryWait constants are used to add some waitstates
// if the opcode access video memory data outside of vblank/hblank
// It seems to happen on only one ticks for each pixel.
// Not used for now (too problematic with current code).
//const u8 videoMemoryWait[16] =
// {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static int32 romSize = 0x2000000;
u8 biosProtected[4];
u8 cpuBitsSet[256];
u8 cpuLowestBitSet[256];
#ifdef WORDS_BIGENDIAN
bool8 cpuBiosSwapped = false;
#endif
u32 myROM[] = {
0xEA000006,
0xEA000093,
0xEA000006,
0x00000000,
0x00000000,
0x00000000,
0xEA000088,
0x00000000,
0xE3A00302,
0xE1A0F000,
0xE92D5800,
0xE55EC002,
0xE28FB03C,
0xE79BC10C,
0xE14FB000,
0xE92D0800,
0xE20BB080,
0xE38BB01F,
0xE129F00B,
0xE92D4004,
0xE1A0E00F,
0xE12FFF1C,
0xE8BD4004,
0xE3A0C0D3,
0xE129F00C,
0xE8BD0800,
0xE169F00B,
0xE8BD5800,
0xE1B0F00E,
0x0000009C,
0x0000009C,
0x0000009C,
0x0000009C,
0x000001F8,
0x000001F0,
0x000000AC,
0x000000A0,
0x000000FC,
0x00000168,
0xE12FFF1E,
0xE1A03000,
0xE1A00001,
0xE1A01003,
0xE2113102,
0x42611000,
0xE033C040,
0x22600000,
0xE1B02001,
0xE15200A0,
0x91A02082,
0x3AFFFFFC,
0xE1500002,
0xE0A33003,
0x20400002,
0xE1320001,
0x11A020A2,
0x1AFFFFF9,
0xE1A01000,
0xE1A00003,
0xE1B0C08C,
0x22600000,
0x42611000,
0xE12FFF1E,
0xE92D0010,
0xE1A0C000,
0xE3A01001,
0xE1500001,
0x81A000A0,
0x81A01081,
0x8AFFFFFB,
0xE1A0000C,
0xE1A04001,
0xE3A03000,
0xE1A02001,
0xE15200A0,
0x91A02082,
0x3AFFFFFC,
0xE1500002,
0xE0A33003,
0x20400002,
0xE1320001,
0x11A020A2,
0x1AFFFFF9,
0xE0811003,
0xE1B010A1,
0xE1510004,
0x3AFFFFEE,
0xE1A00004,
0xE8BD0010,
0xE12FFF1E,
0xE0010090,
0xE1A01741,
0xE2611000,
0xE3A030A9,
0xE0030391,
0xE1A03743,
0xE2833E39,
0xE0030391,
0xE1A03743,
0xE2833C09,
0xE283301C,
0xE0030391,
0xE1A03743,
0xE2833C0F,
0xE28330B6,
0xE0030391,
0xE1A03743,
0xE2833C16,
0xE28330AA,
0xE0030391,
0xE1A03743,
0xE2833A02,
0xE2833081,
0xE0030391,
0xE1A03743,
0xE2833C36,
0xE2833051,
0xE0030391,
0xE1A03743,
0xE2833CA2,
0xE28330F9,
0xE0000093,
0xE1A00840,
0xE12FFF1E,
0xE3A00001,
0xE3A01001,
0xE92D4010,
0xE3A03000,
0xE3A04001,
0xE3500000,
0x1B000004,
0xE5CC3301,
0xEB000002,
0x0AFFFFFC,
0xE8BD4010,
0xE12FFF1E,
0xE3A0C301,
0xE5CC3208,
0xE15C20B8,
0xE0110002,
0x10222000,
0x114C20B8,
0xE5CC4208,
0xE12FFF1E,
0xE92D500F,
0xE3A00301,
0xE1A0E00F,
0xE510F004,
0xE8BD500F,
0xE25EF004,
0xE59FD044,
0xE92D5000,
0xE14FC000,
0xE10FE000,
0xE92D5000,
0xE3A0C302,
0xE5DCE09C,
0xE35E00A5,
0x1A000004,
0x05DCE0B4,
0x021EE080,
0xE28FE004,
0x159FF018,
0x059FF018,
0xE59FD018,
0xE8BD5000,
0xE169F00C,
0xE8BD5000,
0xE25EF004,
0x03007FF0,
0x09FE2000,
0x09FFC000,
0x03007FE0
};
variable_desc saveGameStruct[] = {
{ &DISPCNT, sizeof(u16) },
{ &DISPSTAT, sizeof(u16) },
{ &VCOUNT, sizeof(u16) },
{ &BG0CNT, sizeof(u16) },
{ &BG1CNT, sizeof(u16) },
{ &BG2CNT, sizeof(u16) },
{ &BG3CNT, sizeof(u16) },
{ &BG0HOFS, sizeof(u16) },
{ &BG0VOFS, sizeof(u16) },
{ &BG1HOFS, sizeof(u16) },
{ &BG1VOFS, sizeof(u16) },
{ &BG2HOFS, sizeof(u16) },
{ &BG2VOFS, sizeof(u16) },
{ &BG3HOFS, sizeof(u16) },
{ &BG3VOFS, sizeof(u16) },
{ &BG2PA, sizeof(u16) },
{ &BG2PB, sizeof(u16) },
{ &BG2PC, sizeof(u16) },
{ &BG2PD, sizeof(u16) },
{ &BG2X_L, sizeof(u16) },
{ &BG2X_H, sizeof(u16) },
{ &BG2Y_L, sizeof(u16) },
{ &BG2Y_H, sizeof(u16) },
{ &BG3PA, sizeof(u16) },
{ &BG3PB, sizeof(u16) },
{ &BG3PC, sizeof(u16) },
{ &BG3PD, sizeof(u16) },
{ &BG3X_L, sizeof(u16) },
{ &BG3X_H, sizeof(u16) },
{ &BG3Y_L, sizeof(u16) },
{ &BG3Y_H, sizeof(u16) },
{ &WIN0H, sizeof(u16) },
{ &WIN1H, sizeof(u16) },
{ &WIN0V, sizeof(u16) },
{ &WIN1V, sizeof(u16) },
{ &WININ, sizeof(u16) },
{ &WINOUT, sizeof(u16) },
{ &MOSAIC, sizeof(u16) },
{ &BLDMOD, sizeof(u16) },
{ &COLEV, sizeof(u16) },
{ &COLY, sizeof(u16) },
{ &DM0SAD_L, sizeof(u16) },
{ &DM0SAD_H, sizeof(u16) },
{ &DM0DAD_L, sizeof(u16) },
{ &DM0DAD_H, sizeof(u16) },
{ &DM0CNT_L, sizeof(u16) },
{ &DM0CNT_H, sizeof(u16) },
{ &DM1SAD_L, sizeof(u16) },
{ &DM1SAD_H, sizeof(u16) },
{ &DM1DAD_L, sizeof(u16) },
{ &DM1DAD_H, sizeof(u16) },
{ &DM1CNT_L, sizeof(u16) },
{ &DM1CNT_H, sizeof(u16) },
{ &DM2SAD_L, sizeof(u16) },
{ &DM2SAD_H, sizeof(u16) },
{ &DM2DAD_L, sizeof(u16) },
{ &DM2DAD_H, sizeof(u16) },
{ &DM2CNT_L, sizeof(u16) },
{ &DM2CNT_H, sizeof(u16) },
{ &DM3SAD_L, sizeof(u16) },
{ &DM3SAD_H, sizeof(u16) },
{ &DM3DAD_L, sizeof(u16) },
{ &DM3DAD_H, sizeof(u16) },
{ &DM3CNT_L, sizeof(u16) },
{ &DM3CNT_H, sizeof(u16) },
{ &TM0D, sizeof(u16) },
{ &TM0CNT, sizeof(u16) },
{ &TM1D, sizeof(u16) },
{ &TM1CNT, sizeof(u16) },
{ &TM2D, sizeof(u16) },
{ &TM2CNT, sizeof(u16) },
{ &TM3D, sizeof(u16) },
{ &TM3CNT, sizeof(u16) },
{ &P1, sizeof(u16) },
{ &IE, sizeof(u16) },
{ &IF, sizeof(u16) },
{ &IME, sizeof(u16) },
{ &holdState, sizeof(bool8) },
{ &holdType, sizeof(int32) },
{ &lcdTicks, sizeof(int32) },
{ &timer0On, sizeof(bool8) },
{ &timer0Ticks, sizeof(int32) },
{ &timer0Reload, sizeof(int32) },
{ &timer0ClockReload, sizeof(int32) },
{ &timer1On, sizeof(bool8) },
{ &timer1Ticks, sizeof(int32) },
{ &timer1Reload, sizeof(int32) },
{ &timer1ClockReload, sizeof(int32) },
{ &timer2On, sizeof(bool8) },
{ &timer2Ticks, sizeof(int32) },
{ &timer2Reload, sizeof(int32) },
{ &timer2ClockReload, sizeof(int32) },
{ &timer3On, sizeof(bool8) },
{ &timer3Ticks, sizeof(int32) },
{ &timer3Reload, sizeof(int32) },
{ &timer3ClockReload, sizeof(int32) },
{ &dma0Source, sizeof(u32) },
{ &dma0Dest, sizeof(u32) },
{ &dma1Source, sizeof(u32) },
{ &dma1Dest, sizeof(u32) },
{ &dma2Source, sizeof(u32) },
{ &dma2Dest, sizeof(u32) },
{ &dma3Source, sizeof(u32) },
{ &dma3Dest, sizeof(u32) },
{ &fxOn, sizeof(bool8) },
{ &windowOn, sizeof(bool8) },
{ &N_FLAG, sizeof(bool8) },
{ &C_FLAG, sizeof(bool8) },
{ &Z_FLAG, sizeof(bool8) },
{ &V_FLAG, sizeof(bool8) },
{ &armState, sizeof(bool8) },
{ &armIrqEnable, sizeof(bool8) },
{ &armNextPC, sizeof(u32) },
{ &armMode, sizeof(int32) },
{ &saveType, sizeof(int32) },
{ NULL, 0 }
};
/////////////////////////////////////////////
#ifdef PROFILING
void cpuProfil(profile_segment *seg)
{
profilSegment = seg;
}
void cpuEnableProfiling(int hz)
{
if (hz == 0)
hz = 100;
profilingTicks = profilingTicksReload = 16777216 / hz;
profSetHertz(hz);
}
#endif
inline int CPUUpdateTicks()
{
int cpuLoopTicks = lcdTicks;
if (soundTicks < cpuLoopTicks)
cpuLoopTicks = soundTicks;
if (timer0On && (timer0Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer0Ticks;
}
if (timer1On && !(TM1CNT & 4) && (timer1Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer1Ticks;
}
if (timer2On && !(TM2CNT & 4) && (timer2Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer2Ticks;
}
if (timer3On && !(TM3CNT & 4) && (timer3Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer3Ticks;
}
#ifdef PROFILING
if (profilingTicksReload != 0)
{
if (profilingTicks < cpuLoopTicks)
{
cpuLoopTicks = profilingTicks;
}
}
#endif
if (SWITicks)
{
if (SWITicks < cpuLoopTicks)
cpuLoopTicks = SWITicks;
}
if (IRQTicks)
{
if (IRQTicks < cpuLoopTicks)
cpuLoopTicks = IRQTicks;
}
return cpuLoopTicks;
}
void CPUUpdateWindow0()
{
int x00 = WIN0H >> 8;
int x01 = WIN0H & 255;
if (x00 <= x01)
{
for (int i = 0; i < 240; i++)
{
gfxInWin0[i] = (i >= x00 && i < x01);
}
}
else
{
for (int i = 0; i < 240; i++)
{
gfxInWin0[i] = (i >= x00 || i < x01);
}
}
}
void CPUUpdateWindow1()
{
int x00 = WIN1H >> 8;
int x01 = WIN1H & 255;
if (x00 <= x01)
{
for (int i = 0; i < 240; i++)
{
gfxInWin1[i] = (i >= x00 && i < x01);
}
}
else
{
for (int i = 0; i < 240; i++)
{
gfxInWin1[i] = (i >= x00 || i < x01);
}
}
}
#define CLEAR_ARRAY(a) \
{ \
u32 *array = (a); \
for (int i = 0; i < 240; i++) { \
*array++ = 0x80000000; \
} \
} \
void CPUUpdateRenderBuffers(bool force)
{
if (!(layerEnable & 0x0100) || force)
{
CLEAR_ARRAY(line0);
}
if (!(layerEnable & 0x0200) || force)
{
CLEAR_ARRAY(line1);
}
if (!(layerEnable & 0x0400) || force)
{
CLEAR_ARRAY(line2);
}
if (!(layerEnable & 0x0800) || force)
{
CLEAR_ARRAY(line3);
}
}
#undef CLEAR_ARRAY
bool CPUWriteStateToStream(gzFile gzFile)
{
utilWriteInt(gzFile, SAVE_GAME_VERSION);
utilGzWrite(gzFile, &rom[0xa0], 16);
utilWriteInt(gzFile, useBios);
utilGzWrite(gzFile, ®[0], sizeof(reg));
utilWriteData(gzFile, saveGameStruct);
// new to version 0.7.1
utilWriteInt(gzFile, stopState);
// new to version 0.8
utilWriteInt(gzFile, intState);
utilGzWrite(gzFile, internalRAM, 0x8000);
utilGzWrite(gzFile, paletteRAM, 0x400);
utilGzWrite(gzFile, workRAM, 0x40000);
utilGzWrite(gzFile, vram, 0x20000);
utilGzWrite(gzFile, oam, 0x400);
utilGzWrite(gzFile, pix, 4 * 241 * 162);
utilGzWrite(gzFile, ioMem, 0x400);
eepromSaveGame(gzFile);
flashSaveGame(gzFile);
soundSaveGame(gzFile);
cheatsSaveGame(gzFile);
// version 1.5
rtcSaveGame(gzFile);
// SAVE_GAME_VERSION_9 (new to re-recording version which is based on 1.72)
{
utilGzWrite(gzFile, &sensorX, sizeof(sensorX));
utilGzWrite(gzFile, &sensorY, sizeof(sensorY));
bool8 movieActive = VBAMovieIsActive();
utilGzWrite(gzFile, &movieActive, sizeof(movieActive));
if (movieActive)
{
uint8 *movie_freeze_buf = NULL;
uint32 movie_freeze_size = 0;
int code = VBAMovieFreeze(&movie_freeze_buf, &movie_freeze_size);
if (movie_freeze_buf)
{
utilGzWrite(gzFile, &movie_freeze_size, sizeof(movie_freeze_size));
utilGzWrite(gzFile, movie_freeze_buf, movie_freeze_size);
delete [] movie_freeze_buf;
}
else
{
if (code == MOVIE_UNRECORDED_INPUT)
{
systemMessage(0, N_("Cannot make a movie snapshot as long as there are unrecorded input changes."));
}
else
{
systemMessage(0, N_("Failed to save movie snapshot."));
}
return false;
}
}
utilGzWrite(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount));
}
// SAVE_GAME_VERSION_13
{
utilGzWrite(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount));
utilGzWrite(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged));
utilGzWrite(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast));
}
// SAVE_GAME_VERSION_14
{
utilGzWrite(gzFile, memoryWait, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWait32, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWaitSeq, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWaitSeq32, 16 * sizeof(u8));
utilGzWrite(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used...
}
return true;
}
bool CPUWriteState(const char *file)
{
gzFile gzFile = utilGzOpen(file, "wb");
if (gzFile == NULL)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"), file);
return false;
}
bool res = CPUWriteStateToStream(gzFile);
utilGzClose(gzFile);
return res;
}
bool CPUWriteMemState(char *memory, int available)
{
gzFile gzFile = utilMemGzOpen(memory, available, "w");
if (gzFile == NULL)
{
return false;
}
bool res = CPUWriteStateToStream(gzFile);
long pos = utilGzTell(gzFile) + 8;
if (pos >= (available))
res = false;
utilGzClose(gzFile);
return res;
}
bool CPUReadStateFromStream(gzFile gzFile)
{
char tempBackupName[128];
if (tempSaveSafe)
{
sprintf(tempBackupName, "gbatempsave%d.sav", tempSaveID++);
CPUWriteState(tempBackupName);
}
int version = utilReadInt(gzFile);
if (version > SAVE_GAME_VERSION || version < SAVE_GAME_VERSION_1)
{
systemMessage(MSG_UNSUPPORTED_VBA_SGM,
N_("Unsupported VisualBoyAdvance save game version %d"),
version);
goto failedLoad;
}
u8 romname[17];
utilGzRead(gzFile, romname, 16);
if (memcmp(&rom[0xa0], romname, 16) != 0)
{
romname[16] = 0;
for (int i = 0; i < 16; i++)
if (romname[i] < 32)
romname[i] = 32;
systemMessage(MSG_CANNOT_LOAD_SGM, N_("Cannot load save game for %s"), romname);
goto failedLoad;
}
bool8 ub = utilReadInt(gzFile) ? true : false;
if (ub != useBios)
{
if (useBios)
systemMessage(MSG_SAVE_GAME_NOT_USING_BIOS,
N_("Save game is not using the BIOS files"));
else
systemMessage(MSG_SAVE_GAME_USING_BIOS,
N_("Save game is using the BIOS file"));
goto failedLoad;
}
utilGzRead(gzFile, ®[0], sizeof(reg));
utilReadData(gzFile, saveGameStruct);
if (version < SAVE_GAME_VERSION_3)
stopState = false;
else
stopState = utilReadInt(gzFile) ? true : false;
if (version < SAVE_GAME_VERSION_4)
intState = false;
else
intState = utilReadInt(gzFile) ? true : false;
utilGzRead(gzFile, internalRAM, 0x8000);
utilGzRead(gzFile, paletteRAM, 0x400);
utilGzRead(gzFile, workRAM, 0x40000);
utilGzRead(gzFile, vram, 0x20000);
utilGzRead(gzFile, oam, 0x400);
if (version < SAVE_GAME_VERSION_6)
utilGzRead(gzFile, pix, 4 * 240 * 160);
else
utilGzRead(gzFile, pix, 4 * 241 * 162);
utilGzRead(gzFile, ioMem, 0x400);
if (skipSaveGameBattery)
{
// skip eeprom data
eepromReadGameSkip(gzFile, version);
// skip flash data
flashReadGameSkip(gzFile, version);
}
else
{
eepromReadGame(gzFile, version);
flashReadGame(gzFile, version);
}
soundReadGame(gzFile, version);
if (version > SAVE_GAME_VERSION_1)
{
if (skipSaveGameCheats)
{
// skip cheats list data
cheatsReadGameSkip(gzFile, version);
}
else
{
cheatsReadGame(gzFile, version);
}
}
if (version > SAVE_GAME_VERSION_6)
{
rtcReadGame(gzFile);
}
if (version <= SAVE_GAME_VERSION_7)
{
u32 temp;
#define SWAP(a, b, c) \
temp = (a); \
(a) = (b) << 16 | (c); \
(b) = (temp) >> 16; \
(c) = (temp) & 0xFFFF;
SWAP(dma0Source, DM0SAD_H, DM0SAD_L);
SWAP(dma0Dest, DM0DAD_H, DM0DAD_L);
SWAP(dma1Source, DM1SAD_H, DM1SAD_L);
SWAP(dma1Dest, DM1DAD_H, DM1DAD_L);
SWAP(dma2Source, DM2SAD_H, DM2SAD_L);
SWAP(dma2Dest, DM2DAD_H, DM2DAD_L);
SWAP(dma3Source, DM3SAD_H, DM3SAD_L);
SWAP(dma3Dest, DM3DAD_H, DM3DAD_L);
}
#undef SWAP
if (version <= SAVE_GAME_VERSION_8)
{
timer0ClockReload = TIMER_TICKS[TM0CNT & 3];
timer1ClockReload = TIMER_TICKS[TM1CNT & 3];
timer2ClockReload = TIMER_TICKS[TM2CNT & 3];
timer3ClockReload = TIMER_TICKS[TM3CNT & 3];
timer0Ticks = ((0x10000 - TM0D) << timer0ClockReload) - timer0Ticks;
timer1Ticks = ((0x10000 - TM1D) << timer1ClockReload) - timer1Ticks;
timer2Ticks = ((0x10000 - TM2D) << timer2ClockReload) - timer2Ticks;
timer3Ticks = ((0x10000 - TM3D) << timer3ClockReload) - timer3Ticks;
interp_rate();
}
// set pointers!
layerEnable = layerSettings & DISPCNT;
CPUUpdateRender();
CPUUpdateRenderBuffers(true);
CPUUpdateWindow0();
CPUUpdateWindow1();
gbaSaveType = 0;
switch (saveType)
{
case 0:
cpuSaveGameFunc = flashSaveDecide;
break;
case 1:
cpuSaveGameFunc = sramWrite;
gbaSaveType = 1;
break;
case 2:
cpuSaveGameFunc = flashWrite;
gbaSaveType = 2;
break;
case 3:
break;
case 5:
gbaSaveType = 5;
break;
default:
systemMessage(MSG_UNSUPPORTED_SAVE_TYPE,
N_("Unsupported save type %d"), saveType);
break;
}
if (eepromInUse)
gbaSaveType = 3;
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
bool wasPlayingMovie = VBAMovieIsActive() && VBAMovieIsPlaying();
if (version >= SAVE_GAME_VERSION_9) // new to re-recording version:
{
utilGzRead(gzFile, &sensorX, sizeof(sensorX));
utilGzRead(gzFile, &sensorY, sizeof(sensorY));
bool8 movieSnapshot;
utilGzRead(gzFile, &movieSnapshot, sizeof(movieSnapshot));
if (VBAMovieIsActive() && !movieSnapshot)
{
systemMessage(0, N_("Can't load a non-movie snapshot while a movie is active."));
goto failedLoad;
}
if (movieSnapshot) // even if a movie isn't active we still want to parse through this
// because we have already got stuff added in this save format
{
uint32 movieInputDataSize = 0;
utilGzRead(gzFile, &movieInputDataSize, sizeof(movieInputDataSize));
uint8 *local_movie_data = new uint8[movieInputDataSize];
int readBytes = utilGzRead(gzFile, local_movie_data, movieInputDataSize);
if (readBytes != movieInputDataSize)
{
systemMessage(0, N_("Corrupt movie snapshot."));
delete [] local_movie_data;
goto failedLoad;
}
int code = VBAMovieUnfreeze(local_movie_data, movieInputDataSize);
delete [] local_movie_data;
if (code != MOVIE_SUCCESS && VBAMovieIsActive())
{
char errStr [1024];
strcpy(errStr, "Failed to load movie snapshot");
switch (code)
{
case MOVIE_NOT_FROM_THIS_MOVIE:
strcat(errStr, ";\nSnapshot not from this movie"); break;
case MOVIE_NOT_FROM_A_MOVIE:
strcat(errStr, ";\nNot a movie snapshot"); break; // shouldn't get here...
case MOVIE_UNVERIFIABLE_POST_END:
sprintf(errStr, "%s;\nSnapshot unverifiable with movie after End Frame %u", errStr, VBAMovieGetLastErrorInfo()); break;
case MOVIE_TIMELINE_INCONSISTENT_AT:
sprintf(errStr, "%s;\nSnapshot inconsistent with movie at Frame %u", errStr, VBAMovieGetLastErrorInfo()); break;
case MOVIE_WRONG_FORMAT:
strcat(errStr, ";\nWrong format"); break;
}
strcat(errStr, ".");
systemMessage(0, N_(errStr));
goto failedLoad;
}
}
utilGzRead(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount));
}
if (version < SAVE_GAME_VERSION_14)
{
if (version >= SAVE_GAME_VERSION_10)
{
utilGzSeek(gzFile, 16 * sizeof(int32) * 6, SEEK_CUR);
}
if (version >= SAVE_GAME_VERSION_11)
{
utilGzSeek(gzFile, sizeof(bool8) * 3, SEEK_CUR);
}
if (version >= SAVE_GAME_VERSION_12)
{
utilGzSeek(gzFile, sizeof(bool8) * 2, SEEK_CUR);
}
}
if (version >= SAVE_GAME_VERSION_13)
{
utilGzRead(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount));
utilGzRead(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged));
utilGzRead(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast));
}
if (version >= SAVE_GAME_VERSION_14)
{
utilGzRead(gzFile, memoryWait, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWait32, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWaitSeq, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWaitSeq32, 16 * sizeof(u8));
utilGzRead(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used...
}
if (armState)
{
ARM_PREFETCH;
}
else
{
THUMB_PREFETCH;
}
CPUUpdateRegister(0x204, CPUReadHalfWordQuick(0x4000204));
systemSetJoypad(0, ~P1 & 0x3FF);
VBAUpdateButtonPressDisplay();
VBAUpdateFrameCountDisplay();
systemRefreshScreen();
if (tempSaveSafe)
{
remove(tempBackupName);
tempSaveAttempts = 0;
}
return true;
failedLoad:
if (tempSaveSafe)
{
tempSaveAttempts++;
if (tempSaveAttempts < 3) // fail no more than 2 times in a row
CPUReadState(tempBackupName);
remove(tempBackupName);
}
if (wasPlayingMovie && VBAMovieIsRecording())
{
VBAMovieSwitchToPlaying();
}
return false;
}
bool CPUReadMemState(char *memory, int available)
{
gzFile gzFile = utilMemGzOpen(memory, available, "r");
tempSaveSafe = false;
bool res = CPUReadStateFromStream(gzFile);
tempSaveSafe = true;
utilGzClose(gzFile);
return res;
}
bool CPUReadState(const char *file)
{
gzFile gzFile = utilGzOpen(file, "rb");
if (gzFile == NULL)
return false;
bool res = CPUReadStateFromStream(gzFile);
utilGzClose(gzFile);
return res;
}
bool CPUExportEepromFile(const char *fileName)
{
if (eepromInUse)
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"),
fileName);
return false;
}
for (int i = 0; i < eepromSize; )
{
for (int j = 0; j < 8; j++)
{
if (fwrite(&eepromData[i + 7 - j], 1, 1, file) != 1)
{
fclose(file);
return false;
}
}
i += 8;
}
fclose(file);
}
return true;
}
bool CPUWriteBatteryToStream(gzFile gzFile)
{
if (!gzFile)
return false;
utilWriteInt(gzFile, SAVE_GAME_VERSION);
// for simplicity, we put both types of battery files should be in the stream, even if one's empty
eepromSaveGame(gzFile);
flashSaveGame(gzFile);
return true;
}
bool CPUWriteBatteryFile(const char *fileName)
{
if (gbaSaveType == 0)
{
if (eepromInUse)
gbaSaveType = 3;
else
switch (saveType)
{
case 1:
gbaSaveType = 1;
break;
case 2:
gbaSaveType = 2;
break;
}
}
if ((gbaSaveType != 0) && (gbaSaveType != 5))
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"),
fileName);
return false;
}
// only save if Flash/Sram in use or EEprom in use
if (gbaSaveType != 3)
{
if (gbaSaveType == 2)
{
if (fwrite(flashSaveMemory, 1, flashSize, file) != (size_t)flashSize)
{
fclose(file);
return false;
}
}
else
{
if (fwrite(flashSaveMemory, 1, 0x10000, file) != 0x10000)
{
fclose(file);
return false;
}
}
}
else
{
if (fwrite(eepromData, 1, eepromSize, file) != (size_t)eepromSize)
{
fclose(file);
return false;
}
}
fclose(file);
}
return true;
}
bool CPUReadGSASnapshot(const char *fileName)
{
int i;
FILE *file = fopen(fileName, "rb");
if (!file)
{
systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName);
return false;
}
// check file size to know what we should read
fseek(file, 0, SEEK_END);
// long size = ftell(file);
fseek(file, 0x0, SEEK_SET);
fread(&i, 1, 4, file);
fseek(file, i, SEEK_CUR); // Skip SharkPortSave
fseek(file, 4, SEEK_CUR); // skip some sort of flag
fread(&i, 1, 4, file); // name length
fseek(file, i, SEEK_CUR); // skip name
fread(&i, 1, 4, file); // desc length
fseek(file, i, SEEK_CUR); // skip desc
fread(&i, 1, 4, file); // notes length
fseek(file, i, SEEK_CUR); // skip notes
int saveSize;
fread(&saveSize, 1, 4, file); // read length
saveSize -= 0x1c; // remove header size
char buffer[17];
char buffer2[17];
fread(buffer, 1, 16, file);
buffer[16] = 0;
for (i = 0; i < 16; i++)
if (buffer[i] < 32)
buffer[i] = 32;
memcpy(buffer2, &rom[0xa0], 16);
buffer2[16] = 0;
for (i = 0; i < 16; i++)
if (buffer2[i] < 32)
buffer2[i] = 32;
if (memcmp(buffer, buffer2, 16))
{
systemMessage(MSG_CANNOT_IMPORT_SNAPSHOT_FOR,
N_("Cannot import snapshot for %s. Current game is %s"),
buffer,
buffer2);
fclose(file);
return false;
}
fseek(file, 12, SEEK_CUR); // skip some flags
if (saveSize >= 65536)
{
if (fread(flashSaveMemory, 1, saveSize, file) != (size_t)saveSize)
{
fclose(file);
return false;
}
}
else
{
systemMessage(MSG_UNSUPPORTED_SNAPSHOT_FILE,
N_("Unsupported snapshot file %s"),
fileName);
fclose(file);
return false;
}
fclose(file);
CPUReset();
return true;
}
bool CPUWriteGSASnapshot(const char *fileName,
const char *title,
const char *desc,
const char *notes)
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName);
return false;
}
u8 buffer[17];
utilPutDword(buffer, 0x0d); // SharkPortSave length
fwrite(buffer, 1, 4, file);
fwrite("SharkPortSave", 1, 0x0d, file);
utilPutDword(buffer, 0x000f0000);
fwrite(buffer, 1, 4, file); // save type 0x000f0000 = GBA save
utilPutDword(buffer, (u32)strlen(title));
fwrite(buffer, 1, 4, file); // title length
fwrite(title, 1, strlen(title), file);
utilPutDword(buffer, (u32)strlen(desc));
fwrite(buffer, 1, 4, file); // desc length
fwrite(desc, 1, strlen(desc), file);
utilPutDword(buffer, (u32)strlen(notes));
fwrite(buffer, 1, 4, file); // notes length
fwrite(notes, 1, strlen(notes), file);
int saveSize = 0x10000;
if (gbaSaveType == 2)
saveSize = flashSize;
int totalSize = saveSize + 0x1c;
utilPutDword(buffer, totalSize); // length of remainder of save - CRC
fwrite(buffer, 1, 4, file);
char *temp = new char[0x2001c];
memset(temp, 0, 28);
memcpy(temp, &rom[0xa0], 16); // copy internal name
temp[0x10] = rom[0xbe]; // reserved area (old checksum)
temp[0x11] = rom[0xbf]; // reserved area (old checksum)
temp[0x12] = rom[0xbd]; // complement check
temp[0x13] = rom[0xb0]; // maker
temp[0x14] = 1; // 1 save ?
memcpy(&temp[0x1c], flashSaveMemory, saveSize); // copy save
fwrite(temp, 1, totalSize, file); // write save + header
u32 crc = 0;
for (int i = 0; i < totalSize; i++)
{
crc += ((u32)temp[i] << (crc % 0x18));
}
utilPutDword(buffer, crc);
fwrite(buffer, 1, 4, file); // CRC?
fclose(file);
delete [] temp;
return true;
}
bool CPUImportEepromFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (!file)
return false;
// check file size to know what we should read
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
if (size == 512 || size == 0x2000)
{
if (fread(eepromData, 1, size, file) != (size_t)size)
{
fclose(file);
return false;
}
for (int i = 0; i < size; )
{
u8 tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
i += 4;
}
}
else
{
fclose(file);
return false;
}
fclose(file);
return true;
}
bool CPUReadBatteryFromStream(gzFile gzFile)
{
if (!gzFile)
return false;
int version = utilReadInt(gzFile);
// for simplicity, we put both types of battery files should be in the stream, even if one's empty
eepromReadGame(gzFile, version);
flashReadGame(gzFile, version);
return true;
}
bool CPUReadBatteryFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (!file)
return false;
// check file size to know what we should read
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
if (size == 512 || size == 0x2000)
{
if (fread(eepromData, 1, size, file) != (size_t)size)
{
fclose(file);
return false;
}
}
else
{
if (size == 0x20000)
{
if (fread(flashSaveMemory, 1, 0x20000, file) != 0x20000)
{
fclose(file);
return false;
}
flashSetSize(0x20000);
}
else
{
if (fread(flashSaveMemory, 1, 0x10000, file) != 0x10000)
{
fclose(file);
return false;
}
flashSetSize(0x10000);
}
}
fclose(file);
return true;
}
bool CPUWritePNGFile(const char *fileName)
{
return utilWritePNGFile(fileName, 240, 160, pix);
}
bool CPUWriteBMPFile(const char *fileName)
{
return utilWriteBMPFile(fileName, 240, 160, pix);
}
void CPUCleanUp()
{
#ifdef PROFILING
if (profilingTicksReload)
{
profCleanup();
}
#endif
PIX_FREE(pix);
pix = NULL;
free(bios);
bios = NULL;
free(rom);
rom = NULL;
free(internalRAM);
internalRAM = NULL;
free(workRAM);
workRAM = NULL;
free(paletteRAM);
paletteRAM = NULL;
free(vram);
vram = NULL;
free(oam);
oam = NULL;
free(ioMem);
ioMem = NULL;
#if 0
eepromErase();
flashErase();
#endif
#ifndef NO_DEBUGGER
elfCleanUp();
#endif
systemCleanUp();
systemRefreshScreen();
}
int CPULoadRom(const char *szFile)
{
int size = 0x2000000;
if (rom != NULL)
{
CPUCleanUp();
}
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
rom = (u8 *)malloc(0x2000000);
if (rom == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"ROM");
return 0;
}
// FIXME: size+4 is so RAM search and watch are safe to read any byte in the allocated region as a 4-byte int
workRAM = (u8 *)RAM_CALLOC(0x40000);
if (workRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"WRAM");
return 0;
}
u8 *whereToLoad = cpuIsMultiBoot ? workRAM : rom;
#ifndef NO_DEBUGGER
if (utilIsELF(szFile))
{
FILE *f = fopen(szFile, "rb");
if (!f)
{
systemMessage(MSG_ERROR_OPENING_IMAGE, N_("Error opening image %s"),
szFile);
CPUCleanUp();
return 0;
}
bool res = elfRead(szFile, size, f);
if (!res || size == 0)
{
CPUCleanUp();
elfCleanUp();
return 0;
}
}
else
#endif //NO_DEBUGGER
if (szFile != NULL)
{
if (!utilLoad(szFile,
utilIsGBAImage,
whereToLoad,
size))
{
CPUCleanUp();
return 0;
}
}
u16 *temp = (u16 *)(rom + ((size + 1) & ~1));
for (int i = (size + 1) & ~1; i < 0x2000000; i += 2)
{
WRITE16LE(temp, (i >> 1) & 0xFFFF);
temp++;
}
pix = (u8 *)PIX_CALLOC(4 * 241 * 162);
if (pix == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"PIX");
CPUCleanUp();
return 0;
}
bios = (u8 *)RAM_CALLOC(0x4000);
if (bios == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"BIOS");
CPUCleanUp();
return 0;
}
internalRAM = (u8 *)RAM_CALLOC(0x8000);
if (internalRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"IRAM");
CPUCleanUp();
return 0;
}
paletteRAM = (u8 *)RAM_CALLOC(0x400);
if (paletteRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"PRAM");
CPUCleanUp();
return 0;
}
vram = (u8 *)RAM_CALLOC(0x20000);
if (vram == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"VRAM");
CPUCleanUp();
return 0;
}
oam = (u8 *)RAM_CALLOC(0x400);
if (oam == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"OAM");
CPUCleanUp();
return 0;
}
ioMem = (u8 *)RAM_CALLOC(0x400);
if (ioMem == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"IO");
CPUCleanUp();
return 0;
}
flashInit();
eepromInit();
CPUUpdateRenderBuffers(true);
romSize = size;
return size;
}
void CPUDoMirroring(bool b)
{
u32 mirroredRomSize = (((romSize) >> 20) & 0x3F) << 20;
u32 mirroredRomAddress = romSize;
if ((mirroredRomSize <= 0x800000) && (b))
{
mirroredRomAddress = mirroredRomSize;
if (mirroredRomSize == 0)
mirroredRomSize = 0x100000;
while (mirroredRomAddress < 0x01000000)
{
memcpy((u16 *)(rom + mirroredRomAddress), (u16 *)(rom), mirroredRomSize);
mirroredRomAddress += mirroredRomSize;
}
}
}
// Emulates the Cheat System (m) code
void CPUMasterCodeCheck()
{
if (cheatsEnabled)
{
if ((mastercode) && (mastercode == armNextPC))
{
u32 joy = 0;
if (systemReadJoypads())
joy = systemGetJoypad(0, cpuEEPROMSensorEnabled);
u32 ext = (joy >> 10);
cpuTotalTicks += cheatsCheckKeys(P1 ^ 0x3FF, ext);
}
}
}
void CPUUpdateRender()
{
switch (DISPCNT & 7)
{
case 0:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode0RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode0RenderLineNoWindow;
else
renderLine = mode0RenderLineAll;
break;
case 1:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode1RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode1RenderLineNoWindow;
else
renderLine = mode1RenderLineAll;
break;
case 2:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode2RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode2RenderLineNoWindow;
else
renderLine = mode2RenderLineAll;
break;
case 3:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode3RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode3RenderLineNoWindow;
else
renderLine = mode3RenderLineAll;
break;
case 4:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode4RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode4RenderLineNoWindow;
else
renderLine = mode4RenderLineAll;
break;
case 5:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode5RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode5RenderLineNoWindow;
else
renderLine = mode5RenderLineAll;
default:
break;
}
}
void CPUUpdateCPSR()
{
u32 CPSR = reg[16].I & 0x40;
if (N_FLAG)
CPSR |= 0x80000000;
if (Z_FLAG)
CPSR |= 0x40000000;
if (C_FLAG)
CPSR |= 0x20000000;
if (V_FLAG)
CPSR |= 0x10000000;
if (!armState)
CPSR |= 0x00000020;
if (!armIrqEnable)
CPSR |= 0x80;
CPSR |= (armMode & 0x1F);
reg[16].I = CPSR;
}
void CPUUpdateFlags(bool breakLoop)
{
u32 CPSR = reg[16].I;
N_FLAG = (CPSR & 0x80000000) ? true : false;
Z_FLAG = (CPSR & 0x40000000) ? true : false;
C_FLAG = (CPSR & 0x20000000) ? true : false;
V_FLAG = (CPSR & 0x10000000) ? true : false;
armState = (CPSR & 0x20) ? false : true;
armIrqEnable = (CPSR & 0x80) ? false : true;
if (breakLoop)
{
if (armIrqEnable && (IF & IE) && (IME & 1))
cpuNextEvent = cpuTotalTicks;
}
}
void CPUUpdateFlags()
{
CPUUpdateFlags(true);
}
#ifdef WORDS_BIGENDIAN
static void CPUSwap(volatile u32 *a, volatile u32 *b)
{
volatile u32 c = *b;
*b = *a;
*a = c;
}
#else
static void CPUSwap(u32 *a, u32 *b)
{
u32 c = *b;
*b = *a;
*a = c;
}
#endif
void CPUSwitchMode(int mode, bool saveState, bool breakLoop)
{
// if(armMode == mode)
// return;
CPUUpdateCPSR();
switch (armMode)
{
case 0x10:
case 0x1F:
reg[R13_USR].I = reg[13].I;
reg[R14_USR].I = reg[14].I;
reg[17].I = reg[16].I;
break;
case 0x11:
CPUSwap(®[R8_FIQ].I, ®[8].I);
CPUSwap(®[R9_FIQ].I, ®[9].I);
CPUSwap(®[R10_FIQ].I, ®[10].I);
CPUSwap(®[R11_FIQ].I, ®[11].I);
CPUSwap(®[R12_FIQ].I, ®[12].I);
reg[R13_FIQ].I = reg[13].I;
reg[R14_FIQ].I = reg[14].I;
reg[SPSR_FIQ].I = reg[17].I;
break;
case 0x12:
reg[R13_IRQ].I = reg[13].I;
reg[R14_IRQ].I = reg[14].I;
reg[SPSR_IRQ].I = reg[17].I;
break;
case 0x13:
reg[R13_SVC].I = reg[13].I;
reg[R14_SVC].I = reg[14].I;
reg[SPSR_SVC].I = reg[17].I;
break;
case 0x17:
reg[R13_ABT].I = reg[13].I;
reg[R14_ABT].I = reg[14].I;
reg[SPSR_ABT].I = reg[17].I;
break;
case 0x1b:
reg[R13_UND].I = reg[13].I;
reg[R14_UND].I = reg[14].I;
reg[SPSR_UND].I = reg[17].I;
break;
}
u32 CPSR = reg[16].I;
u32 SPSR = reg[17].I;
switch (mode)
{
case 0x10:
case 0x1F:
reg[13].I = reg[R13_USR].I;
reg[14].I = reg[R14_USR].I;
reg[16].I = SPSR;
break;
case 0x11:
CPUSwap(®[8].I, ®[R8_FIQ].I);
CPUSwap(®[9].I, ®[R9_FIQ].I);
CPUSwap(®[10].I, ®[R10_FIQ].I);
CPUSwap(®[11].I, ®[R11_FIQ].I);
CPUSwap(®[12].I, ®[R12_FIQ].I);
reg[13].I = reg[R13_FIQ].I;
reg[14].I = reg[R14_FIQ].I;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_FIQ].I;
break;
case 0x12:
reg[13].I = reg[R13_IRQ].I;
reg[14].I = reg[R14_IRQ].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_IRQ].I;
break;
case 0x13:
reg[13].I = reg[R13_SVC].I;
reg[14].I = reg[R14_SVC].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_SVC].I;
break;
case 0x17:
reg[13].I = reg[R13_ABT].I;
reg[14].I = reg[R14_ABT].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_ABT].I;
break;
case 0x1b:
reg[13].I = reg[R13_UND].I;
reg[14].I = reg[R14_UND].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_UND].I;
break;
default:
systemMessage(MSG_UNSUPPORTED_ARM_MODE, N_("Unsupported ARM mode %02x"), mode);
break;
}
armMode = mode;
CPUUpdateFlags(breakLoop);
CPUUpdateCPSR();
}
void CPUSwitchMode(int mode, bool saveState)
{
CPUSwitchMode(mode, saveState, true);
}
void CPUUndefinedException()
{
u32 PC = reg[15].I;
bool savedArmState = armState;
CPUSwitchMode(0x1b, true, false);
reg[14].I = PC - (savedArmState ? 4 : 2);
reg[15].I = 0x04;
armState = true;
armIrqEnable = false;
armNextPC = 0x04;
ARM_PREFETCH;
reg[15].I += 4;
}
void CPUSoftwareInterrupt()
{
u32 PC = reg[15].I;
bool savedArmState = armState;
CPUSwitchMode(0x13, true, false);
reg[14].I = PC - (savedArmState ? 4 : 2);
reg[15].I = 0x08;
armState = true;
armIrqEnable = false;
armNextPC = 0x08;
ARM_PREFETCH;
reg[15].I += 4;
}
void CPUSoftwareInterrupt(int comment)
{
static bool disableMessage = false;
if (armState)
comment >>= 16;
#ifdef BKPT_SUPPORT
if (comment == 0xff)
{
dbgOutput(NULL, reg[0].I);
return;
}
#endif
#ifdef PROFILING
if (comment == 0xfe)
{
profStartup(reg[0].I, reg[1].I);
return;
}
if (comment == 0xfd)
{
profControl(reg[0].I);
return;
}
if (comment == 0xfc)
{
profCleanup();
return;
}
if (comment == 0xfb)
{
profCount();
return;
}
#endif
if (comment == 0xfa)
{
agbPrintFlush();
return;
}
#ifdef SDL
if (comment == 0xf9)
{
emulating = 0;
cpuNextEvent = cpuTotalTicks;
cpuBreakLoop = true;
return;
}
#endif
if (useBios)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment,
armState ? armNextPC - 4 : armNextPC - 2,
reg[0].I,
reg[1].I,
reg[2].I,
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
return;
}
// This would be correct, but it causes problems if uncommented
// else {
// biosProtected = 0xe3a02004;
// }
switch (comment)
{
case 0x00:
BIOS_SoftReset();
ARM_PREFETCH;
break;
case 0x01:
BIOS_RegisterRamReset();
break;
case 0x02:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("Halt: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
holdState = true;
holdType = -1;
cpuNextEvent = cpuTotalTicks;
break;
case 0x03:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("Stop: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
holdState = true;
holdType = -1;
stopState = true;
cpuNextEvent = cpuTotalTicks;
break;
case 0x04:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("IntrWait: 0x%08x,0x%08x (VCOUNT = %2d)\n",
reg[0].I,
reg[1].I,
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
break;
case 0x05:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("VBlankIntrWait: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
break;
case 0x06:
CPUSoftwareInterrupt();
break;
case 0x07:
CPUSoftwareInterrupt();
break;
case 0x08:
BIOS_Sqrt();
break;
case 0x09:
BIOS_ArcTan();
break;
case 0x0A:
BIOS_ArcTan2();
break;
case 0x0B:
{
int len = (reg[2].I & 0x1FFFFF) >> 1;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
{
if ((reg[2].I >> 24) & 1)
{
if ((reg[2].I >> 26) & 1)
SWITicks = (7 + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1);
else
SWITicks = (8 + memoryWait[(reg[1].I >> 24) & 0xF]) * (len);
}
else
{
if ((reg[2].I >> 26) & 1)
SWITicks = (10 + memoryWait32[(reg[0].I >> 24) & 0xF] +
memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1);
else
SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
}
}
BIOS_CpuSet();
break;
case 0x0C:
{
int len = (reg[2].I & 0x1FFFFF) >> 5;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
{
if ((reg[2].I >> 24) & 1)
SWITicks = (6 + memoryWait32[(reg[1].I >> 24) & 0xF] +
7 * (memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 1)) * len;
else
SWITicks = (9 + memoryWait32[(reg[0].I >> 24) & 0xF] +
memoryWait32[(reg[1].I >> 24) & 0xF] +
7 * (memoryWaitSeq32[(reg[0].I >> 24) & 0xF] +
memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 2)) * len;
}
}
BIOS_CpuFastSet();
break;
case 0x0D:
BIOS_GetBiosChecksum();
break;
case 0x0E:
BIOS_BgAffineSet();
break;
case 0x0F:
BIOS_ObjAffineSet();
break;
case 0x10:
{
int len = CPUReadHalfWord(reg[2].I);
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
SWITicks = (32 + memoryWait[(reg[0].I >> 24) & 0xF]) * len;
}
BIOS_BitUnPack();
break;
case 0x11:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (9 + memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_LZ77UnCompWram();
break;
case 0x12:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (19 + memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_LZ77UnCompVram();
break;
case 0x13:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (29 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1)) * len;
}
BIOS_HuffUnComp();
break;
case 0x14:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_RLUnCompWram();
break;
case 0x15:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (34 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_RLUnCompVram();
break;
case 0x16:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff8bitUnFilterWram();
break;
case 0x17:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (39 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff8bitUnFilterVram();
break;
case 0x18:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff16bitUnFilter();
break;
case 0x19:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SoundBiasSet: 0x%08x (VCOUNT = %2d)\n",
reg[0].I,
VCOUNT);
}
#endif
if (reg[0].I)
systemSoundPause();
else
systemSoundResume();
break;
case 0x1F:
BIOS_MidiKey2Freq();
break;
case 0x2A:
BIOS_SndDriverJmpTableCopy();
// let it go, because we don't really emulate this function // FIXME (?)
default:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment,
armState ? armNextPC - 4 : armNextPC - 2,
reg[0].I,
reg[1].I,
reg[2].I,
VCOUNT);
}
#endif
if (!disableMessage)
{
systemMessage(MSG_UNSUPPORTED_BIOS_FUNCTION,
N_("Unsupported BIOS function %02x called from %08x. A BIOS file is needed in order to get correct behaviour."),
comment,
armMode ? armNextPC - 4 : armNextPC - 2);
disableMessage = true;
}
break;
}
}
void CPUCompareVCOUNT()
{
if (VCOUNT == (DISPSTAT >> 8))
{
DISPSTAT |= 4;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 0x20)
{
IF |= 4;
UPDATE_REG(0x202, IF);
}
}
else
{
DISPSTAT &= 0xFFFB;
UPDATE_REG(0x4, DISPSTAT);
}
if (layerEnableDelay > 0)
{
--layerEnableDelay;
if (layerEnableDelay == 1)
layerEnable = layerSettings & DISPCNT;
}
}
static void doDMA(u32 &s, u32 &d, u32 si, u32 di, u32 c, int transfer32)
{
int sm = s >> 24;
int dm = d >> 24;
int sw = 0;
int dw = 0;
int sc = c;
cpuDmaCount = c;
// This is done to get the correct waitstates.
if (sm > 15)
sm = 15;
if (dm > 15)
dm = 15;
//if ((sm>=0x05) && (sm<=0x07) || (dm>=0x05) && (dm <=0x07))
// blank = (((DISPSTAT | ((DISPSTAT>>1)&1))==1) ? true : false);
if (transfer32)
{
s &= 0xFFFFFFFC;
if (s < 0x02000000 && (reg[15].I >> 24))
{
while (c != 0)
{
CPUWriteMemory(d, 0);
d += di;
c--;
}
}
else
{
while (c != 0)
{
cpuDmaLast = CPUReadMemory(s);
CPUWriteMemory(d, cpuDmaLast);
d += di;
s += si;
c--;
}
}
}
else
{
s &= 0xFFFFFFFE;
si = (int)si >> 1;
di = (int)di >> 1;
if (s < 0x02000000 && (reg[15].I >> 24))
{
while (c != 0)
{
CPUWriteHalfWord(d, 0);
d += di;
c--;
}
}
else
{
while (c != 0)
{
cpuDmaLast = CPUReadHalfWord(s);
CPUWriteHalfWord(d, cpuDmaLast);
cpuDmaLast |= (cpuDmaLast << 16);
d += di;
s += si;
c--;
}
}
}
cpuDmaCount = 0;
int totalTicks = 0;
if (transfer32)
{
sw = 1 + memoryWaitSeq32[sm & 15];
dw = 1 + memoryWaitSeq32[dm & 15];
totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait32[sm & 15] +
memoryWaitSeq32[dm & 15];
}
else
{
sw = 1 + memoryWaitSeq[sm & 15];
dw = 1 + memoryWaitSeq[dm & 15];
totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait[sm & 15] +
memoryWaitSeq[dm & 15];
}
cpuDmaTicksToUpdate += totalTicks;
}
void CPUCheckDMA(int reason, int dmamask)
{
// DMA 0
if ((DM0CNT_H & 0x8000) && (dmamask & 1))
{
if (((DM0CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM0CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM0CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA0)
{
int count = (DM0CNT_L ? DM0CNT_L : 0x4000) << 1;
if (DM0CNT_H & 0x0400)
count <<= 1;
log("DMA0: s=%08x d=%08x c=%04x count=%08x\n", dma0Source, dma0Dest,
DM0CNT_H,
count);
}
#endif
doDMA(dma0Source, dma0Dest, sourceIncrement, destIncrement,
DM0CNT_L ? DM0CNT_L : 0x4000,
DM0CNT_H & 0x0400);
cpuDmaHack = true;
if (DM0CNT_H & 0x4000)
{
IF |= 0x0100;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM0CNT_H >> 5) & 3) == 3)
{
dma0Dest = DM0DAD_L | (DM0DAD_H << 16);
}
if (!(DM0CNT_H & 0x0200) || (reason == 0))
{
DM0CNT_H &= 0x7FFF;
UPDATE_REG(0xBA, DM0CNT_H);
}
}
}
// DMA 1
if ((DM1CNT_H & 0x8000) && (dmamask & 2))
{
if (((DM1CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM1CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM1CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
if (reason == 3)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA1)
{
log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest,
DM1CNT_H,
16);
}
#endif
doDMA(dma1Source, dma1Dest, sourceIncrement, 0, 4,
0x0400);
}
else
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA1)
{
int count = (DM1CNT_L ? DM1CNT_L : 0x4000) << 1;
if (DM1CNT_H & 0x0400)
count <<= 1;
log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest,
DM1CNT_H,
count);
}
#endif
doDMA(dma1Source, dma1Dest, sourceIncrement, destIncrement,
DM1CNT_L ? DM1CNT_L : 0x4000,
DM1CNT_H & 0x0400);
}
cpuDmaHack = true;
if (DM1CNT_H & 0x4000)
{
IF |= 0x0200;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM1CNT_H >> 5) & 3) == 3)
{
dma1Dest = DM1DAD_L | (DM1DAD_H << 16);
}
if (!(DM1CNT_H & 0x0200) || (reason == 0))
{
DM1CNT_H &= 0x7FFF;
UPDATE_REG(0xC6, DM1CNT_H);
}
}
}
// DMA 2
if ((DM2CNT_H & 0x8000) && (dmamask & 4))
{
if (((DM2CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM2CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM2CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
if (reason == 3)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA2)
{
int count = (4) << 2;
log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest,
DM2CNT_H,
count);
}
#endif
doDMA(dma2Source, dma2Dest, sourceIncrement, 0, 4,
0x0400);
}
else
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA2)
{
int count = (DM2CNT_L ? DM2CNT_L : 0x4000) << 1;
if (DM2CNT_H & 0x0400)
count <<= 1;
log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest,
DM2CNT_H,
count);
}
#endif
doDMA(dma2Source, dma2Dest, sourceIncrement, destIncrement,
DM2CNT_L ? DM2CNT_L : 0x4000,
DM2CNT_H & 0x0400);
}
cpuDmaHack = true;
if (DM2CNT_H & 0x4000)
{
IF |= 0x0400;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM2CNT_H >> 5) & 3) == 3)
{
dma2Dest = DM2DAD_L | (DM2DAD_H << 16);
}
if (!(DM2CNT_H & 0x0200) || (reason == 0))
{
DM2CNT_H &= 0x7FFF;
UPDATE_REG(0xD2, DM2CNT_H);
}
}
}
// DMA 3
if ((DM3CNT_H & 0x8000) && (dmamask & 8))
{
if (((DM3CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM3CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM3CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA3)
{
int count = (DM3CNT_L ? DM3CNT_L : 0x10000) << 1;
if (DM3CNT_H & 0x0400)
count <<= 1;
log("DMA3: s=%08x d=%08x c=%04x count=%08x\n", dma3Source, dma3Dest,
DM3CNT_H,
count);
}
#endif
doDMA(dma3Source, dma3Dest, sourceIncrement, destIncrement,
DM3CNT_L ? DM3CNT_L : 0x10000,
DM3CNT_H & 0x0400);
if (DM3CNT_H & 0x4000)
{
IF |= 0x0800;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM3CNT_H >> 5) & 3) == 3)
{
dma3Dest = DM3DAD_L | (DM3DAD_H << 16);
}
if (!(DM3CNT_H & 0x0200) || (reason == 0))
{
DM3CNT_H &= 0x7FFF;
UPDATE_REG(0xDE, DM3CNT_H);
}
}
}
}
void CPUUpdateRegister(u32 address, u16 value)
{
switch (address)
{
case 0x00:
{
if ((value & 7) > 5)
{
// display modes above 0-5 are prohibited
DISPCNT = (value & 7);
}
bool change = (0 != ((DISPCNT ^ value) & 0x80));
bool changeBG = (0 != ((DISPCNT ^ value) & 0x0F00));
u16 changeBGon = ((~DISPCNT) & value) & 0x0F00; // these layers are being activated
DISPCNT = (value & 0xFFF7); // bit 3 can only be accessed by the BIOS to enable GBC mode
UPDATE_REG(0x00, DISPCNT);
if (changeBGon)
{
layerEnableDelay = 4;
layerEnable = layerSettings & value & (~changeBGon);
}
else
{
layerEnable = layerSettings & value;
// CPUUpdateTicks(); // what does this do?
}
windowOn = (layerEnable & 0x6000) ? true : false;
if (change && !((value & 0x80)))
{
if (!(DISPSTAT & 1))
{
lcdTicks = 1008;
// VCOUNT = 0;
// UPDATE_REG(0x06, VCOUNT);
DISPSTAT &= 0xFFFC;
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
// (*renderLine)();
}
CPUUpdateRender();
// we only care about changes in BG0-BG3
if (changeBG)
{
CPUUpdateRenderBuffers(false);
}
break;
}
case 0x04:
DISPSTAT = (value & 0xFF38) | (DISPSTAT & 7);
UPDATE_REG(0x04, DISPSTAT);
break;
case 0x06:
// not writable
break;
case 0x08:
BG0CNT = (value & 0xDFCF);
UPDATE_REG(0x08, BG0CNT);
break;
case 0x0A:
BG1CNT = (value & 0xDFCF);
UPDATE_REG(0x0A, BG1CNT);
break;
case 0x0C:
BG2CNT = (value & 0xFFCF);
UPDATE_REG(0x0C, BG2CNT);
break;
case 0x0E:
BG3CNT = (value & 0xFFCF);
UPDATE_REG(0x0E, BG3CNT);
break;
case 0x10:
BG0HOFS = value & 511;
UPDATE_REG(0x10, BG0HOFS);
break;
case 0x12:
BG0VOFS = value & 511;
UPDATE_REG(0x12, BG0VOFS);
break;
case 0x14:
BG1HOFS = value & 511;
UPDATE_REG(0x14, BG1HOFS);
break;
case 0x16:
BG1VOFS = value & 511;
UPDATE_REG(0x16, BG1VOFS);
break;
case 0x18:
BG2HOFS = value & 511;
UPDATE_REG(0x18, BG2HOFS);
break;
case 0x1A:
BG2VOFS = value & 511;
UPDATE_REG(0x1A, BG2VOFS);
break;
case 0x1C:
BG3HOFS = value & 511;
UPDATE_REG(0x1C, BG3HOFS);
break;
case 0x1E:
BG3VOFS = value & 511;
UPDATE_REG(0x1E, BG3VOFS);
break;
case 0x20:
BG2PA = value;
UPDATE_REG(0x20, BG2PA);
break;
case 0x22:
BG2PB = value;
UPDATE_REG(0x22, BG2PB);
break;
case 0x24:
BG2PC = value;
UPDATE_REG(0x24, BG2PC);
break;
case 0x26:
BG2PD = value;
UPDATE_REG(0x26, BG2PD);
break;
case 0x28:
BG2X_L = value;
UPDATE_REG(0x28, BG2X_L);
gfxBG2Changed |= 1;
break;
case 0x2A:
BG2X_H = (value & 0xFFF);
UPDATE_REG(0x2A, BG2X_H);<|fim▁hole|> gfxBG2Changed |= 1;
break;
case 0x2C:
BG2Y_L = value;
UPDATE_REG(0x2C, BG2Y_L);
gfxBG2Changed |= 2;
break;
case 0x2E:
BG2Y_H = value & 0xFFF;
UPDATE_REG(0x2E, BG2Y_H);
gfxBG2Changed |= 2;
break;
case 0x30:
BG3PA = value;
UPDATE_REG(0x30, BG3PA);
break;
case 0x32:
BG3PB = value;
UPDATE_REG(0x32, BG3PB);
break;
case 0x34:
BG3PC = value;
UPDATE_REG(0x34, BG3PC);
break;
case 0x36:
BG3PD = value;
UPDATE_REG(0x36, BG3PD);
break;
case 0x38:
BG3X_L = value;
UPDATE_REG(0x38, BG3X_L);
gfxBG3Changed |= 1;
break;
case 0x3A:
BG3X_H = value & 0xFFF;
UPDATE_REG(0x3A, BG3X_H);
gfxBG3Changed |= 1;
break;
case 0x3C:
BG3Y_L = value;
UPDATE_REG(0x3C, BG3Y_L);
gfxBG3Changed |= 2;
break;
case 0x3E:
BG3Y_H = value & 0xFFF;
UPDATE_REG(0x3E, BG3Y_H);
gfxBG3Changed |= 2;
break;
case 0x40:
WIN0H = value;
UPDATE_REG(0x40, WIN0H);
CPUUpdateWindow0();
break;
case 0x42:
WIN1H = value;
UPDATE_REG(0x42, WIN1H);
CPUUpdateWindow1();
break;
case 0x44:
WIN0V = value;
UPDATE_REG(0x44, WIN0V);
break;
case 0x46:
WIN1V = value;
UPDATE_REG(0x46, WIN1V);
break;
case 0x48:
WININ = value & 0x3F3F;
UPDATE_REG(0x48, WININ);
break;
case 0x4A:
WINOUT = value & 0x3F3F;
UPDATE_REG(0x4A, WINOUT);
break;
case 0x4C:
MOSAIC = value;
UPDATE_REG(0x4C, MOSAIC);
break;
case 0x50:
BLDMOD = value & 0x3FFF;
UPDATE_REG(0x50, BLDMOD);
fxOn = ((BLDMOD >> 6) & 3) != 0;
CPUUpdateRender();
break;
case 0x52:
COLEV = value & 0x1F1F;
UPDATE_REG(0x52, COLEV);
break;
case 0x54:
COLY = value & 0x1F;
UPDATE_REG(0x54, COLY);
break;
case 0x60:
case 0x62:
case 0x64:
case 0x68:
case 0x6c:
case 0x70:
case 0x72:
case 0x74:
case 0x78:
case 0x7c:
case 0x80:
case 0x84:
soundEvent(address & 0xFF, (u8)(value & 0xFF));
soundEvent((address & 0xFF) + 1, (u8)(value >> 8));
break;
case 0x82:
case 0x88:
case 0xa0:
case 0xa2:
case 0xa4:
case 0xa6:
case 0x90:
case 0x92:
case 0x94:
case 0x96:
case 0x98:
case 0x9a:
case 0x9c:
case 0x9e:
soundEvent(address & 0xFF, value);
break;
case 0xB0:
DM0SAD_L = value;
UPDATE_REG(0xB0, DM0SAD_L);
break;
case 0xB2:
DM0SAD_H = value & 0x07FF;
UPDATE_REG(0xB2, DM0SAD_H);
break;
case 0xB4:
DM0DAD_L = value;
UPDATE_REG(0xB4, DM0DAD_L);
break;
case 0xB6:
DM0DAD_H = value & 0x07FF;
UPDATE_REG(0xB6, DM0DAD_H);
break;
case 0xB8:
DM0CNT_L = value & 0x3FFF;
UPDATE_REG(0xB8, 0);
break;
case 0xBA:
{
bool start = ((DM0CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM0CNT_H = value;
UPDATE_REG(0xBA, DM0CNT_H);
if (start && (value & 0x8000))
{
dma0Source = DM0SAD_L | (DM0SAD_H << 16);
dma0Dest = DM0DAD_L | (DM0DAD_H << 16);
CPUCheckDMA(0, 1);
}
break;
}
case 0xBC:
DM1SAD_L = value;
UPDATE_REG(0xBC, DM1SAD_L);
break;
case 0xBE:
DM1SAD_H = value & 0x0FFF;
UPDATE_REG(0xBE, DM1SAD_H);
break;
case 0xC0:
DM1DAD_L = value;
UPDATE_REG(0xC0, DM1DAD_L);
break;
case 0xC2:
DM1DAD_H = value & 0x07FF;
UPDATE_REG(0xC2, DM1DAD_H);
break;
case 0xC4:
DM1CNT_L = value & 0x3FFF;
UPDATE_REG(0xC4, 0);
break;
case 0xC6:
{
bool start = ((DM1CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM1CNT_H = value;
UPDATE_REG(0xC6, DM1CNT_H);
if (start && (value & 0x8000))
{
dma1Source = DM1SAD_L | (DM1SAD_H << 16);
dma1Dest = DM1DAD_L | (DM1DAD_H << 16);
CPUCheckDMA(0, 2);
}
break;
}
case 0xC8:
DM2SAD_L = value;
UPDATE_REG(0xC8, DM2SAD_L);
break;
case 0xCA:
DM2SAD_H = value & 0x0FFF;
UPDATE_REG(0xCA, DM2SAD_H);
break;
case 0xCC:
DM2DAD_L = value;
UPDATE_REG(0xCC, DM2DAD_L);
break;
case 0xCE:
DM2DAD_H = value & 0x07FF;
UPDATE_REG(0xCE, DM2DAD_H);
break;
case 0xD0:
DM2CNT_L = value & 0x3FFF;
UPDATE_REG(0xD0, 0);
break;
case 0xD2:
{
bool start = ((DM2CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM2CNT_H = value;
UPDATE_REG(0xD2, DM2CNT_H);
if (start && (value & 0x8000))
{
dma2Source = DM2SAD_L | (DM2SAD_H << 16);
dma2Dest = DM2DAD_L | (DM2DAD_H << 16);
CPUCheckDMA(0, 4);
}
break;
}
case 0xD4:
DM3SAD_L = value;
UPDATE_REG(0xD4, DM3SAD_L);
break;
case 0xD6:
DM3SAD_H = value & 0x0FFF;
UPDATE_REG(0xD6, DM3SAD_H);
break;
case 0xD8:
DM3DAD_L = value;
UPDATE_REG(0xD8, DM3DAD_L);
break;
case 0xDA:
DM3DAD_H = value & 0x0FFF;
UPDATE_REG(0xDA, DM3DAD_H);
break;
case 0xDC:
DM3CNT_L = value;
UPDATE_REG(0xDC, 0);
break;
case 0xDE:
{
bool start = ((DM3CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xFFE0;
DM3CNT_H = value;
UPDATE_REG(0xDE, DM3CNT_H);
if (start && (value & 0x8000))
{
dma3Source = DM3SAD_L | (DM3SAD_H << 16);
dma3Dest = DM3DAD_L | (DM3DAD_H << 16);
CPUCheckDMA(0, 8);
}
break;
}
case 0x100:
timer0Reload = value;
interp_rate();
break;
case 0x102:
timer0Value = value;
timerOnOffDelay |= 1;
cpuNextEvent = cpuTotalTicks;
break;
case 0x104:
timer1Reload = value;
interp_rate();
break;
case 0x106:
timer1Value = value;
timerOnOffDelay |= 2;
cpuNextEvent = cpuTotalTicks;
break;
case 0x108:
timer2Reload = value;
break;
case 0x10A:
timer2Value = value;
timerOnOffDelay |= 4;
cpuNextEvent = cpuTotalTicks;
break;
case 0x10C:
timer3Reload = value;
break;
case 0x10E:
timer3Value = value;
timerOnOffDelay |= 8;
cpuNextEvent = cpuTotalTicks;
break;
case 0x128:
if (value & 0x80)
{
value &= 0xff7f;
if (value & 1 && (value & 0x4000))
{
UPDATE_REG(0x12a, 0xFF);
IF |= 0x80;
UPDATE_REG(0x202, IF);
value &= 0x7f7f;
}
}
UPDATE_REG(0x128, value);
break;
case 0x130:
P1 |= (value & 0x3FF);
UPDATE_REG(0x130, P1);
break;
case 0x132:
UPDATE_REG(0x132, value & 0xC3FF);
break;
case 0x200:
IE = value & 0x3FFF;
UPDATE_REG(0x200, IE);
if ((IME & 1) && (IF & IE) && armIrqEnable)
cpuNextEvent = cpuTotalTicks;
break;
case 0x202:
IF ^= (value & IF);
UPDATE_REG(0x202, IF);
break;
case 0x204:
{
memoryWait[0x0e] = memoryWaitSeq[0x0e] = gamepakRamWaitState[value & 3];
if (!speedHack)
{
memoryWait[0x08] = memoryWait[0x09] = gamepakWaitState[(value >> 2) & 3];
memoryWaitSeq[0x08] = memoryWaitSeq[0x09] =
gamepakWaitState0[(value >> 4) & 1];
memoryWait[0x0a] = memoryWait[0x0b] = gamepakWaitState[(value >> 5) & 3];
memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] =
gamepakWaitState1[(value >> 7) & 1];
memoryWait[0x0c] = memoryWait[0x0d] = gamepakWaitState[(value >> 8) & 3];
memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] =
gamepakWaitState2[(value >> 10) & 1];
}
else
{
memoryWait[0x08] = memoryWait[0x09] = 3;
memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = 1;
memoryWait[0x0a] = memoryWait[0x0b] = 3;
memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = 1;
memoryWait[0x0c] = memoryWait[0x0d] = 3;
memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = 1;
}
for (int i = 8; i < 15; i++)
{
memoryWait32[i] = memoryWait[i] + memoryWaitSeq[i] + 1;
memoryWaitSeq32[i] = memoryWaitSeq[i] * 2 + 1;
}
if ((value & 0x4000) == 0x4000)
{
busPrefetchEnable = true;
busPrefetch = false;
busPrefetchCount = 0;
}
else
{
busPrefetchEnable = false;
busPrefetch = false;
busPrefetchCount = 0;
}
UPDATE_REG(0x204, value & 0x7FFF);
}
break;
case 0x208:
IME = value & 1;
UPDATE_REG(0x208, IME);
if ((IME & 1) && (IF & IE) && armIrqEnable)
cpuNextEvent = cpuTotalTicks;
break;
case 0x300:
if (value != 0)
value &= 0xFFFE;
UPDATE_REG(0x300, value);
break;
default:
UPDATE_REG(address & 0x3FE, value);
break;
}
}
void applyTimer()
{
if (timerOnOffDelay & 1)
{
timer0ClockReload = TIMER_TICKS[timer0Value & 3];
if (!timer0On && (timer0Value & 0x80))
{
// reload the counter
TM0D = timer0Reload;
timer0Ticks = (0x10000 - TM0D) << timer0ClockReload;
UPDATE_REG(0x100, TM0D);
}
timer0On = timer0Value & 0x80 ? true : false;
TM0CNT = timer0Value & 0xC7;
interp_rate();
UPDATE_REG(0x102, TM0CNT);
// CPUUpdateTicks();
}
if (timerOnOffDelay & 2)
{
timer1ClockReload = TIMER_TICKS[timer1Value & 3];
if (!timer1On && (timer1Value & 0x80))
{
// reload the counter
TM1D = timer1Reload;
timer1Ticks = (0x10000 - TM1D) << timer1ClockReload;
UPDATE_REG(0x104, TM1D);
}
timer1On = timer1Value & 0x80 ? true : false;
TM1CNT = timer1Value & 0xC7;
interp_rate();
UPDATE_REG(0x106, TM1CNT);
}
if (timerOnOffDelay & 4)
{
timer2ClockReload = TIMER_TICKS[timer2Value & 3];
if (!timer2On && (timer2Value & 0x80))
{
// reload the counter
TM2D = timer2Reload;
timer2Ticks = (0x10000 - TM2D) << timer2ClockReload;
UPDATE_REG(0x108, TM2D);
}
timer2On = timer2Value & 0x80 ? true : false;
TM2CNT = timer2Value & 0xC7;
UPDATE_REG(0x10A, TM2CNT);
}
if (timerOnOffDelay & 8)
{
timer3ClockReload = TIMER_TICKS[timer3Value & 3];
if (!timer3On && (timer3Value & 0x80))
{
// reload the counter
TM3D = timer3Reload;
timer3Ticks = (0x10000 - TM3D) << timer3ClockReload;
UPDATE_REG(0x10C, TM3D);
}
timer3On = timer3Value & 0x80 ? true : false;
TM3CNT = timer3Value & 0xC7;
UPDATE_REG(0x10E, TM3CNT);
}
cpuNextEvent = CPUUpdateTicks();
timerOnOffDelay = 0;
}
void CPULoadInternalBios()
{
// load internal BIOS
#ifdef WORDS_BIGENDIAN
for (size_t i = 0; i < sizeof(myROM) / 4; ++i)
{
WRITE32LE(&bios[i], myROM[i]);
}
#else
memcpy(bios, myROM, sizeof(myROM));
#endif
}
void CPUInit()
{
biosProtected[0] = 0x00;
biosProtected[1] = 0xf0;
biosProtected[2] = 0x29;
biosProtected[3] = 0xe1;
int i = 0;
for (i = 0; i < 256; i++)
{
int cpuBitSetCount = 0;
int j;
for (j = 0; j < 8; j++)
if (i & (1 << j))
cpuBitSetCount++;
cpuBitsSet[i] = cpuBitSetCount;
for (j = 0; j < 8; j++)
if (i & (1 << j))
break;
cpuLowestBitSet[i] = j;
}
for (i = 0; i < 0x400; i++)
ioReadable[i] = true;
for (i = 0x10; i < 0x48; i++)
ioReadable[i] = false;
for (i = 0x4c; i < 0x50; i++)
ioReadable[i] = false;
for (i = 0x54; i < 0x60; i++)
ioReadable[i] = false;
for (i = 0x8c; i < 0x90; i++)
ioReadable[i] = false;
for (i = 0xa0; i < 0xb8; i++)
ioReadable[i] = false;
for (i = 0xbc; i < 0xc4; i++)
ioReadable[i] = false;
for (i = 0xc8; i < 0xd0; i++)
ioReadable[i] = false;
for (i = 0xd4; i < 0xdc; i++)
ioReadable[i] = false;
for (i = 0xe0; i < 0x100; i++)
ioReadable[i] = false;
for (i = 0x110; i < 0x120; i++)
ioReadable[i] = false;
for (i = 0x12c; i < 0x130; i++)
ioReadable[i] = false;
for (i = 0x138; i < 0x140; i++)
ioReadable[i] = false;
for (i = 0x144; i < 0x150; i++)
ioReadable[i] = false;
for (i = 0x15c; i < 0x200; i++)
ioReadable[i] = false;
for (i = 0x20c; i < 0x300; i++)
ioReadable[i] = false;
for (i = 0x304; i < 0x400; i++)
ioReadable[i] = false;
if (romSize < 0x1fe2000)
{
*((u16 *)&rom[0x1fe209c]) = 0xdffa; // SWI 0xFA
*((u16 *)&rom[0x1fe209e]) = 0x4770; // BX LR
}
else
{
agbPrintEnable(false);
}
gbaSaveType = 0;
eepromInUse = 0;
saveType = 0;
}
void CPUReset()
{
systemReset();
if (gbaSaveType == 0)
{
if (eepromInUse)
gbaSaveType = 3;
else
switch (saveType)
{
case 1:
gbaSaveType = 1;
break;
case 2:
gbaSaveType = 2;
break;
}
}
// clean picture
memset(pix, 0, 4 * 241 * 162);
// clean registers
memset(®[0], 0, sizeof(reg));
// clean OAM
memset(oam, 0, 0x400);
// clean palette
memset(paletteRAM, 0, 0x400);
// clean vram
memset(vram, 0, 0x20000);
// clean io memory
memset(ioMem, 0, 0x400);
DISPCNT = 0x0080;
DISPSTAT = 0x0000;
VCOUNT = (useBios && !skipBios) ? 0 : 0x007E;
BG0CNT = 0x0000;
BG1CNT = 0x0000;
BG2CNT = 0x0000;
BG3CNT = 0x0000;
BG0HOFS = 0x0000;
BG0VOFS = 0x0000;
BG1HOFS = 0x0000;
BG1VOFS = 0x0000;
BG2HOFS = 0x0000;
BG2VOFS = 0x0000;
BG3HOFS = 0x0000;
BG3VOFS = 0x0000;
BG2PA = 0x0100;
BG2PB = 0x0000;
BG2PC = 0x0000;
BG2PD = 0x0100;
BG2X_L = 0x0000;
BG2X_H = 0x0000;
BG2Y_L = 0x0000;
BG2Y_H = 0x0000;
BG3PA = 0x0100;
BG3PB = 0x0000;
BG3PC = 0x0000;
BG3PD = 0x0100;
BG3X_L = 0x0000;
BG3X_H = 0x0000;
BG3Y_L = 0x0000;
BG3Y_H = 0x0000;
WIN0H = 0x0000;
WIN1H = 0x0000;
WIN0V = 0x0000;
WIN1V = 0x0000;
WININ = 0x0000;
WINOUT = 0x0000;
MOSAIC = 0x0000;
BLDMOD = 0x0000;
COLEV = 0x0000;
COLY = 0x0000;
DM0SAD_L = 0x0000;
DM0SAD_H = 0x0000;
DM0DAD_L = 0x0000;
DM0DAD_H = 0x0000;
DM0CNT_L = 0x0000;
DM0CNT_H = 0x0000;
DM1SAD_L = 0x0000;
DM1SAD_H = 0x0000;
DM1DAD_L = 0x0000;
DM1DAD_H = 0x0000;
DM1CNT_L = 0x0000;
DM1CNT_H = 0x0000;
DM2SAD_L = 0x0000;
DM2SAD_H = 0x0000;
DM2DAD_L = 0x0000;
DM2DAD_H = 0x0000;
DM2CNT_L = 0x0000;
DM2CNT_H = 0x0000;
DM3SAD_L = 0x0000;
DM3SAD_H = 0x0000;
DM3DAD_L = 0x0000;
DM3DAD_H = 0x0000;
DM3CNT_L = 0x0000;
DM3CNT_H = 0x0000;
TM0D = 0x0000;
TM0CNT = 0x0000;
TM1D = 0x0000;
TM1CNT = 0x0000;
TM2D = 0x0000;
TM2CNT = 0x0000;
TM3D = 0x0000;
TM3CNT = 0x0000;
P1 = 0x03FF;
IE = 0x0000;
IF = 0x0000;
IME = 0x0000;
armMode = 0x1F;
armState = true;
if (cpuIsMultiBoot)
{
reg[13].I = 0x03007F00;
reg[15].I = 0x02000000;
reg[16].I = 0x00000000;
reg[R13_IRQ].I = 0x03007FA0;
reg[R13_SVC].I = 0x03007FE0;
armIrqEnable = true;
}
else
{
if (useBios && !skipBios)
{
reg[15].I = 0x00000000;
armMode = 0x13;
armIrqEnable = false;
}
else
{
reg[13].I = 0x03007F00;
reg[15].I = 0x08000000;
reg[16].I = 0x00000000;
reg[R13_IRQ].I = 0x03007FA0;
reg[R13_SVC].I = 0x03007FE0;
armIrqEnable = true;
}
}
C_FLAG = V_FLAG = N_FLAG = Z_FLAG = false;
UPDATE_REG(0x00, DISPCNT);
UPDATE_REG(0x06, VCOUNT);
UPDATE_REG(0x20, BG2PA);
UPDATE_REG(0x26, BG2PD);
UPDATE_REG(0x30, BG3PA);
UPDATE_REG(0x36, BG3PD);
UPDATE_REG(0x130, P1);
UPDATE_REG(0x88, 0x200);
// disable FIQ
reg[16].I |= 0x40;
CPUUpdateCPSR();
armNextPC = reg[15].I;
reg[15].I += 4;
// reset internal state
intState = false;
stopState = false;
holdState = false;
holdType = 0;
biosProtected[0] = 0x00;
biosProtected[1] = 0xf0;
biosProtected[2] = 0x29;
biosProtected[3] = 0xe1;
lcdTicks = (useBios && !skipBios) ? 1008 : 208;
timer0On = false;
timer0Ticks = 0;
timer0Reload = 0;
timer0ClockReload = 0;
timer1On = false;
timer1Ticks = 0;
timer1Reload = 0;
timer1ClockReload = 0;
timer2On = false;
timer2Ticks = 0;
timer2Reload = 0;
timer2ClockReload = 0;
timer3On = false;
timer3Ticks = 0;
timer3Reload = 0;
timer3ClockReload = 0;
dma0Source = 0;
dma0Dest = 0;
dma1Source = 0;
dma1Dest = 0;
dma2Source = 0;
dma2Dest = 0;
dma3Source = 0;
dma3Dest = 0;
cpuSaveGameFunc = flashSaveDecide;
renderLine = mode0RenderLine;
fxOn = false;
windowOn = false;
saveType = 0;
layerEnable = DISPCNT & layerSettings;
CPUUpdateRenderBuffers(true);
for (int i = 0; i < 256; i++)
{
memoryMap[i].address = (u8 *)&dummyAddress;
memoryMap[i].mask = 0;
}
memoryMap[0].address = bios;
memoryMap[0].mask = 0x3FFF;
memoryMap[2].address = workRAM;
memoryMap[2].mask = 0x3FFFF;
memoryMap[3].address = internalRAM;
memoryMap[3].mask = 0x7FFF;
memoryMap[4].address = ioMem;
memoryMap[4].mask = 0x3FF;
memoryMap[5].address = paletteRAM;
memoryMap[5].mask = 0x3FF;
memoryMap[6].address = vram;
memoryMap[6].mask = 0x1FFFF;
memoryMap[7].address = oam;
memoryMap[7].mask = 0x3FF;
memoryMap[8].address = rom;
memoryMap[8].mask = 0x1FFFFFF;
memoryMap[9].address = rom;
memoryMap[9].mask = 0x1FFFFFF;
memoryMap[10].address = rom;
memoryMap[10].mask = 0x1FFFFFF;
memoryMap[12].address = rom;
memoryMap[12].mask = 0x1FFFFFF;
memoryMap[14].address = flashSaveMemory;
memoryMap[14].mask = 0xFFFF;
eepromReset();
flashReset();
rtcReset();
CPUUpdateWindow0();
CPUUpdateWindow1();
// make sure registers are correctly initialized if not using BIOS
if (!useBios)
{
if (cpuIsMultiBoot)
BIOS_RegisterRamReset(0xfe);
else
BIOS_RegisterRamReset(0xff);
}
else
{
if (cpuIsMultiBoot)
BIOS_RegisterRamReset(0xfe);
}
switch (cpuSaveType)
{
case 0: // automatic
cpuSramEnabled = true;
cpuFlashEnabled = true;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = false;
saveType = gbaSaveType = 0;
break;
case 1: // EEPROM
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = false;
saveType = gbaSaveType = 3;
// EEPROM usage is automatically detected
break;
case 2: // SRAM
cpuSramEnabled = true;
cpuFlashEnabled = false;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
cpuSaveGameFunc = sramDelayedWrite; // to insure we detect the write
saveType = gbaSaveType = 1;
break;
case 3: // FLASH
cpuSramEnabled = false;
cpuFlashEnabled = true;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
cpuSaveGameFunc = flashDelayedWrite; // to insure we detect the write
saveType = gbaSaveType = 2;
break;
case 4: // EEPROM+Sensor
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = true;
// EEPROM usage is automatically detected
saveType = gbaSaveType = 3;
break;
case 5: // NONE
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
// no save at all
saveType = gbaSaveType = 5;
break;
}
ARM_PREFETCH;
cpuDmaHack = false;
SWITicks = 0;
IRQTicks = 0;
soundReset();
systemRefreshScreen();
}
void CPUInterrupt()
{
u32 PC = reg[15].I;
bool savedState = armState;
CPUSwitchMode(0x12, true, false);
reg[14].I = PC;
if (!savedState)
reg[14].I += 2;
reg[15].I = 0x18;
armState = true;
armIrqEnable = false;
armNextPC = reg[15].I;
reg[15].I += 4;
ARM_PREFETCH;
// if(!holdState)
biosProtected[0] = 0x02;
biosProtected[1] = 0xc0;
biosProtected[2] = 0x5e;
biosProtected[3] = 0xe5;
}
static inline void CPUDrawPixLine()
{
switch (systemColorDepth)
{
case 16:
{
u16 *dest = (u16 *)pix + 241 * (VCOUNT + 1);
for (int x = 0; x < 240; )
{
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
}
// for filters that read past the screen
*dest++ = 0;
break;
}
case 24:
{
u8 *dest = (u8 *)pix + 240 * VCOUNT * 3;
for (int x = 0; x < 240; )
{
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
}
break;
}
case 32:
{
u32 *dest = (u32 *)pix + 241 * (VCOUNT + 1);
for (int x = 0; x < 240; )
{
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
}
break;
}
}
}
static inline u32 CPUGetUserInput()
{
// update joystick information
systemReadJoypads();
u32 joy = systemGetJoypad(0, cpuEEPROMSensorEnabled);
P1 = 0x03FF ^ (joy & 0x3FF);
UPDATE_REG(0x130, P1);
// HACK: some special "buttons"
extButtons = (joy >> 18);
speedup = (extButtons & 1) != 0;
return joy;
}
static inline void CPUBeforeEmulation()
{
if (newFrame)
{
CallRegisteredLuaFunctions(LUACALL_BEFOREEMULATION);
u32 joy = CPUGetUserInput();
// this seems wrong, but there are cases where the game
// can enter the stop state without requesting an IRQ from
// the joypad.
// FIXME: where is the right place???
u16 P1CNT = READ16LE(((u16 *)&ioMem[0x132]));
if ((P1CNT & 0x4000) || stopState)
{
u16 p1 = (0x3FF ^ P1) & 0x3FF;
if (P1CNT & 0x8000)
{
if (p1 == (P1CNT & 0x3FF))
{
IF |= 0x1000;
UPDATE_REG(0x202, IF);
}
}
else
{
if (p1 & P1CNT)
{
IF |= 0x1000;
UPDATE_REG(0x202, IF);
}
}
}
//if (cpuEEPROMSensorEnabled)
//systemUpdateMotionSensor(0);
VBAMovieResetIfRequested();
newFrame = false;
}
}
static inline void CPUFrameBoundaryWork()
{
// HACK: some special "buttons"
if (cheatsEnabled)
cheatsCheckKeys(P1 ^ 0x3FF, extButtons);
systemFrameBoundaryWork();
}
void CPULoop(int _ticks)
{
CPUBeforeEmulation();
int32 ticks = _ticks;
int32 clockTicks;
int32 timerOverflow = 0;
bool newVideoFrame = false;
// variable used by the CPU core
cpuTotalTicks = 0;
cpuNextEvent = CPUUpdateTicks();
if (cpuNextEvent > ticks)
cpuNextEvent = ticks;
#ifdef SDL
cpuBreakLoop = false;
#endif
for (;;)
{
#ifndef FINAL_VERSION
if (systemDebug)
{
if (systemDebug >= 10 && !holdState)
{
CPUUpdateCPSR();
#ifdef BKPT_SUPPORT
if (debugger_last)
{
sprintf(
buffer,
"R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n",
oldreg[0],
oldreg[1],
oldreg[2],
oldreg[3],
oldreg[4],
oldreg[5],
oldreg[6],
oldreg[7],
oldreg[8],
oldreg[9],
oldreg[10],
oldreg[11],
oldreg[12],
oldreg[13],
oldreg[14],
oldreg[15],
oldreg[16],
oldreg[17]);
}
#endif
sprintf(
buffer,
"R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x"
"R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n",
reg[0].I,
reg[1].I,
reg[2].I,
reg[3].I,
reg[4].I,
reg[5].I,
reg[6].I,
reg[7].I,
reg[8].I,
reg[9].I,
reg[10].I,
reg[11].I,
reg[12].I,
reg[13].I,
reg[14].I,
reg[15].I,
reg[16].I,
reg[17].I);
log(buffer);
}
else if (!holdState)
{
log("PC=%08x\n", armNextPC);
}
}
#endif /* FINAL_VERSION */
if (!holdState && !SWITicks)
{
if (armState)
{
if (!armExecute())
return;
}
else
{
if (!thumbExecute())
return;
}
clockTicks = 0;
}
else
clockTicks = CPUUpdateTicks();
cpuTotalTicks += clockTicks;
if (cpuTotalTicks >= cpuNextEvent)
{
int32 remainingTicks = cpuTotalTicks - cpuNextEvent;
if (SWITicks)
{
SWITicks -= clockTicks;
if (SWITicks < 0)
SWITicks = 0;
}
clockTicks = cpuNextEvent;
cpuTotalTicks = 0;
cpuDmaHack = false;
updateLoop:
if (IRQTicks)
{
IRQTicks -= clockTicks;
if (IRQTicks < 0)
IRQTicks = 0;
}
lcdTicks -= clockTicks;
if (lcdTicks <= 0)
{
if (DISPSTAT & 1) // V-BLANK
{ // if in V-Blank mode, keep computing...
if (DISPSTAT & 2)
{
lcdTicks += 1008;
VCOUNT++;
UPDATE_REG(0x06, VCOUNT);
DISPSTAT &= 0xFFFD;
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
else
{
lcdTicks += 224;
DISPSTAT |= 2;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 16)
{
IF |= 2;
UPDATE_REG(0x202, IF);
}
}
if (VCOUNT >= 228) //Reaching last line
{
DISPSTAT &= 0xFFFC;
UPDATE_REG(0x04, DISPSTAT);
VCOUNT = 0;
UPDATE_REG(0x06, VCOUNT);
CPUCompareVCOUNT();
}
}
else
{
if (DISPSTAT & 2)
{
// if in H-Blank, leave it and move to drawing mode
VCOUNT++;
UPDATE_REG(0x06, VCOUNT);
lcdTicks += 1008;
DISPSTAT &= 0xFFFD;
if (VCOUNT == 160)
{
DISPSTAT |= 1;
DISPSTAT &= 0xFFFD;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 0x0008)
{
IF |= 1;
UPDATE_REG(0x202, IF);
}
CPUCheckDMA(1, 0x0f);
newVideoFrame = true;
}
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
else
{
if (systemFrameDrawingRequired())
{
(*renderLine)();
CPUDrawPixLine();
}
// entering H-Blank
DISPSTAT |= 2;
UPDATE_REG(0x04, DISPSTAT);
lcdTicks += 224;
CPUCheckDMA(2, 0x0f);
if (DISPSTAT & 16)
{
IF |= 2;
UPDATE_REG(0x202, IF);
}
}
}
}
// we shouldn't be doing sound in stop state, but we lose synchronization
// if sound is disabled, so in stop state, soundTick will just produce
// mute sound
soundTicks -= clockTicks;
if (soundTicks <= 0)
{
soundTick();
soundTicks += soundTickStep;
}
if (!stopState)
{
if (timer0On)
{
timer0Ticks -= clockTicks;
if (timer0Ticks <= 0)
{
timer0Ticks += (0x10000 - timer0Reload) << timer0ClockReload;
timerOverflow |= 1;
soundTimerOverflow(0);
if (TM0CNT & 0x40)
{
IF |= 0x08;
UPDATE_REG(0x202, IF);
}
}
TM0D = 0xFFFF - (timer0Ticks >> timer0ClockReload) & 0xFFFF;
UPDATE_REG(0x100, TM0D);
}
if (timer1On)
{
if (TM1CNT & 4)
{
if (timerOverflow & 1)
{
TM1D++;
if (TM1D == 0)
{
TM1D += timer1Reload;
timerOverflow |= 2;
soundTimerOverflow(1);
if (TM1CNT & 0x40)
{
IF |= 0x10;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x104, TM1D);
}
}
else
{
timer1Ticks -= clockTicks;
if (timer1Ticks <= 0)
{
timer1Ticks += (0x10000 - timer1Reload) << timer1ClockReload;
timerOverflow |= 2;
soundTimerOverflow(1);
if (TM1CNT & 0x40)
{
IF |= 0x10;
UPDATE_REG(0x202, IF);
}
}
TM1D = 0xFFFF - (timer1Ticks >> timer1ClockReload) & 0xFFFF;
UPDATE_REG(0x104, TM1D);
}
}
if (timer2On)
{
if (TM2CNT & 4)
{
if (timerOverflow & 2)
{
TM2D++;
if (TM2D == 0)
{
TM2D += timer2Reload;
timerOverflow |= 4;
if (TM2CNT & 0x40)
{
IF |= 0x20;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x108, TM2D);
}
}
else
{
timer2Ticks -= clockTicks;
if (timer2Ticks <= 0)
{
timer2Ticks += (0x10000 - timer2Reload) << timer2ClockReload;
timerOverflow |= 4;
if (TM2CNT & 0x40)
{
IF |= 0x20;
UPDATE_REG(0x202, IF);
}
}
TM2D = 0xFFFF - (timer2Ticks >> timer2ClockReload) & 0xFFFF;
UPDATE_REG(0x108, TM2D);
}
}
if (timer3On)
{
if (TM3CNT & 4)
{
if (timerOverflow & 4)
{
TM3D++;
if (TM3D == 0)
{
TM3D += timer3Reload;
if (TM3CNT & 0x40)
{
IF |= 0x40;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x10C, TM3D);
}
}
else
{
timer3Ticks -= clockTicks;
if (timer3Ticks <= 0)
{
timer3Ticks += (0x10000 - timer3Reload) << timer3ClockReload;
if (TM3CNT & 0x40)
{
IF |= 0x40;
UPDATE_REG(0x202, IF);
}
}
TM3D = 0xFFFF - (timer3Ticks >> timer3ClockReload) & 0xFFFF;
UPDATE_REG(0x10C, TM3D);
}
}
}
timerOverflow = 0;
#ifdef PROFILING
profilingTicks -= clockTicks;
if (profilingTicks <= 0)
{
profilingTicks += profilingTicksReload;
if (profilSegment)
{
profile_segment *seg = profilSegment;
do
{
u16 *b = (u16 *)seg->sbuf;
int pc = ((reg[15].I - seg->s_lowpc) * seg->s_scale) / 0x10000;
if (pc >= 0 && pc < seg->ssiz)
{
b[pc]++;
break;
}
seg = seg->next;
}
while (seg);
}
}
#endif
if (newVideoFrame)
{
newVideoFrame = false;
CPUFrameBoundaryWork();
}
ticks -= clockTicks;
cpuNextEvent = CPUUpdateTicks();
if (cpuDmaTicksToUpdate > 0)
{
if (cpuDmaTicksToUpdate > cpuNextEvent)
clockTicks = cpuNextEvent;
else
clockTicks = cpuDmaTicksToUpdate;
cpuDmaTicksToUpdate -= clockTicks;
cpuDmaHack = true;
goto updateLoop; // this is evil
}
if (IF && (IME & 1) && armIrqEnable)
{
int res = IF & IE;
if (stopState)
res &= 0x3080;
if (res)
{
if (intState)
{
if (!IRQTicks)
{
CPUInterrupt();
intState = false;
holdState = false;
stopState = false;
holdType = 0;
}
}
else
{
if (!holdState)
{
intState = true;
IRQTicks = 7;
if (cpuNextEvent > IRQTicks)
cpuNextEvent = IRQTicks;
}
else
{
CPUInterrupt();
holdState = false;
stopState = false;
holdType = 0;
}
}
// Stops the SWI Ticks emulation if an IRQ is executed
//(to avoid problems with nested IRQ/SWI)
if (SWITicks)
SWITicks = 0;
}
}
if (remainingTicks > 0)
{
if (remainingTicks > cpuNextEvent)
clockTicks = cpuNextEvent;
else
clockTicks = remainingTicks;
remainingTicks -= clockTicks;
goto updateLoop; // this is evil, too
}
if (timerOnOffDelay)
applyTimer();
//if (cpuNextEvent > ticks) // FIXME: can be negative and slow down
// cpuNextEvent = ticks;
#ifdef SDL
if (newFrame || useOldFrameTiming && ticks <= 0 || cpuBreakLoop)
#else
if (newFrame || useOldFrameTiming && ticks <= 0)
#endif
{
break;
}
}
}
}
struct EmulatedSystem GBASystem =
{
// emuMain
CPULoop,
// emuReset
CPUReset,
// emuCleanUp
CPUCleanUp,
// emuReadBattery
CPUReadBatteryFile,
// emuWriteBattery
CPUWriteBatteryFile,
// emuReadBatteryFromStream
CPUReadBatteryFromStream,
// emuWriteBatteryToStream
CPUWriteBatteryToStream,
// emuReadState
CPUReadState,
// emuWriteState
CPUWriteState,
// emuReadStateFromStream
CPUReadStateFromStream,
// emuWriteStateToStream
CPUWriteStateToStream,
// emuReadMemState
CPUReadMemState,
// emuWriteMemState
CPUWriteMemState,
// emuWritePNG
CPUWritePNGFile,
// emuWriteBMP
CPUWriteBMPFile,
// emuUpdateCPSR
CPUUpdateCPSR,
// emuHasDebugger
true,
// emuCount
#ifdef FINAL_VERSION
250000,
#else
5000,
#endif
};<|fim▁end|> | |
<|file_name|>sandbox_stats_beam.go<|end_file_name|><|fim▁begin|>// Code generated by soracom-cli generate-cmd. DO NOT EDIT.
package cmd
import (
"github.com/spf13/cobra"
)<|fim▁hole|>func init() {
SandboxStatsCmd.AddCommand(SandboxStatsBeamCmd)
}
// SandboxStatsBeamCmd defines 'beam' subcommand
var SandboxStatsBeamCmd = &cobra.Command{
Use: "beam",
Short: TRCLI("cli.sandbox.stats.beam.summary"),
Long: TRCLI(`cli.sandbox.stats.beam.description`),
}<|fim▁end|> | |
<|file_name|>doc.rs<|end_file_name|><|fim▁begin|>use std::cell::{RefCell, UnsafeCell};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fmt::{Display, Error, Formatter};
use std::rc::Rc;
use super::parser::{Builder, ParserError, ShowType};
pub struct ContainerData {
direct_children_vec: Vec<(Key, Rc<DirectChild>)>,
direct_children_map: HashMap<String, Rc<DirectChild>>,
indirect_children: HashMap<String, Rc<Container>>
}
impl ContainerData {
fn new() -> ContainerData {
ContainerData {
direct_children_vec: Vec::new(),
direct_children_map: HashMap::new(),
indirect_children: HashMap::new()
}
}
fn print(&self, buf: &mut String) {
}
}
enum ContainerKind {
Root,
Table,
Array,
}
struct Container {
kind: ContainerKind,
data: ContainerData,
lead: String
}
impl Container {
fn new(k: ContainerKind, s: String) -> Container {
Container {
kind: k,
data: ContainerData::new(),
lead: s
}
}
fn print(&self, buf: &mut String) {
buf.push_str(&*self.lead);
match self.kind {
ContainerKind::Table => buf.push_str("["),
ContainerKind::Array => buf.push_str("[["),
ContainerKind::Root => {}
}
self.data.print(buf);
match self.kind {
ContainerKind::Table => buf.push_str("]"),
ContainerKind::Array => buf.push_str("]]"),
ContainerKind::Root => {}
}
}
}
enum DirectChild {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
Datetime(String),
Array(Vec<ArrayElement>),
InlineTable(Container),
}
enum ArrayElement {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
Datetime(String),
Array(Vec<ArrayElement>),
}
#[derive(PartialEq, Eq, Hash)]
pub struct Key {
text: String,
lead: String,
trail: String
}
impl Display for Key {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
unimplemented!()
}
}
impl ShowType for () {
fn type_str(&self) -> &'static str {
unimplemented!()
}
}
struct DocBuilder;
impl Builder for DocBuilder {
type Table = Container;
type Array = Container;
type Key = Key;
type Value = ();
fn root_table(lead_ws: &str) -> Self::Table { Container::new(ContainerKind::Root, lead_ws.to_string()) }
fn table(lead_ws: &str) -> Self::Table { Container::new(ContainerKind::Table, lead_ws.to_string()) }
fn array(vals: Vec<Self::Value>, lead_ws: &str) -> Self::Array { unimplemented!() }
fn key(val: String, lead_ws: &str) -> Self::Key { unimplemented!()}
fn value_string(parsed: String, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn value_integer(parsed: i64, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn value_float(parsed: f64, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn value_boolean(parsed: bool, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn value_datetime(parsed: String, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn value_array(parsed: Self::Array, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn value_table(parsed: Self::Table, raw: &str, lead_ws: &str) -> Self::Value { unimplemented!() }
fn insert(table: &mut Self::Table, key: Self::Key, v: Self::Value) -> bool {
unimplemented!()
}
fn insert_container<'b>(mut cur: &'b mut Self::Table, keys: &[String],
key_lo: usize, key_hi: usize)
-> Result<&'b mut Self::Table, ParserError> {
unimplemented!()
}
fn get_table<'b>(t: &'b mut Self::Table, key: &'b str) -> Option<&'b mut Self::Table> {
unimplemented!()
}
fn get_array<'b>(t: &'b mut Self::Table, key: &'b str) -> Option<&'b mut Self::Array> { unimplemented!() }
fn contains_table(t: &Self::Table) -> bool {
unimplemented!()
}
fn merge(table: &mut Self::Table, value: Self::Table) -> Result<(), String> {
unimplemented!()
}
fn push<'b>(vec: &'b mut Self::Array, value: Self::Value) -> Result<(), &'b str> { unimplemented!() }
fn set_trailing_aux(table: &mut Self::Table, aux: &str) {
unimplemented!()
}
}
#[cfg(test)]
mod test {
use super::DocBuilder;
use super::super::parser::ParseSession;
macro_rules! round_trip {
($text: expr) => ({
let mut p = ParseSession::new($text, DocBuilder);
let table = p.parse().unwrap();
let mut buf = String::new();
table.print(&mut buf);
println!("\"{}\"", buf);
assert!($text == buf);
})
}
#[test]
fn empty() { round_trip!(" #asd \n ") }
#[test]
fn single_table() { round_trip!(" #asd\t \n [a] \t \n\n #asdasdad\n ") }
<|fim▁hole|><|fim▁end|> |
} |
<|file_name|>test_ops.py<|end_file_name|><|fim▁begin|># encoding: utf-8
from __future__ import unicode_literals
import operator
import pytest
from marrow.mongo import Filter
from marrow.schema.compat import odict, py3
@pytest.fixture
def empty_ops(request):
return Filter()
@pytest.fixture
def single_ops(request):
return Filter({'roll': 27})
<|fim▁hole|>class TestOpsMapping(object):
def test_getitem(self, empty_ops, single_ops):
with pytest.raises(KeyError):
empty_ops['roll']
assert single_ops['roll'] == 27
def test_setitem(self, empty_ops):
assert repr(empty_ops) == "Filter([])"
empty_ops['meaning'] = 42
if py3:
assert repr(empty_ops) == "Filter([('meaning', 42)])"
else:
assert repr(empty_ops) == "Filter([(u'meaning', 42)])"
def test_delitem(self, empty_ops, single_ops):
with pytest.raises(KeyError):
del empty_ops['roll']
if py3:
assert repr(single_ops) == "Filter([('roll', 27)])"
else:
assert repr(single_ops) == "Filter([(u'roll', 27)])"
del single_ops['roll']
assert repr(single_ops) == "Filter([])"
def test_length(self, empty_ops, single_ops):
assert len(empty_ops) == 0
assert len(single_ops) == 1
def test_keys(self, empty_ops, single_ops):
assert list(empty_ops.keys()) == []
assert list(single_ops.keys()) == ['roll']
def test_items(self, empty_ops, single_ops):
assert list(empty_ops.items()) == []
assert list(single_ops.items()) == [('roll', 27)]
def test_values(self, empty_ops, single_ops):
assert list(empty_ops.values()) == []
assert list(single_ops.values()) == [27]
def test_contains(self, single_ops):
assert 'foo' not in single_ops
assert 'roll' in single_ops
def test_equality_inequality(self, empty_ops, single_ops):
assert empty_ops == {}
assert empty_ops != {'roll': 27}
assert single_ops != {}
assert single_ops == {'roll': 27}
def test_get(self, single_ops):
assert single_ops.get('foo') is None
assert single_ops.get('foo', 42) == 42
assert single_ops.get('roll') == 27
def test_clear(self, single_ops):
assert len(single_ops.operations) == 1
single_ops.clear()
assert len(single_ops.operations) == 0
def test_pop(self, single_ops):
assert len(single_ops.operations) == 1
with pytest.raises(KeyError):
single_ops.pop('foo')
assert single_ops.pop('foo', 42) == 42
assert len(single_ops.operations) == 1
assert single_ops.pop('roll') == 27
assert len(single_ops.operations) == 0
def test_popitem(self, single_ops):
assert len(single_ops.operations) == 1
assert single_ops.popitem() == ('roll', 27)
assert len(single_ops.operations) == 0
with pytest.raises(KeyError):
single_ops.popitem()
def test_update(self, empty_ops, single_ops):
assert len(empty_ops.operations) == 0
empty_ops.update(name="Bob Dole")
assert len(empty_ops.operations) == 1
if py3:
assert repr(empty_ops) == "Filter([('name', 'Bob Dole')])"
else:
assert repr(empty_ops) == "Filter([('name', u'Bob Dole')])"
assert len(single_ops.operations) == 1
if py3:
assert repr(single_ops) == "Filter([('roll', 27)])"
else:
assert repr(single_ops) == "Filter([(u'roll', 27)])"
single_ops.update([('name', "Bob Dole")])
assert len(single_ops.operations) == 2
if py3:
assert repr(single_ops) in ("Filter([('roll', 27), ('name', 'Bob Dole')])", "Filter([('name', 'Bob Dole'), ('roll', 27)])")
else:
assert repr(single_ops) in ("Filter([(u'roll', 27), (u'name', u'Bob Dole')])", "Filter([(u'name', u'Bob Dole'), (u'roll', 27)])")
def test_setdefault(self, empty_ops):
assert len(empty_ops.operations) == 0
empty_ops.setdefault('fnord', 42)
assert len(empty_ops.operations) == 1
assert empty_ops.operations['fnord'] == 42
empty_ops.setdefault('fnord', 27)
assert len(empty_ops.operations) == 1
assert empty_ops.operations['fnord'] == 42
def test_ops_shallow_copy(self, single_ops):
assert single_ops.operations == single_ops.copy().operations
class TestOperationsCombination(object):
def test_operations_and_clean_merge(self):
comb = Filter({'roll': 27}) & Filter({'foo': 42})
assert comb.as_query == {'roll': 27, 'foo': 42}
def test_operations_and_operator_overlap(self):
comb = Filter({'roll': {'$gte': 27}}) & Filter({'roll': {'$lte': 42}})
assert comb.as_query == {'roll': {'$gte': 27, '$lte': 42}}
def test_paradoxical_condition(self):
comb = Filter({'roll': 27}) & Filter({'roll': {'$lte': 42}})
assert comb.as_query == {'roll': {'$eq': 27, '$lte': 42}}
comb = Filter({'roll': {'$gte': 27}}) & Filter({'roll': 42})
assert list(comb.as_query['roll'].items()) in ([('$gte', 27), ('$eq', 42)], [('$eq', 42), ('$gte', 27)])
def test_operations_or_clean_merge(self):
comb = Filter({'roll': 27}) | Filter({'foo': 42})
assert comb.as_query == {'$or': [{'roll': 27}, {'foo': 42}]}
comb = comb | Filter({'bar': 'baz'})
assert comb.as_query == {'$or': [{'roll': 27}, {'foo': 42}, {'bar': 'baz'}]}
def test_operations_hard_and(self):
comb = Filter({'$and': [{'a': 1}, {'b': 2}]}) & Filter({'$and': [{'c': 3}]})
assert comb.as_query == {'$and': [{'a': 1}, {'b': 2}, {'c': 3}]}
def test_operations_soft_and(self):
comb = Filter({'$and': [{'a': 1}, {'b': 2}]}) & Filter({'c': 3})
assert comb.as_query == {'$and': [{'a': 1}, {'b': 2}], 'c': 3}<|fim▁end|> | def test_ops_iteration(single_ops):
assert list(iter(single_ops)) == ['roll']
|
<|file_name|>MotionTracker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
'''
This SimpleCV example uses a technique called frame differencing to determine
if motion has occured. You take an initial image, then another, subtract
the difference, what is left over is what has changed between those two images
this are typically blobs on the images, so we do a blob search to count
the number of blobs and if they exist then motion has occured
'''
from __future__ import print_function
import sys, time, socket
from SimpleCV import *
cam = Camera() #setup the camera
#settings for the project
min_size = 0.1*cam.getProperty("width")*cam.getProperty("height") #make the threshold adapatable for various camera sizes
thresh = 10 # frame diff threshold
show_message_for = 2 # the amount of seconds to show the motion detected message
motion_timestamp = int(time.time())
message_text = "Motion detected"
draw_message = False
lastImg = cam.getImage()
lastImg.show()
while True:
newImg = cam.getImage()
trackImg = newImg - lastImg # diff the images
blobs = trackImg.findBlobs() #use adapative blob detection<|fim▁hole|> motion_timestamp = now
draw_message = True
#See if the time has exceeded to display the message
if (now - motion_timestamp) > show_message_for:
draw_message = False
#Draw the message on the screen
if(draw_message):
newImg.drawText(message_text, 5,5)
print(message_text)
lastImg = newImg # update the image
newImg.show()<|fim▁end|> | now = int(time.time())
#If blobs are found then motion has occured
if blobs: |
<|file_name|>array.ts<|end_file_name|><|fim▁begin|>import { DataEntity, get, set } from '@terascope/utils';
import { PostProcessConfig, InputOutputCardinality } from '../../../interfaces';
import TransformOpBase from './base';<|fim▁hole|> private fields!: string[];
static cardinality: InputOutputCardinality = 'many-to-one';
constructor(config: PostProcessConfig) {
super(config);
}
// source work differently here so we do not use the inherited validate
protected validateConfig(config: PostProcessConfig): void {
const { target: tField } = config;
const fields = config.fields || config.sources;
if (!tField || typeof tField !== 'string' || tField.length === 0) {
const { name } = this.constructor;
throw new Error(
`could not find target for ${name} validation or it is improperly formatted, config: ${JSON.stringify(config)}`
);
}
if (!fields || !Array.isArray(fields) || fields.length === 0) {
throw new Error(`array creation configuration is misconfigured, could not determine fields to join ${JSON.stringify(config)}`);
}
this.fields = fields;
this.target = tField;
}
run(doc: DataEntity): DataEntity {
const results: any[] = [];
this.fields.forEach((field) => {
const data = get(doc, field);
if (data !== undefined) {
if (Array.isArray(data)) {
results.push(...data);
} else {
results.push(data);
}
}
});
if (results.length > 0) set(doc, this.target, results);
return doc;
}
}<|fim▁end|> |
export default class MakeArray extends TransformOpBase { |
<|file_name|>Bar.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Animated,
Easing,
View,
} from 'react-native';
const INDETERMINATE_WIDTH_FACTOR = 0.3;
const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR);
export default class ProgressBar extends Component {
static propTypes = {
animated: PropTypes.bool,
borderColor: PropTypes.string,
borderRadius: PropTypes.number,
borderWidth: PropTypes.number,
children: PropTypes.node,
color: PropTypes.string,
height: PropTypes.number,
indeterminate: PropTypes.bool,
progress: PropTypes.number,
style: View.propTypes.style,
unfilledColor: PropTypes.string,
width: PropTypes.number,
};
static defaultProps = {
animated: true,
borderRadius: 4,
borderWidth: 1,
color: 'rgba(0, 122, 255, 1)',
height: 6,
indeterminate: false,
progress: 0,
width: 150,
};
constructor(props) {
super(props);
const progress = Math.min(Math.max(props.progress, 0), 1);
this.state = {
progress: new Animated.Value(props.indeterminate ? INDETERMINATE_WIDTH_FACTOR : progress),
animationValue: new Animated.Value(BAR_WIDTH_ZERO_POSITION),
};
}
componentDidMount() {
if (this.props.indeterminate) {
this.animate();
}
}
componentWillReceiveProps(props) {
if (props.indeterminate !== this.props.indeterminate) {
if (props.indeterminate) {
this.animate();
} else {
Animated.spring(this.state.animationValue, {
toValue: BAR_WIDTH_ZERO_POSITION,
}).start();
}
}
if (
props.indeterminate !== this.props.indeterminate ||
props.progress !== this.props.progress
) {
const progress = (props.indeterminate
? INDETERMINATE_WIDTH_FACTOR
: Math.min(Math.max(props.progress, 0), 1)
);
if (props.animated) {
Animated.spring(this.state.progress, {
toValue: progress,
bounciness: 0,
}).start();
} else {
this.state.progress.setValue(progress);
}
}
}
animate() {
this.state.animationValue.setValue(0);
Animated.timing(this.state.animationValue, {
toValue: 1,
duration: 1000,<|fim▁hole|> this.animate();
}
});
}
render() {
const {
borderColor,
borderRadius,
borderWidth,
children,
color,
height,
style,
unfilledColor,
width,
...restProps
} = this.props;
const innerWidth = width - (borderWidth * 2);
const containerStyle = {
width,
borderWidth,
borderColor: borderColor || color,
borderRadius,
overflow: 'hidden',
backgroundColor: unfilledColor,
};
const progressStyle = {
backgroundColor: color,
height,
width: innerWidth,
transform: [{
translateX: this.state.animationValue.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth * -INDETERMINATE_WIDTH_FACTOR, innerWidth],
}),
}, {
translateX: this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth / -2, 0],
}),
}, {
scaleX: this.state.progress,
}],
};
return (
<View style={[containerStyle, style]} {...restProps}>
<Animated.View style={progressStyle} />
{children}
</View>
);
}
}<|fim▁end|> | easing: Easing.linear,
isInteraction: false,
}).start((endState) => {
if (endState.finished) { |
<|file_name|>build_standalone.py<|end_file_name|><|fim▁begin|>import os
import shutil
from subprocess import call
def main():
# Clean the build directory
if os.path.isdir('./build'):
shutil.rmtree('./build')
# Freeze it
call('python setup.py build')
<|fim▁hole|> # Make sure the 7-zip folder is on your path
file_name = 'simulation_standalone'
if os.path.isfile('{}.zip'.format(file_name)):
os.remove('{}.zip'.format(file_name))
call('7z a -tzip {}.zip simulation.xlsm'.format(file_name, file_name))
call('7z a -tzip {}.zip LICENSE.txt'.format(file_name))
call('7z a -tzip {}.zip build'.format(file_name))
if __name__ == '__main__':
main()<|fim▁end|> | # Zip it up - 7-zip provides better compression than the zipfile module |
<|file_name|>config_test.go<|end_file_name|><|fim▁begin|><|fim▁hole|> "testing"
)
func TestLoadConfig(t *testing.T) {
c, err := loadConfig("testdata/config.yaml")
if err != nil {
t.Errorf("failed to load config: %s", err)
}
expect := config{
Reporter: []string{"hoge", "fuga"},
Noticer: []string{"bar"},
}
if !reflect.DeepEqual(expect, *c) {
t.Errorf("something went wrong\n got: %#v\nexpect: %#v", *c, expect)
}
}<|fim▁end|> | package horenso
import (
"reflect" |
<|file_name|>IsOptional.java<|end_file_name|><|fim▁begin|>/*
Copyright (C) 2013-2020 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.support.matchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.Objects;
import java.util.Optional;
/**
* Provides matchers around the {@code Optional} class.
*
* @param <T>
* @author john.butler
* @see Optional
*/
public final class IsOptional<T> extends TypeSafeMatcher<Optional<? extends T>> {
/**
* Checks that the passed Optional is not present.
*/
public static IsOptional<Object> isAbsent() {
return new IsOptional<>(false);
}
/**
* Checks that the passed Optional is present.
*/
public static IsOptional<Object> isPresent() {
return new IsOptional<>(true);
}
public static <T> IsOptional<T> isValue(T value) {
return new IsOptional<>(value);
}
public static <T> IsOptional<T> matches(Matcher<T> matcher) {
return new IsOptional<>(matcher);
}
public static <T extends Iterable> IsOptional<T> isIterable(Matcher<? extends Iterable> matcher) {
return new IsOptional<>((Matcher) matcher);
}
private final boolean someExpected;
private final Optional<T> expected;
private final Optional<Matcher<T>> matcher;
private IsOptional(boolean someExpected) {
this.someExpected = someExpected;
this.expected = Optional.empty();
this.matcher = Optional.empty();
}
private IsOptional(T value) {
this.someExpected = true;<|fim▁hole|>
private IsOptional(Matcher<T> matcher) {
this.someExpected = true;
this.expected = Optional.empty();
this.matcher = Optional.of(matcher);
}
@Override
public void describeTo(Description description) {
if (!someExpected) {
description.appendText("<Absent>");
} else if (expected.isPresent()) {
description.appendValue(expected);
} else if (matcher.isPresent()) {
description.appendText("a present value matching ");
matcher.get().describeTo(description);
} else {
description.appendText("<Present>");
}
}
@Override
public boolean matchesSafely(Optional<? extends T> item) {
if (!someExpected) {
return !item.isPresent();
} else if (expected.isPresent()) {
return item.isPresent() && Objects.equals(item.get(), expected.get());
} else if (matcher.isPresent()) {
return item.isPresent() && matcher.get().matches(item.get());
} else {
return item.isPresent();
}
}
}<|fim▁end|> | this.expected = Optional.of(value);
this.matcher = Optional.empty();
} |
<|file_name|>CheerioPlugins.test.ts<|end_file_name|><|fim▁begin|>//
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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 'mocha';
import { assert } from 'chai';
import * as Cheerio from 'cheerio';
import {
listToParagraph,
} from 'app/parser/util/CheerioPlugin';
import {
getListItemsHTML,
} from './testData';
describe('CheerioPlugins', () => {<|fim▁hole|> const select: Cheerio = Cheerio.load(getListItemsHTML());
const text = listToParagraph(select('ul'));
const textEtalon = 'Tristhet (synlig tristhet og subjektiv opplevd tristhet). '
+ 'Indre spenning. '
+ 'Indre spenning. '
+ 'Indre spenning. '
+ 'Redusert nattesøvn. '
+ 'Svekket apetitt. '
+ 'Konsentrasjonsvansker. '
+ 'Initiativløshet. '
+ 'Svekkende følelsesmessige reaksjoner. '
+ 'Depressivt tankeinnhold. '
+ 'Selvmordstanker';
assert.equal (text, textEtalon);
});
});<|fim▁end|> |
it('list to Paragraph', function() { |
<|file_name|>runtime.js<|end_file_name|><|fim▁begin|>'use strict'
require('should')
const DummyTransport = require('chix-transport/dummy')
const ProcessManager = require('chix-flow/src/process/manager')
const RuntimeHandler = require('../lib/handler/runtime')
const pkg = require('../package')
const schemas = require('../schemas')
// TODO: this just loads the definitions from the live webserver.
// Doesn't matter that much I think..
describe('Runtime Handler:', () => {
it('Should respond to getruntime', (done) => {
const pm = new ProcessManager()
const transport = new DummyTransport({
// logger: console,
bail: true,
schemas: schemas
})
RuntimeHandler.handle(pm, transport /*, console*/)
transport.capabilities = ['my-capabilities']
transport.once('send', (data, conn) => {
data.protocol.should.eql('runtime')
data.command.should.eql('runtime')
data.payload.version.should.eql(pkg.version)
data.payload.capabilities.should.eql([
'my-capabilities'
])
conn.should.eql('test-connection')
// assume the data from the server is ok
done()
})<|fim▁hole|> command: 'getruntime'
}, 'test-connection')
})
})<|fim▁end|> |
// trigger component action
transport.receive({
protocol: 'runtime', |
<|file_name|>bcs.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
import { imageApi } from 'app/apis';
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
// Import our contract artifacts and turn them into usable abstractions.
import store_artifacts from 'build/contracts/Store.json'
import { LogService } from 'app/services';
@Component({
selector: 'bcs-app',
templateUrl: './bcs.component.html',
styleUrls: [
'./bcs.component.scss'
]
})
export class BcsComponent implements OnInit {
public cashRegisterImage: string;
public ethereumLogo: string;
// The following code is simple to show off interacting with your contracts.
// As your needs grow you will likely need to change its form and structure.
// For application bootstrapping, check out window.addEventListener below.
public accounts: any[] = [];
public account: any;
public account_balance: number;
private _web3: any;
// public _web3: any;
// Store is our usable abstraction, which we'll use through the code below.
public Store: any;
// tslint:disable-next-line:no-empty<|fim▁hole|> constructor(private logger: LogService) { }
// tslint:disable-next-line:no-trailing-whitespace
// tslint:disable-next-line:no-empty
public ngOnInit() {
console.log('BCS component loaded');
this.ethereumLogo = imageApi.getImageData('ethereum');
this.cashRegisterImage = imageApi.getImageData('cash_register');
this.initWeb3();
this.initContracts();
}
public initWeb3() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof (window as any).web3 !== 'undefined') {
this.logger.logEx("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask", "BCS");
// Use Mist/MetaMask's provider
(window as any).web3 = new Web3(web3.currentProvider);
} else {
this.logger.logEx("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask", "BCS");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
(window as any).web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
}
public initContracts() {
this.Store = contract(store_artifacts);
// Bootstrap the MetaCoin abstraction for Use.
this.Store.setProvider((window as any).web3.currentProvider);
this._web3 = (window as any).web3;
// Get the initial account balance so it can be displayed.
this._web3.eth.getAccounts((err, accs) => {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
this.accounts = accs;
this.account = this.accounts[0];
this.account_balance = this._web3.fromWei(this._web3.eth.getBalance(this.account), 'ether').toNumber();
});
}
}<|fim▁end|> | |
<|file_name|>test_quat.py<|end_file_name|><|fim▁begin|>import unittest
import pytk.geo as geo
class GeoQuatTest(unittest.TestCase):
def test_shape(self):
self.assertRaises(geo.GeoException, geo.quat, [])
self.assertRaises(geo.GeoException, geo.quat, [0])
self.assertRaises(geo.GeoException, geo.quat, [0, 1])
self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2])
self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4])
self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4, 5])
self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4, 5, 6])
self.assertRaises(geo.GeoException, geo.quat, [0, 1, 2, 3, 4, 5, 6, 7])
def test_equality(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual(w, w)
self.assertEqual(x, x)
self.assertEqual(y, y)
self.assertEqual(z, z)
self.assertNotEqual(w, x)
self.assertNotEqual(w, y)
self.assertNotEqual(w, z)
self.assertNotEqual(x, y)
self.assertNotEqual(x, z)
self.assertNotEqual(y, z)
def test_add_sub(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual( w + x + y , geo.quat([1, 1, 1, 0]))
self.assertEqual( w + x + z, geo.quat([1, 1, 0, 1]))
self.assertEqual( w + y + z, geo.quat([1, 0, 1, 1]))
self.assertEqual( x + y + z, geo.quat([0, 1, 1, 1]))
self.assertEqual( w - x + y , geo.quat([ 1, -1, 1, 0]))
self.assertEqual( w - x + z, geo.quat([ 1, -1, 0, 1]))
self.assertEqual( w - y + z, geo.quat([ 1, 0, -1, 1]))
self.assertEqual( x - y + z, geo.quat([ 0, 1, -1, 1]))
self.assertEqual(- w + x - y , geo.quat([-1, 1, -1, 0]))
self.assertEqual(- w + x - z, geo.quat([-1, 1, 0, -1]))
self.assertEqual(- w + y - z, geo.quat([-1, 0, 1, -1]))
self.assertEqual( - x + y - z, geo.quat([ 0, -1, 1, -1]))
def test_neg(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual(w - x, w + (-x))
self.assertEqual(w - y, w + (-y))
self.assertEqual(w - z, w + (-z))
self.assertEqual(x - y, x + (-y))
self.assertEqual(x - z, x + (-z))
self.assertEqual(y - z, y + (-z))
def test_pow(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertAlmostEqual(w ** 2, 1)
self.assertAlmostEqual(x ** 2, 1)
self.assertAlmostEqual(y ** 2, 1)
self.assertAlmostEqual(z ** 2, 1)
self.assertAlmostEqual(( w - x + y ) ** 2, 3)
self.assertAlmostEqual(( w - x + z) ** 2, 3)
self.assertAlmostEqual(( w - y + z) ** 2, 3)
self.assertAlmostEqual(( x - y + z) ** 2, 3)
self.assertAlmostEqual((- w + x - y ) ** 2, 3)
self.assertAlmostEqual((- w + x - z) ** 2, 3)
self.assertAlmostEqual((- w + y - z) ** 2, 3)
self.assertAlmostEqual(( - x + y - z) ** 2, 3)
def test_conj(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual(w + w.conj, geo.quat([2, 0, 0, 0]))
self.assertEqual(x + x.conj, geo.quat([0, 0, 0, 0]))
self.assertEqual(y + y.conj, geo.quat([0, 0, 0, 0]))
self.assertEqual(z + z.conj, geo.quat([0, 0, 0, 0]))
def test_inv(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual(w * w.inv, geo.quat([1, 0, 0, 0]))
self.assertEqual(w.inv * w, geo.quat([1, 0, 0, 0]))
self.assertEqual(x * x.inv, geo.quat([1, 0, 0, 0]))
self.assertEqual(x.inv * x, geo.quat([1, 0, 0, 0]))
self.assertEqual(y * y.inv, geo.quat([1, 0, 0, 0]))
self.assertEqual(y.inv * y, geo.quat([1, 0, 0, 0]))
self.assertEqual(z * z.inv, geo.quat([1, 0, 0, 0]))
self.assertEqual(z.inv * z, geo.quat([1, 0, 0, 0]))
def test_normal(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertAlmostEqual((w ).normal ** 2, 1)
self.assertAlmostEqual(( x ).normal ** 2, 1)
self.assertAlmostEqual(( y ).normal ** 2, 1)
self.assertAlmostEqual(( z).normal ** 2, 1)
self.assertAlmostEqual((w + x ).normal ** 2, 1)
self.assertAlmostEqual((w + y ).normal ** 2, 1)
self.assertAlmostEqual((w + z).normal ** 2, 1)
self.assertAlmostEqual(( x + y ).normal ** 2, 1)
self.assertAlmostEqual(( x + z).normal ** 2, 1)
self.assertAlmostEqual(( y + z).normal ** 2, 1)
self.assertAlmostEqual((w + x + y ).normal ** 2, 1)<|fim▁hole|> self.assertAlmostEqual((w + x + z).normal ** 2, 1)
self.assertAlmostEqual((w + y + z).normal ** 2, 1)
self.assertAlmostEqual(( x + y + z).normal ** 2, 1)
self.assertAlmostEqual((w + x + y + z).normal ** 2, 1)
def test_as_rquat(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual((w ).as_rquat, rquat([1, 0, 0, 0]))
self.assertEqual(( x ).as_rquat, rquat([0, 1, 0, 0]))
self.assertEqual(( y ).as_rquat, rquat([0, 0, 1, 0]))
self.assertEqual(( z).as_rquat, rquat([0, 0, 0, 1]))
self.assertEqual((w + x ).as_rquat, rquat([1, 1, 0, 0]))
self.assertEqual((w + y ).as_rquat, rquat([1, 0, 1, 0]))
self.assertEqual((w + z).as_rquat, rquat([1, 0, 0, 1]))
self.assertEqual(( x + y ).as_rquat, rquat([0, 1, 1, 0]))
self.assertEqual(( x + z).as_rquat, rquat([0, 1, 0, 1]))
self.assertEqual(( y + z).as_rquat, rquat([0, 0, 1, 1]))
self.assertEqual((w + x + y ).as_rquat, rquat([1, 1, 1, 0]))
self.assertEqual((w + x + z).as_rquat, rquat([1, 1, 0, 1]))
self.assertEqual((w + y + z).as_rquat, rquat([1, 0, 1, 1]))
self.assertEqual(( x + y + z).as_rquat, rquat([0, 1, 1, 1]))
self.assertEqual((w + x + y + z).as_rquat, rquat([1, 1, 1, 1]))
def test_as_vect(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual((w ).as_vect, vect([0, 0, 0]))
self.assertEqual(( x ).as_vect, vect([1, 0, 0]))
self.assertEqual(( y ).as_vect, vect([0, 1, 0]))
self.assertEqual(( z).as_vect, vect([0, 0, 1]))
self.assertEqual((w + x ).as_vect, vect([1, 0, 0]))
self.assertEqual((w + y ).as_vect, vect([0, 1, 0]))
self.assertEqual((w + z).as_vect, vect([0, 0, 1]))
self.assertEqual(( x + y ).as_vect, vect([1, 1, 0]))
self.assertEqual(( x + z).as_vect, vect([1, 0, 1]))
self.assertEqual(( y + z).as_vect, vect([0, 1, 1]))
self.assertEqual((w + x + y ).as_vect, vect([1, 1, 0]))
self.assertEqual((w + x + z).as_vect, vect([1, 0, 1]))
self.assertEqual((w + y + z).as_vect, vect([0, 1, 1]))
self.assertEqual(( x + y + z).as_vect, vect([1, 1, 1]))
self.assertEqual((w + x + y + z).as_vect, vect([1, 1, 1]))
def test_mul(self):
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual( w * x , geo.quat([ 0, 1, 0, 0]))
self.assertEqual( w * y , geo.quat([ 0, 0, 1, 0]))
self.assertEqual( w * z , geo.quat([ 0, 0, 0, 1]))
self.assertEqual( x * y , geo.quat([ 0, 0, 0, 1]))
self.assertEqual( x * z , geo.quat([ 0, 0, -1, 0]))
self.assertEqual( y * z , geo.quat([ 0, 1, 0, 0]))
self.assertEqual( w * x * y , geo.quat([ 0, 0, 0, 1]))
self.assertEqual( w * x * z , geo.quat([ 0, 0, -1, 0]))
self.assertEqual( w * y * z , geo.quat([ 0, 1, 0, 0]))
self.assertEqual( x * y * z , geo.quat([-1, 0, 0, 0]))
self.assertEqual( w * x * y * z , geo.quat([-1, 0, 0, 0]))
self.assertEqual( (w * x) * y * z , geo.quat([-1, 0, 0, 0]))
self.assertEqual( w * (x * y) * z , geo.quat([-1, 0, 0, 0]))
self.assertEqual( w * x * (y * z) , geo.quat([-1, 0, 0, 0]))
self.assertEqual((w * x * y) * (z), geo.quat([-1, 0, 0, 0]))
self.assertEqual((w * x) * (y * z), geo.quat([-1, 0, 0, 0]))
self.assertEqual((w) * (x * y * z), geo.quat([-1, 0, 0, 0]))
self.assertNotEqual(x * y, y * x)
self.assertNotEqual(x * z, z * x)
self.assertNotEqual(y * z, z * y)
def test_rotate(self):
v = geo.vect([0, 1, 2])
w = geo.quat([1, 0, 0, 0])
x = geo.quat([0, 1, 0, 0])
y = geo.quat([0, 0, 1, 0])
z = geo.quat([0, 0, 0, 1])
self.assertEqual( w * v , geo.vect([0, 1, 2]))
self.assertEqual( x * v , geo.vect([0, -1, -2]))
self.assertEqual( y * v , geo.vect([0, 1, -2]))
self.assertEqual( z * v , geo.vect([0, -1, 2]))
self.assertEqual( w * x * v , geo.vect([0, -1, -2]))
self.assertEqual( w * y * v , geo.vect([0, 1, -2]))
self.assertEqual( w * z * v , geo.vect([0, -1, 2]))
self.assertEqual( x * y * v , geo.vect([0, -1, 2]))
self.assertEqual( x * z * v , geo.vect([0, 1, -2]))
self.assertEqual( y * z * v , geo.vect([0, -1, -2]))
self.assertEqual( w * x * y * v , geo.vect([0, -1, 2]))
self.assertEqual( w * x * z * v , geo.vect([0, 1, -2]))
self.assertEqual( w * y * z * v , geo.vect([0, -1, -2]))
self.assertEqual( x * y * z * v , geo.vect([0, 1, 2]))
self.assertEqual( w * x * y * z * v , geo.vect([0, 1, 2]))<|fim▁end|> | |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")<|fim▁hole|> no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text<|fim▁end|> | |
<|file_name|>ListExecutedCommands.js<|end_file_name|><|fim▁begin|>var fixDate = function(date) {
return date.Format('2006-01-02 15:04:05');
};
var entries = executeCommand('getEntries', {});
dbotCommands = [];
userCommands = [];
for (var i = 0; i < entries.length; i++) {
if (typeof entries[i].Contents == 'string' && entries[i].Contents.indexOf('!') === 0 && entries[i].Contents.indexOf('!listExecutedCommands') !== 0) {
if (entries[i].Metadata.User) {
if (args.source === 'All' || args.source === 'Manual') {
userCommands.push({
'Time': fixDate(entries[i].Metadata.Created),
'Entry ID': entries[i].ID,
'User': entries[i].Metadata.User,
'Command': entries[i].Contents
});
}
} else {
if (args.source === 'All' || args.source === 'Playbook') {
dbotCommands.push({<|fim▁hole|> 'Playbook (Task)': entries[i].Metadata.EntryTask.PlaybookName + " (" + entries[i].Metadata.EntryTask.TaskName + ")",
'Command': entries[i].Contents
});
}
}
}
}
var md = '';
if (dbotCommands.length > 0) {
md += tableToMarkdown('DBot Executed Commands', dbotCommands, ['Time', 'Entry ID', 'Playbook (Task)', 'Command']) + '\n';
}
if (userCommands.length > 0) {
md += tableToMarkdown('User Executed Commands', userCommands, ['Time', 'Entry ID', 'User', 'Command']) + '\n';
}
if (md === '') {
md = 'No commands found\n';
}
return {ContentsFormat: formats.markdown, Type: entryTypes.note, Contents: md};<|fim▁end|> | 'Time': fixDate(entries[i].Metadata.Created),
'Entry ID': entries[i].ID, |
<|file_name|>test_ujson.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
try:
import json
except ImportError:
import simplejson as json
import calendar
import datetime
import decimal
from functools import partial
import locale
import math
import re
import time
import dateutil
import numpy as np
import pytest
import pytz
import pandas._libs.json as ujson
from pandas._libs.tslib import Timestamp
import pandas.compat as compat
from pandas.compat import StringIO, range, u
from pandas import DataFrame, DatetimeIndex, Index, NaT, Series, date_range
import pandas.util.testing as tm
json_unicode = (json.dumps if compat.PY3
else partial(json.dumps, encoding="utf-8"))
def _clean_dict(d):
"""
Sanitize dictionary for JSON by converting all keys to strings.
Parameters
----------
d : dict
The dictionary to convert.
Returns
-------
cleaned_dict : dict
"""
return {str(k): v for k, v in compat.iteritems(d)}<|fim▁hole|>@pytest.fixture(params=[
None, # Column indexed by default.
"split",
"records",
"values",
"index"])
def orient(request):
return request.param
@pytest.fixture(params=[None, True])
def numpy(request):
return request.param
class TestUltraJSONTests(object):
@pytest.mark.skipif(compat.is_platform_32bit(),
reason="not compliant on 32-bit, xref #15865")
def test_encode_decimal(self):
sut = decimal.Decimal("1337.1337")
encoded = ujson.encode(sut, double_precision=15)
decoded = ujson.decode(encoded)
assert decoded == 1337.1337
sut = decimal.Decimal("0.95")
encoded = ujson.encode(sut, double_precision=1)
assert encoded == "1.0"
decoded = ujson.decode(encoded)
assert decoded == 1.0
sut = decimal.Decimal("0.94")
encoded = ujson.encode(sut, double_precision=1)
assert encoded == "0.9"
decoded = ujson.decode(encoded)
assert decoded == 0.9
sut = decimal.Decimal("1.95")
encoded = ujson.encode(sut, double_precision=1)
assert encoded == "2.0"
decoded = ujson.decode(encoded)
assert decoded == 2.0
sut = decimal.Decimal("-1.95")
encoded = ujson.encode(sut, double_precision=1)
assert encoded == "-2.0"
decoded = ujson.decode(encoded)
assert decoded == -2.0
sut = decimal.Decimal("0.995")
encoded = ujson.encode(sut, double_precision=2)
assert encoded == "1.0"
decoded = ujson.decode(encoded)
assert decoded == 1.0
sut = decimal.Decimal("0.9995")
encoded = ujson.encode(sut, double_precision=3)
assert encoded == "1.0"
decoded = ujson.decode(encoded)
assert decoded == 1.0
sut = decimal.Decimal("0.99999999999999944")
encoded = ujson.encode(sut, double_precision=15)
assert encoded == "1.0"
decoded = ujson.decode(encoded)
assert decoded == 1.0
@pytest.mark.parametrize("ensure_ascii", [True, False])
def test_encode_string_conversion(self, ensure_ascii):
string_input = "A string \\ / \b \f \n \r \t </script> &"
not_html_encoded = ('"A string \\\\ \\/ \\b \\f \\n '
'\\r \\t <\\/script> &"')
html_encoded = ('"A string \\\\ \\/ \\b \\f \\n \\r \\t '
'\\u003c\\/script\\u003e \\u0026"')
def helper(expected_output, **encode_kwargs):
output = ujson.encode(string_input,
ensure_ascii=ensure_ascii,
**encode_kwargs)
assert output == expected_output
assert string_input == json.loads(output)
assert string_input == ujson.decode(output)
# Default behavior assumes encode_html_chars=False.
helper(not_html_encoded)
# Make sure explicit encode_html_chars=False works.
helper(not_html_encoded, encode_html_chars=False)
# Make sure explicit encode_html_chars=True does the encoding.
helper(html_encoded, encode_html_chars=True)
@pytest.mark.parametrize("long_number", [
-4342969734183514, -12345678901234.56789012, -528656961.4399388
])
def test_double_long_numbers(self, long_number):
sut = {u("a"): long_number}
encoded = ujson.encode(sut, double_precision=15)
decoded = ujson.decode(encoded)
assert sut == decoded
def test_encode_non_c_locale(self):
lc_category = locale.LC_NUMERIC
# We just need one of these locales to work.
for new_locale in ("it_IT.UTF-8", "Italian_Italy"):
if tm.can_set_locale(new_locale, lc_category):
with tm.set_locale(new_locale, lc_category):
assert ujson.loads(ujson.dumps(4.78e60)) == 4.78e60
assert ujson.loads("4.78", precise_float=True) == 4.78
break
def test_decimal_decode_test_precise(self):
sut = {u("a"): 4.56}
encoded = ujson.encode(sut)
decoded = ujson.decode(encoded, precise_float=True)
assert sut == decoded
@pytest.mark.skipif(compat.is_platform_windows() and not compat.PY3,
reason="buggy on win-64 for py2")
def test_encode_double_tiny_exponential(self):
num = 1e-40
assert num == ujson.decode(ujson.encode(num))
num = 1e-100
assert num == ujson.decode(ujson.encode(num))
num = -1e-45
assert num == ujson.decode(ujson.encode(num))
num = -1e-145
assert np.allclose(num, ujson.decode(ujson.encode(num)))
@pytest.mark.parametrize("unicode_key", [
u("key1"), u("بن")
])
def test_encode_dict_with_unicode_keys(self, unicode_key):
unicode_dict = {unicode_key: u("value1")}
assert unicode_dict == ujson.decode(ujson.encode(unicode_dict))
@pytest.mark.parametrize("double_input", [
math.pi,
-math.pi # Should work with negatives too.
])
def test_encode_double_conversion(self, double_input):
output = ujson.encode(double_input)
assert round(double_input, 5) == round(json.loads(output), 5)
assert round(double_input, 5) == round(ujson.decode(output), 5)
def test_encode_with_decimal(self):
decimal_input = 1.0
output = ujson.encode(decimal_input)
assert output == "1.0"
def test_encode_array_of_nested_arrays(self):
nested_input = [[[[]]]] * 20
output = ujson.encode(nested_input)
assert nested_input == json.loads(output)
assert nested_input == ujson.decode(output)
nested_input = np.array(nested_input)
tm.assert_numpy_array_equal(nested_input, ujson.decode(
output, numpy=True, dtype=nested_input.dtype))
def test_encode_array_of_doubles(self):
doubles_input = [31337.31337, 31337.31337,
31337.31337, 31337.31337] * 10
output = ujson.encode(doubles_input)
assert doubles_input == json.loads(output)
assert doubles_input == ujson.decode(output)
tm.assert_numpy_array_equal(np.array(doubles_input),
ujson.decode(output, numpy=True))
def test_double_precision(self):
double_input = 30.012345678901234
output = ujson.encode(double_input, double_precision=15)
assert double_input == json.loads(output)
assert double_input == ujson.decode(output)
for double_precision in (3, 9):
output = ujson.encode(double_input,
double_precision=double_precision)
rounded_input = round(double_input, double_precision)
assert rounded_input == json.loads(output)
assert rounded_input == ujson.decode(output)
@pytest.mark.parametrize("invalid_val", [
20, -1, "9", None
])
def test_invalid_double_precision(self, invalid_val):
double_input = 30.12345678901234567890
expected_exception = (ValueError if isinstance(invalid_val, int)
else TypeError)
with pytest.raises(expected_exception):
ujson.encode(double_input, double_precision=invalid_val)
def test_encode_string_conversion2(self):
string_input = "A string \\ / \b \f \n \r \t"
output = ujson.encode(string_input)
assert string_input == json.loads(output)
assert string_input == ujson.decode(output)
assert output == '"A string \\\\ \\/ \\b \\f \\n \\r \\t"'
@pytest.mark.parametrize("unicode_input", [
"Räksmörgås اسامة بن محمد بن عوض بن لادن",
"\xe6\x97\xa5\xd1\x88"
])
def test_encode_unicode_conversion(self, unicode_input):
enc = ujson.encode(unicode_input)
dec = ujson.decode(enc)
assert enc == json_unicode(unicode_input)
assert dec == json.loads(enc)
def test_encode_control_escaping(self):
escaped_input = "\x19"
enc = ujson.encode(escaped_input)
dec = ujson.decode(enc)
assert escaped_input == dec
assert enc == json_unicode(escaped_input)
def test_encode_unicode_surrogate_pair(self):
surrogate_input = "\xf0\x90\x8d\x86"
enc = ujson.encode(surrogate_input)
dec = ujson.decode(enc)
assert enc == json_unicode(surrogate_input)
assert dec == json.loads(enc)
def test_encode_unicode_4bytes_utf8(self):
four_bytes_input = "\xf0\x91\x80\xb0TRAILINGNORMAL"
enc = ujson.encode(four_bytes_input)
dec = ujson.decode(enc)
assert enc == json_unicode(four_bytes_input)
assert dec == json.loads(enc)
def test_encode_unicode_4bytes_utf8highest(self):
four_bytes_input = "\xf3\xbf\xbf\xbfTRAILINGNORMAL"
enc = ujson.encode(four_bytes_input)
dec = ujson.decode(enc)
assert enc == json_unicode(four_bytes_input)
assert dec == json.loads(enc)
def test_encode_array_in_array(self):
arr_in_arr_input = [[[[]]]]
output = ujson.encode(arr_in_arr_input)
assert arr_in_arr_input == json.loads(output)
assert output == json.dumps(arr_in_arr_input)
assert arr_in_arr_input == ujson.decode(output)
tm.assert_numpy_array_equal(np.array(arr_in_arr_input),
ujson.decode(output, numpy=True))
@pytest.mark.parametrize("num_input", [
31337,
-31337, # Negative number.
-9223372036854775808 # Large negative number.
])
def test_encode_num_conversion(self, num_input):
output = ujson.encode(num_input)
assert num_input == json.loads(output)
assert output == json.dumps(num_input)
assert num_input == ujson.decode(output)
def test_encode_list_conversion(self):
list_input = [1, 2, 3, 4]
output = ujson.encode(list_input)
assert list_input == json.loads(output)
assert list_input == ujson.decode(output)
tm.assert_numpy_array_equal(np.array(list_input),
ujson.decode(output, numpy=True))
def test_encode_dict_conversion(self):
dict_input = {"k1": 1, "k2": 2, "k3": 3, "k4": 4}
output = ujson.encode(dict_input)
assert dict_input == json.loads(output)
assert dict_input == ujson.decode(output)
@pytest.mark.parametrize("builtin_value", [None, True, False])
def test_encode_builtin_values_conversion(self, builtin_value):
output = ujson.encode(builtin_value)
assert builtin_value == json.loads(output)
assert output == json.dumps(builtin_value)
assert builtin_value == ujson.decode(output)
def test_encode_datetime_conversion(self):
datetime_input = datetime.datetime.fromtimestamp(time.time())
output = ujson.encode(datetime_input, date_unit="s")
expected = calendar.timegm(datetime_input.utctimetuple())
assert int(expected) == json.loads(output)
assert int(expected) == ujson.decode(output)
def test_encode_date_conversion(self):
date_input = datetime.date.fromtimestamp(time.time())
output = ujson.encode(date_input, date_unit="s")
tup = (date_input.year, date_input.month, date_input.day, 0, 0, 0)
expected = calendar.timegm(tup)
assert int(expected) == json.loads(output)
assert int(expected) == ujson.decode(output)
@pytest.mark.parametrize("test", [
datetime.time(),
datetime.time(1, 2, 3),
datetime.time(10, 12, 15, 343243),
])
def test_encode_time_conversion_basic(self, test):
output = ujson.encode(test)
expected = '"{iso}"'.format(iso=test.isoformat())
assert expected == output
def test_encode_time_conversion_pytz(self):
# see gh-11473: to_json segfaults with timezone-aware datetimes
test = datetime.time(10, 12, 15, 343243, pytz.utc)
output = ujson.encode(test)
expected = '"{iso}"'.format(iso=test.isoformat())
assert expected == output
def test_encode_time_conversion_dateutil(self):
# see gh-11473: to_json segfaults with timezone-aware datetimes
test = datetime.time(10, 12, 15, 343243, dateutil.tz.tzutc())
output = ujson.encode(test)
expected = '"{iso}"'.format(iso=test.isoformat())
assert expected == output
@pytest.mark.parametrize("decoded_input", [
NaT,
np.datetime64("NaT"),
np.nan,
np.inf,
-np.inf
])
def test_encode_as_null(self, decoded_input):
assert ujson.encode(decoded_input) == "null", "Expected null"
def test_datetime_units(self):
val = datetime.datetime(2013, 8, 17, 21, 17, 12, 215504)
stamp = Timestamp(val)
roundtrip = ujson.decode(ujson.encode(val, date_unit='s'))
assert roundtrip == stamp.value // 10**9
roundtrip = ujson.decode(ujson.encode(val, date_unit='ms'))
assert roundtrip == stamp.value // 10**6
roundtrip = ujson.decode(ujson.encode(val, date_unit='us'))
assert roundtrip == stamp.value // 10**3
roundtrip = ujson.decode(ujson.encode(val, date_unit='ns'))
assert roundtrip == stamp.value
msg = "Invalid value 'foo' for option 'date_unit'"
with pytest.raises(ValueError, match=msg):
ujson.encode(val, date_unit='foo')
def test_encode_to_utf8(self):
unencoded = "\xe6\x97\xa5\xd1\x88"
enc = ujson.encode(unencoded, ensure_ascii=False)
dec = ujson.decode(enc)
assert enc == json_unicode(unencoded, ensure_ascii=False)
assert dec == json.loads(enc)
def test_decode_from_unicode(self):
unicode_input = u("{\"obj\": 31337}")
dec1 = ujson.decode(unicode_input)
dec2 = ujson.decode(str(unicode_input))
assert dec1 == dec2
def test_encode_recursion_max(self):
# 8 is the max recursion depth
class O2(object):
member = 0
pass
class O1(object):
member = 0
pass
decoded_input = O1()
decoded_input.member = O2()
decoded_input.member.member = decoded_input
with pytest.raises(OverflowError):
ujson.encode(decoded_input)
def test_decode_jibberish(self):
jibberish = "fdsa sda v9sa fdsa"
with pytest.raises(ValueError):
ujson.decode(jibberish)
@pytest.mark.parametrize("broken_json", [
"[", # Broken array start.
"{", # Broken object start.
"]", # Broken array end.
"}", # Broken object end.
])
def test_decode_broken_json(self, broken_json):
with pytest.raises(ValueError):
ujson.decode(broken_json)
@pytest.mark.parametrize("too_big_char", [
"[",
"{",
])
def test_decode_depth_too_big(self, too_big_char):
with pytest.raises(ValueError):
ujson.decode(too_big_char * (1024 * 1024))
@pytest.mark.parametrize("bad_string", [
"\"TESTING", # Unterminated.
"\"TESTING\\\"", # Unterminated escape.
"tru", # Broken True.
"fa", # Broken False.
"n", # Broken None.
])
def test_decode_bad_string(self, bad_string):
with pytest.raises(ValueError):
ujson.decode(bad_string)
@pytest.mark.parametrize("broken_json", [
'{{1337:""}}',
'{{"key":"}',
'[[[true',
])
def test_decode_broken_json_leak(self, broken_json):
for _ in range(1000):
with pytest.raises(ValueError):
ujson.decode(broken_json)
@pytest.mark.parametrize("invalid_dict", [
"{{{{31337}}}}", # No key.
"{{{{\"key\":}}}}", # No value.
"{{{{\"key\"}}}}", # No colon or value.
])
def test_decode_invalid_dict(self, invalid_dict):
with pytest.raises(ValueError):
ujson.decode(invalid_dict)
@pytest.mark.parametrize("numeric_int_as_str", [
"31337", "-31337" # Should work with negatives.
])
def test_decode_numeric_int(self, numeric_int_as_str):
assert int(numeric_int_as_str) == ujson.decode(numeric_int_as_str)
@pytest.mark.skipif(compat.PY3, reason="only PY2")
def test_encode_unicode_4bytes_utf8_fail(self):
with pytest.raises(OverflowError):
ujson.encode("\xfd\xbf\xbf\xbf\xbf\xbf")
def test_encode_null_character(self):
wrapped_input = "31337 \x00 1337"
output = ujson.encode(wrapped_input)
assert wrapped_input == json.loads(output)
assert output == json.dumps(wrapped_input)
assert wrapped_input == ujson.decode(output)
alone_input = "\x00"
output = ujson.encode(alone_input)
assert alone_input == json.loads(output)
assert output == json.dumps(alone_input)
assert alone_input == ujson.decode(output)
assert '" \\u0000\\r\\n "' == ujson.dumps(u(" \u0000\r\n "))
def test_decode_null_character(self):
wrapped_input = "\"31337 \\u0000 31337\""
assert ujson.decode(wrapped_input) == json.loads(wrapped_input)
def test_encode_list_long_conversion(self):
long_input = [9223372036854775807, 9223372036854775807,
9223372036854775807, 9223372036854775807,
9223372036854775807, 9223372036854775807]
output = ujson.encode(long_input)
assert long_input == json.loads(output)
assert long_input == ujson.decode(output)
tm.assert_numpy_array_equal(np.array(long_input),
ujson.decode(output, numpy=True,
dtype=np.int64))
def test_encode_long_conversion(self):
long_input = 9223372036854775807
output = ujson.encode(long_input)
assert long_input == json.loads(output)
assert output == json.dumps(long_input)
assert long_input == ujson.decode(output)
@pytest.mark.parametrize("int_exp", [
"1337E40", "1.337E40", "1337E+9", "1.337e+40", "1.337E-4"
])
def test_decode_numeric_int_exp(self, int_exp):
assert ujson.decode(int_exp) == json.loads(int_exp)
def test_dump_to_file(self):
f = StringIO()
ujson.dump([1, 2, 3], f)
assert "[1,2,3]" == f.getvalue()
def test_dump_to_file_like(self):
class FileLike(object):
def __init__(self):
self.bytes = ''
def write(self, data_bytes):
self.bytes += data_bytes
f = FileLike()
ujson.dump([1, 2, 3], f)
assert "[1,2,3]" == f.bytes
def test_dump_file_args_error(self):
with pytest.raises(TypeError):
ujson.dump([], "")
def test_load_file(self):
data = "[1,2,3,4]"
exp_data = [1, 2, 3, 4]
f = StringIO(data)
assert exp_data == ujson.load(f)
f = StringIO(data)
tm.assert_numpy_array_equal(np.array(exp_data),
ujson.load(f, numpy=True))
def test_load_file_like(self):
class FileLike(object):
def read(self):
try:
self.end
except AttributeError:
self.end = True
return "[1,2,3,4]"
exp_data = [1, 2, 3, 4]
f = FileLike()
assert exp_data == ujson.load(f)
f = FileLike()
tm.assert_numpy_array_equal(np.array(exp_data),
ujson.load(f, numpy=True))
def test_load_file_args_error(self):
with pytest.raises(TypeError):
ujson.load("[]")
def test_version(self):
assert re.match(r'^\d+\.\d+(\.\d+)?$', ujson.__version__), \
"ujson.__version__ must be a string like '1.4.0'"
def test_encode_numeric_overflow(self):
with pytest.raises(OverflowError):
ujson.encode(12839128391289382193812939)
def test_encode_numeric_overflow_nested(self):
class Nested(object):
x = 12839128391289382193812939
for _ in range(0, 100):
with pytest.raises(OverflowError):
ujson.encode(Nested())
@pytest.mark.parametrize("val", [
3590016419, 2**31, 2**32, (2**32) - 1
])
def test_decode_number_with_32bit_sign_bit(self, val):
# Test that numbers that fit within 32 bits but would have the
# sign bit set (2**31 <= x < 2**32) are decoded properly.
doc = '{{"id": {val}}}'.format(val=val)
assert ujson.decode(doc)["id"] == val
def test_encode_big_escape(self):
# Make sure no Exception is raised.
for _ in range(10):
base = '\u00e5'.encode("utf-8") if compat.PY3 else "\xc3\xa5"
escape_input = base * 1024 * 1024 * 2
ujson.encode(escape_input)
def test_decode_big_escape(self):
# Make sure no Exception is raised.
for _ in range(10):
base = '\u00e5'.encode("utf-8") if compat.PY3 else "\xc3\xa5"
quote = compat.str_to_bytes("\"")
escape_input = quote + (base * 1024 * 1024 * 2) + quote
ujson.decode(escape_input)
def test_to_dict(self):
d = {u("key"): 31337}
class DictTest(object):
def toDict(self):
return d
o = DictTest()
output = ujson.encode(o)
dec = ujson.decode(output)
assert dec == d
def test_default_handler(self):
class _TestObject(object):
def __init__(self, val):
self.val = val
@property
def recursive_attr(self):
return _TestObject("recursive_attr")
def __str__(self):
return str(self.val)
msg = "Maximum recursion level reached"
with pytest.raises(OverflowError, match=msg):
ujson.encode(_TestObject("foo"))
assert '"foo"' == ujson.encode(_TestObject("foo"),
default_handler=str)
def my_handler(_):
return "foobar"
assert '"foobar"' == ujson.encode(_TestObject("foo"),
default_handler=my_handler)
def my_handler_raises(_):
raise TypeError("I raise for anything")
with pytest.raises(TypeError, match="I raise for anything"):
ujson.encode(_TestObject("foo"), default_handler=my_handler_raises)
def my_int_handler(_):
return 42
assert ujson.decode(ujson.encode(_TestObject("foo"),
default_handler=my_int_handler)) == 42
def my_obj_handler(_):
return datetime.datetime(2013, 2, 3)
assert (ujson.decode(ujson.encode(datetime.datetime(2013, 2, 3))) ==
ujson.decode(ujson.encode(_TestObject("foo"),
default_handler=my_obj_handler)))
obj_list = [_TestObject("foo"), _TestObject("bar")]
assert (json.loads(json.dumps(obj_list, default=str)) ==
ujson.decode(ujson.encode(obj_list, default_handler=str)))
class TestNumpyJSONTests(object):
@pytest.mark.parametrize("bool_input", [True, False])
def test_bool(self, bool_input):
b = np.bool(bool_input)
assert ujson.decode(ujson.encode(b)) == b
def test_bool_array(self):
bool_array = np.array([
True, False, True, True,
False, True, False, False], dtype=np.bool)
output = np.array(ujson.decode(
ujson.encode(bool_array)), dtype=np.bool)
tm.assert_numpy_array_equal(bool_array, output)
def test_int(self, any_int_dtype):
klass = np.dtype(any_int_dtype).type
num = klass(1)
assert klass(ujson.decode(ujson.encode(num))) == num
def test_int_array(self, any_int_dtype):
arr = np.arange(100, dtype=np.int)
arr_input = arr.astype(any_int_dtype)
arr_output = np.array(ujson.decode(ujson.encode(arr_input)),
dtype=any_int_dtype)
tm.assert_numpy_array_equal(arr_input, arr_output)
def test_int_max(self, any_int_dtype):
if any_int_dtype in ("int64", "uint64") and compat.is_platform_32bit():
pytest.skip("Cannot test 64-bit integer on 32-bit platform")
klass = np.dtype(any_int_dtype).type
# uint64 max will always overflow,
# as it's encoded to signed.
if any_int_dtype == "uint64":
num = np.iinfo("int64").max
else:
num = np.iinfo(any_int_dtype).max
assert klass(ujson.decode(ujson.encode(num))) == num
def test_float(self, float_dtype):
klass = np.dtype(float_dtype).type
num = klass(256.2013)
assert klass(ujson.decode(ujson.encode(num))) == num
def test_float_array(self, float_dtype):
arr = np.arange(12.5, 185.72, 1.7322, dtype=np.float)
float_input = arr.astype(float_dtype)
float_output = np.array(ujson.decode(
ujson.encode(float_input, double_precision=15)),
dtype=float_dtype)
tm.assert_almost_equal(float_input, float_output)
def test_float_max(self, float_dtype):
klass = np.dtype(float_dtype).type
num = klass(np.finfo(float_dtype).max / 10)
tm.assert_almost_equal(klass(ujson.decode(
ujson.encode(num, double_precision=15))), num)
def test_array_basic(self):
arr = np.arange(96)
arr = arr.reshape((2, 2, 2, 2, 3, 2))
tm.assert_numpy_array_equal(
np.array(ujson.decode(ujson.encode(arr))), arr)
tm.assert_numpy_array_equal(ujson.decode(
ujson.encode(arr), numpy=True), arr)
@pytest.mark.parametrize("shape", [
(10, 10),
(5, 5, 4),
(100, 1),
])
def test_array_reshaped(self, shape):
arr = np.arange(100)
arr = arr.reshape(shape)
tm.assert_numpy_array_equal(
np.array(ujson.decode(ujson.encode(arr))), arr)
tm.assert_numpy_array_equal(ujson.decode(
ujson.encode(arr), numpy=True), arr)
def test_array_list(self):
arr_list = ["a", list(), dict(), dict(), list(),
42, 97.8, ["a", "b"], {"key": "val"}]
arr = np.array(arr_list)
tm.assert_numpy_array_equal(
np.array(ujson.decode(ujson.encode(arr))), arr)
def test_array_float(self):
dtype = np.float32
arr = np.arange(100.202, 200.202, 1, dtype=dtype)
arr = arr.reshape((5, 5, 4))
arr_out = np.array(ujson.decode(ujson.encode(arr)), dtype=dtype)
tm.assert_almost_equal(arr, arr_out)
arr_out = ujson.decode(ujson.encode(arr), numpy=True, dtype=dtype)
tm.assert_almost_equal(arr, arr_out)
def test_0d_array(self):
with pytest.raises(TypeError):
ujson.encode(np.array(1))
@pytest.mark.parametrize("bad_input,exc_type,kwargs", [
([{}, []], ValueError, {}),
([42, None], TypeError, {}),
([["a"], 42], ValueError, {}),
([42, {}, "a"], TypeError, {}),
([42, ["a"], 42], ValueError, {}),
(["a", "b", [], "c"], ValueError, {}),
([{"a": "b"}], ValueError, dict(labelled=True)),
({"a": {"b": {"c": 42}}}, ValueError, dict(labelled=True)),
([{"a": 42, "b": 23}, {"c": 17}], ValueError, dict(labelled=True))
])
def test_array_numpy_except(self, bad_input, exc_type, kwargs):
with pytest.raises(exc_type):
ujson.decode(ujson.dumps(bad_input), numpy=True, **kwargs)
def test_array_numpy_labelled(self):
labelled_input = {"a": []}
output = ujson.loads(ujson.dumps(labelled_input),
numpy=True, labelled=True)
assert (np.empty((1, 0)) == output[0]).all()
assert (np.array(["a"]) == output[1]).all()
assert output[2] is None
labelled_input = [{"a": 42}]
output = ujson.loads(ujson.dumps(labelled_input),
numpy=True, labelled=True)
assert (np.array([u("a")]) == output[2]).all()
assert (np.array([42]) == output[0]).all()
assert output[1] is None
# see gh-10837: write out the dump explicitly
# so there is no dependency on iteration order
input_dumps = ('[{"a": 42, "b":31}, {"a": 24, "c": 99}, '
'{"a": 2.4, "b": 78}]')
output = ujson.loads(input_dumps, numpy=True, labelled=True)
expected_vals = np.array(
[42, 31, 24, 99, 2.4, 78], dtype=int).reshape((3, 2))
assert (expected_vals == output[0]).all()
assert output[1] is None
assert (np.array([u("a"), "b"]) == output[2]).all()
input_dumps = ('{"1": {"a": 42, "b":31}, "2": {"a": 24, "c": 99}, '
'"3": {"a": 2.4, "b": 78}}')
output = ujson.loads(input_dumps, numpy=True, labelled=True)
expected_vals = np.array(
[42, 31, 24, 99, 2.4, 78], dtype=int).reshape((3, 2))
assert (expected_vals == output[0]).all()
assert (np.array(["1", "2", "3"]) == output[1]).all()
assert (np.array(["a", "b"]) == output[2]).all()
class TestPandasJSONTests(object):
def test_dataframe(self, orient, numpy):
if orient == "records" and numpy:
pytest.skip("Not idiomatic pandas")
df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[
"a", "b"], columns=["x", "y", "z"])
encode_kwargs = {} if orient is None else dict(orient=orient)
decode_kwargs = {} if numpy is None else dict(numpy=numpy)
output = ujson.decode(ujson.encode(df, **encode_kwargs),
**decode_kwargs)
# Ensure proper DataFrame initialization.
if orient == "split":
dec = _clean_dict(output)
output = DataFrame(**dec)
else:
output = DataFrame(output)
# Corrections to enable DataFrame comparison.
if orient == "values":
df.columns = [0, 1, 2]
df.index = [0, 1]
elif orient == "records":
df.index = [0, 1]
elif orient == "index":
df = df.transpose()
tm.assert_frame_equal(output, df, check_dtype=False)
def test_dataframe_nested(self, orient):
df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[
"a", "b"], columns=["x", "y", "z"])
nested = {"df1": df, "df2": df.copy()}
kwargs = {} if orient is None else dict(orient=orient)
exp = {"df1": ujson.decode(ujson.encode(df, **kwargs)),
"df2": ujson.decode(ujson.encode(df, **kwargs))}
assert ujson.decode(ujson.encode(nested, **kwargs)) == exp
def test_dataframe_numpy_labelled(self, orient):
if orient in ("split", "values"):
pytest.skip("Incompatible with labelled=True")
df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[
"a", "b"], columns=["x", "y", "z"], dtype=np.int)
kwargs = {} if orient is None else dict(orient=orient)
output = DataFrame(*ujson.decode(ujson.encode(df, **kwargs),
numpy=True, labelled=True))
if orient is None:
df = df.T
elif orient == "records":
df.index = [0, 1]
tm.assert_frame_equal(output, df)
def test_series(self, orient, numpy):
s = Series([10, 20, 30, 40, 50, 60], name="series",
index=[6, 7, 8, 9, 10, 15]).sort_values()
encode_kwargs = {} if orient is None else dict(orient=orient)
decode_kwargs = {} if numpy is None else dict(numpy=numpy)
output = ujson.decode(ujson.encode(s, **encode_kwargs),
**decode_kwargs)
if orient == "split":
dec = _clean_dict(output)
output = Series(**dec)
else:
output = Series(output)
if orient in (None, "index"):
s.name = None
output = output.sort_values()
s.index = ["6", "7", "8", "9", "10", "15"]
elif orient in ("records", "values"):
s.name = None
s.index = [0, 1, 2, 3, 4, 5]
tm.assert_series_equal(output, s, check_dtype=False)
def test_series_nested(self, orient):
s = Series([10, 20, 30, 40, 50, 60], name="series",
index=[6, 7, 8, 9, 10, 15]).sort_values()
nested = {"s1": s, "s2": s.copy()}
kwargs = {} if orient is None else dict(orient=orient)
exp = {"s1": ujson.decode(ujson.encode(s, **kwargs)),
"s2": ujson.decode(ujson.encode(s, **kwargs))}
assert ujson.decode(ujson.encode(nested, **kwargs)) == exp
def test_index(self):
i = Index([23, 45, 18, 98, 43, 11], name="index")
# Column indexed.
output = Index(ujson.decode(ujson.encode(i)), name="index")
tm.assert_index_equal(i, output)
output = Index(ujson.decode(ujson.encode(i), numpy=True), name="index")
tm.assert_index_equal(i, output)
dec = _clean_dict(ujson.decode(ujson.encode(i, orient="split")))
output = Index(**dec)
tm.assert_index_equal(i, output)
assert i.name == output.name
dec = _clean_dict(ujson.decode(ujson.encode(i, orient="split"),
numpy=True))
output = Index(**dec)
tm.assert_index_equal(i, output)
assert i.name == output.name
output = Index(ujson.decode(ujson.encode(i, orient="values")),
name="index")
tm.assert_index_equal(i, output)
output = Index(ujson.decode(ujson.encode(i, orient="values"),
numpy=True), name="index")
tm.assert_index_equal(i, output)
output = Index(ujson.decode(ujson.encode(i, orient="records")),
name="index")
tm.assert_index_equal(i, output)
output = Index(ujson.decode(ujson.encode(i, orient="records"),
numpy=True), name="index")
tm.assert_index_equal(i, output)
output = Index(ujson.decode(ujson.encode(i, orient="index")),
name="index")
tm.assert_index_equal(i, output)
output = Index(ujson.decode(ujson.encode(i, orient="index"),
numpy=True), name="index")
tm.assert_index_equal(i, output)
def test_datetime_index(self):
date_unit = "ns"
rng = date_range("1/1/2000", periods=20)
encoded = ujson.encode(rng, date_unit=date_unit)
decoded = DatetimeIndex(np.array(ujson.decode(encoded)))
tm.assert_index_equal(rng, decoded)
ts = Series(np.random.randn(len(rng)), index=rng)
decoded = Series(ujson.decode(ujson.encode(ts, date_unit=date_unit)))
idx_values = decoded.index.values.astype(np.int64)
decoded.index = DatetimeIndex(idx_values)
tm.assert_series_equal(ts, decoded)
@pytest.mark.parametrize("invalid_arr", [
"[31337,]", # Trailing comma.
"[,31337]", # Leading comma.
"[]]", # Unmatched bracket.
"[,]", # Only comma.
])
def test_decode_invalid_array(self, invalid_arr):
with pytest.raises(ValueError):
ujson.decode(invalid_arr)
@pytest.mark.parametrize("arr", [
[], [31337]
])
def test_decode_array(self, arr):
assert arr == ujson.decode(str(arr))
@pytest.mark.parametrize("extreme_num", [
9223372036854775807, -9223372036854775808
])
def test_decode_extreme_numbers(self, extreme_num):
assert extreme_num == ujson.decode(str(extreme_num))
@pytest.mark.parametrize("too_extreme_num", [
"9223372036854775808", "-90223372036854775809"
])
def test_decode_too_extreme_numbers(self, too_extreme_num):
with pytest.raises(ValueError):
ujson.decode(too_extreme_num)
def test_decode_with_trailing_whitespaces(self):
assert {} == ujson.decode("{}\n\t ")
def test_decode_with_trailing_non_whitespaces(self):
with pytest.raises(ValueError):
ujson.decode("{}\n\t a")
def test_decode_array_with_big_int(self):
with pytest.raises(ValueError):
ujson.loads("[18446098363113800555]")
@pytest.mark.parametrize("float_number", [
1.1234567893, 1.234567893, 1.34567893,
1.4567893, 1.567893, 1.67893,
1.7893, 1.893, 1.3,
])
@pytest.mark.parametrize("sign", [-1, 1])
def test_decode_floating_point(self, sign, float_number):
float_number *= sign
tm.assert_almost_equal(float_number,
ujson.loads(str(float_number)),
check_less_precise=15)
def test_encode_big_set(self):
s = set()
for x in range(0, 100000):
s.add(x)
# Make sure no Exception is raised.
ujson.encode(s)
def test_encode_empty_set(self):
assert "[]" == ujson.encode(set())
def test_encode_set(self):
s = {1, 2, 3, 4, 5, 6, 7, 8, 9}
enc = ujson.encode(s)
dec = ujson.decode(enc)
for v in dec:
assert v in s<|fim▁end|> | |
<|file_name|>utils.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 glutin;
use servo::ServoCursor;
use traits::view::Key;
pub fn glutin_key_to_script_key(key: glutin::VirtualKeyCode) -> Result<Key, ()> {
match key {
glutin::VirtualKeyCode::A => Ok(Key::A),
glutin::VirtualKeyCode::B => Ok(Key::B),
glutin::VirtualKeyCode::C => Ok(Key::C),
glutin::VirtualKeyCode::D => Ok(Key::D),
glutin::VirtualKeyCode::E => Ok(Key::E),
glutin::VirtualKeyCode::F => Ok(Key::F),
glutin::VirtualKeyCode::G => Ok(Key::G),
glutin::VirtualKeyCode::H => Ok(Key::H),
glutin::VirtualKeyCode::I => Ok(Key::I),
glutin::VirtualKeyCode::J => Ok(Key::J),
glutin::VirtualKeyCode::K => Ok(Key::K),
glutin::VirtualKeyCode::L => Ok(Key::L),
glutin::VirtualKeyCode::M => Ok(Key::M),
glutin::VirtualKeyCode::N => Ok(Key::N),
glutin::VirtualKeyCode::O => Ok(Key::O),
glutin::VirtualKeyCode::P => Ok(Key::P),
glutin::VirtualKeyCode::Q => Ok(Key::Q),
glutin::VirtualKeyCode::R => Ok(Key::R),
glutin::VirtualKeyCode::S => Ok(Key::S),
glutin::VirtualKeyCode::T => Ok(Key::T),
glutin::VirtualKeyCode::U => Ok(Key::U),
glutin::VirtualKeyCode::V => Ok(Key::V),
glutin::VirtualKeyCode::W => Ok(Key::W),
glutin::VirtualKeyCode::X => Ok(Key::X),
glutin::VirtualKeyCode::Y => Ok(Key::Y),
glutin::VirtualKeyCode::Z => Ok(Key::Z),
glutin::VirtualKeyCode::Numpad0 => Ok(Key::Kp0),
glutin::VirtualKeyCode::Numpad1 => Ok(Key::Kp1),
glutin::VirtualKeyCode::Numpad2 => Ok(Key::Kp2),
glutin::VirtualKeyCode::Numpad3 => Ok(Key::Kp3),
glutin::VirtualKeyCode::Numpad4 => Ok(Key::Kp4),
glutin::VirtualKeyCode::Numpad5 => Ok(Key::Kp5),
glutin::VirtualKeyCode::Numpad6 => Ok(Key::Kp6),
glutin::VirtualKeyCode::Numpad7 => Ok(Key::Kp7),
glutin::VirtualKeyCode::Numpad8 => Ok(Key::Kp8),
glutin::VirtualKeyCode::Numpad9 => Ok(Key::Kp9),
glutin::VirtualKeyCode::Key0 => Ok(Key::Num0),
glutin::VirtualKeyCode::Key1 => Ok(Key::Num1),
glutin::VirtualKeyCode::Key2 => Ok(Key::Num2),
glutin::VirtualKeyCode::Key3 => Ok(Key::Num3),
glutin::VirtualKeyCode::Key4 => Ok(Key::Num4),
glutin::VirtualKeyCode::Key5 => Ok(Key::Num5),
glutin::VirtualKeyCode::Key6 => Ok(Key::Num6),
glutin::VirtualKeyCode::Key7 => Ok(Key::Num7),
glutin::VirtualKeyCode::Key8 => Ok(Key::Num8),
glutin::VirtualKeyCode::Key9 => Ok(Key::Num9),
glutin::VirtualKeyCode::Return => Ok(Key::Enter),
glutin::VirtualKeyCode::Space => Ok(Key::Space),
glutin::VirtualKeyCode::Escape => Ok(Key::Escape),
glutin::VirtualKeyCode::Equals => Ok(Key::Equal),
glutin::VirtualKeyCode::Minus => Ok(Key::Minus),
glutin::VirtualKeyCode::Back => Ok(Key::Backspace),
glutin::VirtualKeyCode::PageDown => Ok(Key::PageDown),
glutin::VirtualKeyCode::PageUp => Ok(Key::PageUp),
glutin::VirtualKeyCode::Insert => Ok(Key::Insert),
glutin::VirtualKeyCode::Home => Ok(Key::Home),
glutin::VirtualKeyCode::Delete => Ok(Key::Delete),
glutin::VirtualKeyCode::End => Ok(Key::End),
glutin::VirtualKeyCode::Left => Ok(Key::Left),
glutin::VirtualKeyCode::Up => Ok(Key::Up),
glutin::VirtualKeyCode::Right => Ok(Key::Right),
glutin::VirtualKeyCode::Down => Ok(Key::Down),
glutin::VirtualKeyCode::LShift => Ok(Key::LeftShift),
glutin::VirtualKeyCode::LControl => Ok(Key::LeftControl),
glutin::VirtualKeyCode::LAlt => Ok(Key::LeftAlt),
glutin::VirtualKeyCode::LWin => Ok(Key::LeftSuper),
glutin::VirtualKeyCode::RShift => Ok(Key::RightShift),
glutin::VirtualKeyCode::RControl => Ok(Key::RightControl),
glutin::VirtualKeyCode::RAlt => Ok(Key::RightAlt),
glutin::VirtualKeyCode::RWin => Ok(Key::RightSuper),
glutin::VirtualKeyCode::Apostrophe => Ok(Key::Apostrophe),
glutin::VirtualKeyCode::Backslash => Ok(Key::Backslash),
glutin::VirtualKeyCode::Comma => Ok(Key::Comma),
glutin::VirtualKeyCode::Grave => Ok(Key::GraveAccent),
glutin::VirtualKeyCode::LBracket => Ok(Key::LeftBracket),
glutin::VirtualKeyCode::Period => Ok(Key::Period),
glutin::VirtualKeyCode::RBracket => Ok(Key::RightBracket),
glutin::VirtualKeyCode::Semicolon => Ok(Key::Semicolon),
glutin::VirtualKeyCode::Slash => Ok(Key::Slash),
glutin::VirtualKeyCode::Tab => Ok(Key::Tab),
glutin::VirtualKeyCode::Subtract => Ok(Key::Minus),
glutin::VirtualKeyCode::F1 => Ok(Key::F1),
glutin::VirtualKeyCode::F2 => Ok(Key::F2),
glutin::VirtualKeyCode::F3 => Ok(Key::F3),
glutin::VirtualKeyCode::F4 => Ok(Key::F4),
glutin::VirtualKeyCode::F5 => Ok(Key::F5),
glutin::VirtualKeyCode::F6 => Ok(Key::F6),
glutin::VirtualKeyCode::F7 => Ok(Key::F7),
glutin::VirtualKeyCode::F8 => Ok(Key::F8),
glutin::VirtualKeyCode::F9 => Ok(Key::F9),
glutin::VirtualKeyCode::F10 => Ok(Key::F10),
glutin::VirtualKeyCode::F11 => Ok(Key::F11),
glutin::VirtualKeyCode::F12 => Ok(Key::F12),
glutin::VirtualKeyCode::NavigateBackward => Ok(Key::NavigateBackward),
glutin::VirtualKeyCode::NavigateForward => Ok(Key::NavigateForward),
_ => Err(()),
}
}
pub fn is_printable(key_code: glutin::VirtualKeyCode) -> bool {
use glutin::VirtualKeyCode::*;
match key_code {
Escape | F1 | F2 | F3 | F4 | F5 | F6 | F7 | F8 | F9 | F10 | F11 | F12 | F13 | F14 |
F15 | Snapshot | Scroll | Pause | Insert | Home | Delete | End | PageDown | PageUp |
Left | Up | Right | Down | Back | LAlt | LControl | LMenu | LShift | LWin | Mail |
MediaSelect | MediaStop | Mute | MyComputer | NavigateForward | NavigateBackward |
NextTrack | NoConvert | PlayPause | Power | PrevTrack | RAlt | RControl | RMenu |
RShift | RWin | Sleep | Stop | VolumeDown | VolumeUp | Wake | WebBack | WebFavorites |
WebForward | WebHome | WebRefresh | WebSearch | WebStop => false,
_ => true,
}
}
pub fn servo_cursor_to_glutin_cursor(servo_cursor: ServoCursor) -> glutin::MouseCursor {
match servo_cursor {
ServoCursor::None => glutin::MouseCursor::NoneCursor,
ServoCursor::Default => glutin::MouseCursor::Default,
ServoCursor::Pointer => glutin::MouseCursor::Hand,
ServoCursor::ContextMenu => glutin::MouseCursor::ContextMenu,
ServoCursor::Help => glutin::MouseCursor::Help,
ServoCursor::Progress => glutin::MouseCursor::Progress,
ServoCursor::Wait => glutin::MouseCursor::Wait,
ServoCursor::Cell => glutin::MouseCursor::Cell,
ServoCursor::Crosshair => glutin::MouseCursor::Crosshair,
ServoCursor::Text => glutin::MouseCursor::Text,
ServoCursor::VerticalText => glutin::MouseCursor::VerticalText,
ServoCursor::Alias => glutin::MouseCursor::Alias,
ServoCursor::Copy => glutin::MouseCursor::Copy,
ServoCursor::Move => glutin::MouseCursor::Move,
ServoCursor::NoDrop => glutin::MouseCursor::NoDrop,
ServoCursor::NotAllowed => glutin::MouseCursor::NotAllowed,
ServoCursor::Grab => glutin::MouseCursor::Grab,
ServoCursor::Grabbing => glutin::MouseCursor::Grabbing,
ServoCursor::EResize => glutin::MouseCursor::EResize,
ServoCursor::NResize => glutin::MouseCursor::NResize,
ServoCursor::NeResize => glutin::MouseCursor::NeResize,
ServoCursor::NwResize => glutin::MouseCursor::NwResize,
ServoCursor::SResize => glutin::MouseCursor::SResize,
ServoCursor::SeResize => glutin::MouseCursor::SeResize,
ServoCursor::SwResize => glutin::MouseCursor::SwResize,
ServoCursor::WResize => glutin::MouseCursor::WResize,
ServoCursor::EwResize => glutin::MouseCursor::EwResize,
ServoCursor::NsResize => glutin::MouseCursor::NsResize,
ServoCursor::NeswResize => glutin::MouseCursor::NeswResize,
ServoCursor::NwseResize => glutin::MouseCursor::NwseResize,
ServoCursor::ColResize => glutin::MouseCursor::ColResize,
ServoCursor::RowResize => glutin::MouseCursor::RowResize,
ServoCursor::AllScroll => glutin::MouseCursor::AllScroll,
ServoCursor::ZoomIn => glutin::MouseCursor::ZoomIn,
ServoCursor::ZoomOut => glutin::MouseCursor::ZoomOut,
}
}
// Some shortcuts use Cmd on Mac and Control on other systems.
pub fn cmd_or_ctrl(m: glutin::ModifiersState) -> bool {
if cfg!(target_os = "macos") {
m.logo
} else {
m.ctrl
}
}
pub fn char_to_script_key(c: char) -> Option<Key> {
match c {
' ' => Some(Key::Space),
'"' => Some(Key::Apostrophe),
'\'' => Some(Key::Apostrophe),
'<' => Some(Key::Comma),
',' => Some(Key::Comma),
'_' => Some(Key::Minus),
'-' => Some(Key::Minus),
'>' => Some(Key::Period),
'.' => Some(Key::Period),
'?' => Some(Key::Slash),
'/' => Some(Key::Slash),
'~' => Some(Key::GraveAccent),
'`' => Some(Key::GraveAccent),
')' => Some(Key::Num0),
'0' => Some(Key::Num0),
'!' => Some(Key::Num1),
'1' => Some(Key::Num1),
'@' => Some(Key::Num2),
'2' => Some(Key::Num2),
'#' => Some(Key::Num3),
'3' => Some(Key::Num3),
'$' => Some(Key::Num4),
'4' => Some(Key::Num4),
'%' => Some(Key::Num5),
'5' => Some(Key::Num5),
'^' => Some(Key::Num6),
'6' => Some(Key::Num6),
'&' => Some(Key::Num7),
'7' => Some(Key::Num7),
'*' => Some(Key::Num8),
'8' => Some(Key::Num8),
'(' => Some(Key::Num9),
'9' => Some(Key::Num9),
':' => Some(Key::Semicolon),
';' => Some(Key::Semicolon),
'+' => Some(Key::Equal),
'=' => Some(Key::Equal),
'A' => Some(Key::A),
'a' => Some(Key::A),
'B' => Some(Key::B),
'b' => Some(Key::B),
'C' => Some(Key::C),
'c' => Some(Key::C),
'D' => Some(Key::D),
'd' => Some(Key::D),
'E' => Some(Key::E),
'e' => Some(Key::E),
'F' => Some(Key::F),
'f' => Some(Key::F),
'G' => Some(Key::G),
'g' => Some(Key::G),
'H' => Some(Key::H),
'h' => Some(Key::H),
'I' => Some(Key::I),
'i' => Some(Key::I),
'J' => Some(Key::J),
'j' => Some(Key::J),
'K' => Some(Key::K),
'k' => Some(Key::K),
'L' => Some(Key::L),
'l' => Some(Key::L),
'M' => Some(Key::M),
'm' => Some(Key::M),
'N' => Some(Key::N),
'n' => Some(Key::N),
'O' => Some(Key::O),
'o' => Some(Key::O),
'P' => Some(Key::P),
'p' => Some(Key::P),
'Q' => Some(Key::Q),
'q' => Some(Key::Q),
'R' => Some(Key::R),
'r' => Some(Key::R),<|fim▁hole|> 'S' => Some(Key::S),
's' => Some(Key::S),
'T' => Some(Key::T),
't' => Some(Key::T),
'U' => Some(Key::U),
'u' => Some(Key::U),
'V' => Some(Key::V),
'v' => Some(Key::V),
'W' => Some(Key::W),
'w' => Some(Key::W),
'X' => Some(Key::X),
'x' => Some(Key::X),
'Y' => Some(Key::Y),
'y' => Some(Key::Y),
'Z' => Some(Key::Z),
'z' => Some(Key::Z),
'{' => Some(Key::LeftBracket),
'[' => Some(Key::LeftBracket),
'|' => Some(Key::Backslash),
'\\' => Some(Key::Backslash),
'}' => Some(Key::RightBracket),
']' => Some(Key::RightBracket),
_ => None,
}
}
#[cfg(target_os = "windows")]
pub fn windows_hidpi_factor() -> f32 {
use user32;
use winapi;
use gdi32;
let hdc = unsafe { user32::GetDC(::std::ptr::null_mut()) };
let ppi = unsafe { gdi32::GetDeviceCaps(hdc, winapi::wingdi::LOGPIXELSY) };
ppi as f32 / 96.0
}<|fim▁end|> | |
<|file_name|>pastislib.py<|end_file_name|><|fim▁begin|>"""
Module containing useful functions to link PASTIS MCMC posterior samples with
the bayev package.
"""
import os
import pickle
import importlib
import numpy as np
import PASTIS_NM
import PASTIS_NM.MCMC as MCMC
from PASTIS_NM import resultpath, configpath
def read_pastis_file(target, simul, pastisfile=None):
"""Read configuration dictionary."""
if pastisfile is None:
# Get input_dict
configname = os.path.join(configpath, target,
target + '_' + simul + '.pastis')
else:
configname = pastisfile
try:
f = open(configname)
except IOError:
raise IOError('Configuration file {} not found!'.format(configname))
dd = pickle.load(f)
f.close()
return dd
def get_datadict(target, simul, pastisfile=None):
config_dicts = read_pastis_file(target, simul, pastisfile)
return PASTIS_NM.readdata(config_dicts[2])[0]
def get_priordict(target, simul, pastisfile=None):
config_dicts = read_pastis_file(target, simul, pastisfile)
return MCMC.priors.prior_constructor(config_dicts[1], {})
def get_posterior_samples(target, simul, mergefile=None,
suffix='_Beta1.000000_mergedchain.dat'):
if mergefile is None:
mergepath = os.path.join(resultpath, target,
target + '_' + simul + suffix)
else:
mergepath = mergefile
f = open(mergepath, 'r')
vdm = pickle.load(f)
f.close()
return vdm
def pastis_init(target, simul, posteriorfile=None, datadict=None,
pastisfile=None):
# Read configuration dictionaries.
configdicts = read_pastis_file(target, simul, pastisfile)
infodict, input_dict = configdicts[0], configdicts[1].copy()
# Read data dictionary.
if datadict is None:
datadict = get_datadict(target, simul, pastisfile=pastisfile)
# Obtain PASTIS version the merged chain was constructed with.
vdm = get_posterior_samples(target, simul, mergefile=posteriorfile)
modulename = vdm.__module__.split('.')[0]
# Import the correct PASTIS version used to construct a given posterior
# sample
pastis = importlib.import_module(modulename)
# To deal with potential drifts, we need initialize to fix TrefRV.
pastis.initialize(infodict, datadict, input_dict)
# import PASTIS_rhk.MCMC as MCMC
# MCMC.PASTIS_MCMC.get_likelihood
importlib.import_module('.MCMC.PASTIS_MCMC', package=pastis.__name__)
importlib.import_module('.AstroClasses', package=pastis.__name__)
importlib.import_module('.ObjectBuilder', package=pastis.__name__)
importlib.import_module('.models.RV', package=pastis.__name__)
importlib.reload(pastis.AstroClasses)
importlib.reload(pastis.ObjectBuilder)
importlib.reload(pastis.models.RV)
importlib.reload(pastis.MCMC.PASTIS_MCMC)
return
def pastis_loglike(samples, params, target, simul, posteriorfile=None,
datadict=None, pastisfile=None):
"""
A wrapper to run the PASTIS.MCMC.get_likelihood function.
Computes the loglikelihood on a series of points given in samples using
PASTIS.MCMC.get_likelihood.
:param np.array samples: parameter samples on which to compute log
likelihood. Array dimensions must be (n x k), where *n* is the number of
samples and *k* is the number of model parameters.
:param list params: parameter names. Must be in the PASTIS format: \
objectname_parametername.
:return:
"""
# Read configuration dictionaries.
configdicts = read_pastis_file(target, simul, pastisfile)
input_dict = configdicts[1].copy()
# Read data dictionary.
if datadict is None:
datadict = get_datadict(target, simul, pastisfile=pastisfile)
# Obtain PASTIS version the merged chain was constructed with.
vdm = get_posterior_samples(target, simul, mergefile=posteriorfile)
modulename = vdm.__module__.split('.')[0]
# Import the correct PASTIS version used to construct a given posterior
# sample
pastis = importlib.import_module(modulename)
"""
# To deal with potential drifts, we need initialize to fix TrefRV.<|fim▁hole|> pastis.initialize(infodict, datadict, input_dict)
# import PASTIS_rhk.MCMC as MCMC
# MCMC.PASTIS_MCMC.get_likelihood
importlib.import_module('.MCMC.PASTIS_MCMC', package=pastis.__name__)
importlib.import_module('.AstroClasses', package=pastis.__name__)
importlib.import_module('.ObjectBuilder', package=pastis.__name__)
importlib.import_module('.models.RV', package=pastis.__name__)
reload(pastis.AstroClasses)
reload(pastis.ObjectBuilder)
reload(pastis.models.RV)
reload(pastis.MCMC.PASTIS_MCMC)
"""
# Prepare output arrays
loglike = np.zeros(samples.shape[0])
for s in range(samples.shape[0]):
for parameter_index, full_param_name in enumerate(params):
# Modify input_dict
obj_name, param_name = full_param_name.split('_')
input_dict[obj_name][param_name][0] = samples[s, parameter_index]
# Construct chain state
chain_state, labeldict = \
pastis.MCMC.tools.state_constructor(input_dict)
try:
# Compute likelihood for this state
ll, loglike[s], likeout = \
pastis.MCMC.PASTIS_MCMC.get_likelihood(chain_state,
input_dict,
datadict, labeldict,
False,
False)
except (ValueError, RuntimeError, pastis.EvolTrackError,
pastis.EBOPparamError):
print('Error in likelihood computation, setting lnlike to -n.inf')
loglike[s] = -np.inf
pass
return loglike
def pastis_logprior(samples, params, target, simul, posteriorfile=None,
pastisfile=None):
"""
A wrapper to run the PASTIS.MCMC.get_likelihood function.
Computes the loglikelihood on a series of points given in samples using
PASTIS.MCMC.get_likelihood.
:param np.array samples: parameter samples on which to compute log
likelihood. Array dimensions must be (n x k), where *n* is the number of
samples and *k* is the number of model parameters.
:param list params: parameter names.
:return:
"""
# Read configuration dictionaries.
configdicts = read_pastis_file(target, simul, pastisfile)
input_dict = configdicts[1].copy()
priordict = get_priordict(target, simul, pastisfile=pastisfile)
# Obtain PASTIS version the merged chain was constructed with.
vdm = get_posterior_samples(target, simul, mergefile=posteriorfile)
modulename = vdm.__module__.split('.')[0]
# Import the correct PASTIS version used to construct a given posterior
# sample
pastis = importlib.import_module(modulename)
importlib.import_module('.MCMC.PASTIS_MCMC', package=pastis.__name__)
# Prepare output arrays
logprior = np.zeros(samples.shape[0])
for s in range(samples.shape[0]):
for parameter_index, full_param_name in enumerate(params):
# Modify input_dict
obj_name, param_name = full_param_name.split('_')
input_dict[obj_name][param_name][0] = samples[s, parameter_index]
# Construct chain state
chain_state, labeldict = \
pastis.MCMC.tools.state_constructor(input_dict)
# Compute prior distribution for this state
prior_probability = pastis.MCMC.priors.compute_priors(
priordict, labeldict)[0]
logprior[s] = np.log(prior_probability)
return logprior<|fim▁end|> | |
<|file_name|>index.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | import './Text1'; |
<|file_name|>CyberArkPAS_test.py<|end_file_name|><|fim▁begin|>import pytest
from CyberArkPAS import Client, add_user_command, get_users_command, \
update_user_command, add_safe_command, update_safe_command, get_list_safes_command, get_safe_by_name_command, \
add_safe_member_command, update_safe_member_command, list_safe_members_command, add_account_command, \
update_account_command, get_list_accounts_command, get_list_account_activity_command, fetch_incidents, \
get_account_details_command
from test_data.context import ADD_USER_CONTEXT, GET_USERS_CONTEXT, \
UPDATE_USER_CONTEXT, UPDATE_SAFE_CONTEXT, GET_LIST_SAFES_CONTEXT, GET_SAFE_BY_NAME_CONTEXT, ADD_SAFE_CONTEXT, \
ADD_SAFE_MEMBER_CONTEXT, UPDATE_SAFE_MEMBER_CONTEXT, LIST_SAFE_MEMBER_CONTEXT, ADD_ACCOUNT_CONTEXT, \
UPDATE_ACCOUNT_CONTEXT, GET_LIST_ACCOUNT_CONTEXT, GET_LIST_ACCOUNT_ACTIVITIES_CONTEXT, INCIDENTS, INCIDENTS_AFTER_FETCH, \
INCIDENTS_LIMITED_BY_MAX_SIZE, INCIDENTS_FILTERED_BY_SCORE, GET_ACCOUNT_CONTEXT
from test_data.http_resonses import ADD_USER_RAW_RESPONSE, \
UPDATE_USER_RAW_RESPONSE, GET_USERS_RAW_RESPONSE, ADD_SAFE_RAW_RESPONSE, UPDATE_SAFE_RAW_RESPONSE, \
GET_LIST_SAFES_RAW_RESPONSE, GET_SAFE_BY_NAME_RAW_RESPONSE, ADD_SAFE_MEMBER_RAW_RESPONSE, \
UPDATE_SAFE_MEMBER_RAW_RESPONSE, LIST_SAFE_MEMBER_RAW_RESPONSE, ADD_ACCOUNT_RAW_RESPONSE, \
UPDATE_ACCOUNT_RAW_RESPONSE, GET_LIST_ACCOUNT_RAW_RESPONSE, GET_LIST_ACCOUNT_ACTIVITIES_RAW_RESPONSE, \
GET_SECURITY_EVENTS_RAW_RESPONSE, GET_SECURITY_EVENTS_WITH_UNNECESSARY_INCIDENT_RAW_RESPONSE, \
GET_SECURITY_EVENTS_WITH_15_INCIDENT_RAW_RESPONSE, GET_ACCOUNT_RAW_RESPONSE
ADD_USER_ARGS = {
"change_password_on_the_next_logon": "true",
"description": "new user for test",
"email": "[email protected]",
"enable_user": "true",
"first_name": "user",
"last_name": "test",
"password": "12345Aa",
"password_never_expires": "false",
"profession": "testing integrations",
"username": "TestUser"
}
UPDATE_USER_ARGS = {
"change_password_on_the_next_logon": "true",
"description": "updated description",
"email": "[email protected]",
"enable_user": "true",
"first_name": "test1",
"last_name": "updated-name",
"password_never_expires": "false",
"profession": "test1",
"user_id": "123",
"username": "TestUser1"
}
GET_USER_ARGS = {
"filter": "filteroption",
"search": "searchoption"
}
ADD_SAFE_ARGS = {
"description": "safe for tests",
"number_of_days_retention": "100",
"safe_name": "TestSafe"
}
UPDATE_SAFE_ARGS = {
"description": "UpdatedSafe",
"number_of_days_retention": "150",
"safe_name": "TestSafe",
"safe_new_name": "UpdatedName"
}
GET_SAFE_BY_NAME_ARGS = {
"safe_name": "TestSafe"
}
ADD_SAFE_MEMBER_ARGS = {
"member_name": "TestUser",
"requests_authorization_level": "0",
"safe_name": "TestSafe"
}
UPDATE_SAFE_MEMBER_ARGS = {
"member_name": "TestUser",
"permissions": "UseAccounts",
"requests_authorization_level": "0",
"safe_name": "TestSafe"
}
LIST_SAFE_MEMBER_ARGS = {
"safe_name": "TestSafe"
}
ADD_ACCOUNT_ARGS = {
"account_name": "TestAccount1",
"address": "/",
"automatic_management_enabled": "true",
"password": "12345Aa",
"platform_id": "WinServerLocal",
"safe_name": "TestSafe",
"secret_type": "password",
"username": "TestUser"
}
UPDATE_ACCOUNT_ARGS = {
"account_id": "77_4",
"account_name": "NewName"
}
GET_ACCOUNT_ARGS = {
"account_id": "11_1",
}
GET_LIST_ACCOUNT_ARGS = {
"limit": "2",
"offset": "0"
}
GET_LIST_ACCOUNT_ACTIVITIES_ARGS = {
"account_id": "77_4"<|fim▁hole|>
@pytest.mark.parametrize('command, args, http_response, context', [
(add_user_command, ADD_USER_ARGS, ADD_USER_RAW_RESPONSE, ADD_USER_CONTEXT),
(update_user_command, UPDATE_USER_ARGS, UPDATE_USER_RAW_RESPONSE, UPDATE_USER_CONTEXT),
(get_users_command, {}, GET_USERS_RAW_RESPONSE, GET_USERS_CONTEXT),
(add_safe_command, ADD_SAFE_ARGS, ADD_SAFE_RAW_RESPONSE, ADD_SAFE_CONTEXT),
(update_safe_command, UPDATE_SAFE_ARGS, UPDATE_SAFE_RAW_RESPONSE, UPDATE_SAFE_CONTEXT),
(get_list_safes_command, {}, GET_LIST_SAFES_RAW_RESPONSE, GET_LIST_SAFES_CONTEXT),
(get_safe_by_name_command, GET_SAFE_BY_NAME_ARGS, GET_SAFE_BY_NAME_RAW_RESPONSE, GET_SAFE_BY_NAME_CONTEXT),
(add_safe_member_command, ADD_SAFE_MEMBER_ARGS, ADD_SAFE_MEMBER_RAW_RESPONSE, ADD_SAFE_MEMBER_CONTEXT),
(update_safe_member_command, UPDATE_SAFE_MEMBER_ARGS, UPDATE_SAFE_MEMBER_RAW_RESPONSE, UPDATE_SAFE_MEMBER_CONTEXT),
(list_safe_members_command, LIST_SAFE_MEMBER_ARGS, LIST_SAFE_MEMBER_RAW_RESPONSE, LIST_SAFE_MEMBER_CONTEXT),
(add_account_command, ADD_ACCOUNT_ARGS, ADD_ACCOUNT_RAW_RESPONSE, ADD_ACCOUNT_CONTEXT),
(update_account_command, UPDATE_ACCOUNT_ARGS, UPDATE_ACCOUNT_RAW_RESPONSE, UPDATE_ACCOUNT_CONTEXT),
(get_account_details_command, GET_ACCOUNT_ARGS, GET_ACCOUNT_RAW_RESPONSE, GET_ACCOUNT_CONTEXT),
(get_list_accounts_command, GET_LIST_ACCOUNT_ARGS, GET_LIST_ACCOUNT_RAW_RESPONSE, GET_LIST_ACCOUNT_CONTEXT),
(get_list_account_activity_command, GET_LIST_ACCOUNT_ACTIVITIES_ARGS, GET_LIST_ACCOUNT_ACTIVITIES_RAW_RESPONSE,
GET_LIST_ACCOUNT_ACTIVITIES_CONTEXT),
])
def test_cyberark_pas_commands(command, args, http_response, context, mocker):
"""Unit test
Given
- demisto args
- raw response of the http request
When
- mock the http request result
Then
- create the context
- validate the expected_result and the created context
"""
mocker.patch.object(Client, '_generate_token')
client = Client(server_url="https://api.cyberark.com/", username="user1", password="12345", use_ssl=False,
proxy=False, max_fetch=50)
mocker.patch.object(Client, '_http_request', return_value=http_response)
outputs = command(client, **args)
results = outputs.to_context()
assert results.get("EntryContext") == context
def test_fetch_incidents(mocker):
"""Unit test
Given
- raw response of the http request
When
- mock the http request result as 5 results that are sorted from the newest to the oldest
Then
- as defined in the demisto params - show only 2, those should be the oldest 2 available
- validate the incidents values
"""
mocker.patch.object(Client, '_generate_token')
client = Client(server_url="https://api.cyberark.com/", username="user1", password="12345", use_ssl=False,
proxy=False, max_fetch=50)
mocker.patch.object(Client, '_http_request', return_value=GET_SECURITY_EVENTS_RAW_RESPONSE)
_, incidents = fetch_incidents(client, {}, "3 days", "0", "2")
assert incidents == INCIDENTS
def test_fetch_incidents_with_an_incident_that_was_shown_before(mocker):
"""Unit test
Given
- demisto params
- raw response of the http request
When
- mock the http request result while one of the incidents was shown in the previous run
Then
- validate the incidents values, make sure the event that was shown before is not in
the incidents again
"""
mocker.patch.object(Client, '_generate_token')
client = Client(server_url="https://api.cyberark.com/", username="user1", password="12345", use_ssl=False,
proxy=False, max_fetch=50)
mocker.patch.object(Client, '_http_request', return_value=GET_SECURITY_EVENTS_WITH_UNNECESSARY_INCIDENT_RAW_RESPONSE)
# the last run dict is the same we would have got if we run the prev test before
last_run = {'time': 1594573600000, 'last_event_ids': '["5f0b3064e4b0ba4baf5c1113", "5f0b4320e4b0ba4baf5c2b05"]'}
_, incidents = fetch_incidents(client, last_run, "3 days", "0", "1")
assert incidents == INCIDENTS_AFTER_FETCH
def test_fetch_incidents_with_more_incidents_than_max_size(mocker):
"""Unit test
Given
- demisto params
- raw response of the http request
When
- mock the http request result while the result is 15 incidents and we only wish to see 5
Then
- validate the incidents values, make sure make sure that there are only 5 incidents and that there
are the oldest
"""
mocker.patch.object(Client, '_generate_token')
client = Client(server_url="https://api.cyberark.com/", username="user1", password="12345", use_ssl=False,
proxy=False, max_fetch=5)
mocker.patch.object(Client, '_http_request', return_value=GET_SECURITY_EVENTS_WITH_15_INCIDENT_RAW_RESPONSE)
_, incidents = fetch_incidents(client, {}, "3 days", "0", max_fetch="5")
assert len(incidents) == 5
assert incidents == INCIDENTS_LIMITED_BY_MAX_SIZE
def test_fetch_incidents_with_specific_score(mocker):
"""Unit test
Given
- demisto params
- raw response of the http request
When
- mock the http request result while the result is 15 incidents and we only wish to see 5
Then
- validate the incidents values, make sure make sure that there are only 5 incidents and that there
are the oldest
"""
mocker.patch.object(Client, '_generate_token')
client = Client(server_url="https://api.cyberark.com/", username="user1", password="12345", use_ssl=False,
proxy=False, max_fetch=10)
mocker.patch.object(Client, '_http_request', return_value=GET_SECURITY_EVENTS_WITH_15_INCIDENT_RAW_RESPONSE)
_, incidents = fetch_incidents(client, {}, "3 days", score="50", max_fetch="10")
assert len(incidents) == 3
assert incidents == INCIDENTS_FILTERED_BY_SCORE<|fim▁end|> | }
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! "Strided" data structures
mod col;
pub mod raw;<|fim▁hole|>pub unsized type Col<T> = raw::Slice<T>;<|fim▁end|> |
/// Strided column vector |
<|file_name|>NormalAdapter.java<|end_file_name|><|fim▁begin|>package zhou.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;<|fim▁hole|>import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by zzhoujay on 2015/7/22 0022.
*/
public class NormalAdapter extends RecyclerView.Adapter<NormalAdapter.Holder> {
private List<String> msg;
public NormalAdapter(List<String> msg) {
this.msg = msg;
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_normal, null);
Holder holder = new Holder(view);
return holder;
}
@Override
public void onBindViewHolder(Holder holder, int position) {
String m = msg.get(position);
holder.icon.setImageResource(R.mipmap.ic_launcher);
holder.text.setText(m);
}
@Override
public int getItemCount() {
return msg == null ? 0 : msg.size();
}
public static class Holder extends RecyclerView.ViewHolder {
public TextView text;
public ImageView icon;
public Holder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.item_text);
icon = (ImageView) itemView.findViewById(R.id.item_icon);
}
}
}<|fim▁end|> | |
<|file_name|>macro-use-bang.rs<|end_file_name|><|fim▁begin|>// build-pass (FIXME(62277): could be check-pass?)
// aux-build:test-macros.rs
<|fim▁hole|>fn main() {
identity!(println!("Hello, world!"));
}<|fim▁end|> | #[macro_use]
extern crate test_macros;
|
<|file_name|>test_pipmanager.py<|end_file_name|><|fim▁begin|># Copyright 2015 Facundo Batista, Nicolás Demarchi
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.
#
# For further info, check https://github.com/PyAr/fades
""" Tests for pip related code. """
import unittest
from unittest.mock import patch
import logassert
from fades.pipmanager import PipManager
from fades import helpers
class PipManagerTestCase(unittest.TestCase):
""" Check parsing for `pip show`. """
def setUp(self):
logassert.setup(self, 'fades.pipmanager')
def test_get_parsing_ok(self):
mocked_stdout = ['Name: foo',
'Version: 2.0.0',
'Location: ~/.local/share/fades/86cc492/lib/python3.4/site-packages',
'Requires: ']
mgr = PipManager('/usr/bin', pip_installed=True)
with patch.object(helpers, 'logged_exec') as mock:
mock.return_value = mocked_stdout
version = mgr.get_version('foo')
self.assertEqual(version, '2.0.0')
def test_get_parsing_error(self):
mocked_stdout = ['Name: foo',
'Release: 2.0.0',
'Location: ~/.local/share/fades/86cc492/lib/python3.4/site-packages',
'Requires: ']
mgr = PipManager('/usr/bin', pip_installed=True)
with patch.object(helpers, 'logged_exec') as mock:
version = mgr.get_version('foo')
mock.return_value = mocked_stdout
self.assertEqual(version, '')
self.assertLoggedError('Fades is having problems getting the installed version. '
'Run with -v or check the logs for details')
def test_real_case_levenshtein(self):
mocked_stdout = [
'Metadata-Version: 1.1',
'Name: python-Levenshtein',
'Version: 0.12.0',
'License: GPL',
]
mgr = PipManager('/usr/bin', pip_installed=True)
with patch.object(helpers, 'logged_exec') as mock:
mock.return_value = mocked_stdout
version = mgr.get_version('foo')
self.assertEqual(version, '0.12.0')
def test_install(self):
mgr = PipManager('/usr/bin', pip_installed=True)
with patch.object(helpers, 'logged_exec') as mock:
mgr.install('foo')
mock.assert_called_with(['/usr/bin/pip', 'install', 'foo'])
def test_install_with_options(self):
mgr = PipManager('/usr/bin', pip_installed=True, options=['--bar baz'])
with patch.object(helpers, 'logged_exec') as mock:<|fim▁hole|> mgr = PipManager('/usr/bin', pip_installed=True, options=['--bar=baz'])
with patch.object(helpers, 'logged_exec') as mock:
mgr.install('foo')
mock.assert_called_with(['/usr/bin/pip', 'install', 'foo', '--bar=baz'])
def test_install_raise_error(self):
mgr = PipManager('/usr/bin', pip_installed=True)
with patch.object(helpers, 'logged_exec') as mock:
mock.side_effect = Exception("Kapow!")
with self.assertRaises(Exception):
mgr.install('foo')
self.assertLoggedError("Error installing foo: Kapow!")
def test_install_without_pip(self):
mgr = PipManager('/usr/bin', pip_installed=False)
with patch.object(helpers, 'logged_exec') as mocked_exec:
with patch.object(mgr, '_brute_force_install_pip') as mocked_install_pip:
mgr.install('foo')
self.assertEqual(mocked_install_pip.call_count, 1)
mocked_exec.assert_called_with(['/usr/bin/pip', 'install', 'foo'])<|fim▁end|> | mgr.install('foo')
mock.assert_called_with(['/usr/bin/pip', 'install', 'foo', '--bar', 'baz'])
def test_install_with_options_using_equal(self): |
<|file_name|>helper.py<|end_file_name|><|fim▁begin|>import codecs
import logging
import random
def import_url(path,lo,hi):
with codecs.open(path,encoding='utf-8') as f:
string = f.read()
arr = string.split('\n')
if not lo:
lo=0
if not hi:
hi=len(arr)
arr=arr[lo:hi]
url_arr = []
want = range(lo,hi)
# returns url and its number
for i,line in enumerate(arr):
if i+lo in want:
url = line.split(':')[0]
num = str(i+lo).zfill(5)
url_arr.append((num,url))
return url_arr
def import_proxy(path,mode):
with open(path) as f:
string = f.read()
arr = string.split('\n')
del(arr[-1])
proxy_arr = []
for line in arr:
if mode=='comma':
line_arr=line.split(',')
addr=line_arr[0]
port=line_arr[1]<|fim▁hole|> dic['https'] = 'https://' + line
proxy_arr.append(dic)
random.shuffle(proxy_arr)
return proxy_arr
def setLogger(path):
console_logger = logging.getLogger('consoleLogger')
hdlr = logging.FileHandler('./console.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(formatter)
console_logger.addHandler(hdlr)
console_logger.addHandler(consoleHandler)
console_logger.setLevel(logging.DEBUG)
result_logger = logging.getLogger('resultLogger')
hdlr2 = logging.FileHandler('./'+path,encoding='utf-8')
formatter2 = logging.Formatter('%(message)s')
hdlr2.setFormatter(formatter2)
result_logger.addHandler(hdlr2)
result_logger.setLevel(logging.DEBUG)
return console_logger, result_logger<|fim▁end|> | line=addr+':'+port
dic = {}
dic['http'] = 'http://' + line |
<|file_name|>variant-struct.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 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<|fim▁hole|>pub enum Foo {
Bar {
qux: (),
}
}<|fim▁end|> | // <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.
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>'''WARCAT: Web ARChive (WARC) Archiving Tool
Tool and library for handling Web ARChive (WARC) files.<|fim▁hole|>'''
from .version import *<|fim▁end|> | |
<|file_name|>opengl_info.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2020-2021 Florian Bruhin (The Compiler) <[email protected]>
# This file is part of qutebrowser.
#
# qutebrowser 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.
#
# qutebrowser 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 qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""Show information about the OpenGL setup."""
from PyQt5.QtGui import (QOpenGLContext, QOpenGLVersionProfile,
QOffscreenSurface, QGuiApplication)
app = QGuiApplication([])
surface = QOffscreenSurface()
surface.create()
ctx = QOpenGLContext()
ok = ctx.create()
assert ok
ok = ctx.makeCurrent(surface)
assert ok
print(f"GLES: {ctx.isOpenGLES()}")
vp = QOpenGLVersionProfile()
vp.setVersion(2, 0)
vf = ctx.versionFunctions(vp)
print(f"Vendor: {vf.glGetString(vf.GL_VENDOR)}")
print(f"Renderer: {vf.glGetString(vf.GL_RENDERER)}")
print(f"Version: {vf.glGetString(vf.GL_VERSION)}")<|fim▁hole|>
ctx.doneCurrent()<|fim▁end|> | print(f"Shading language version: {vf.glGetString(vf.GL_SHADING_LANGUAGE_VERSION)}") |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! A Collection of Header implementations for common HTTP Headers.
//!
//! ## Mime
//!
//! Several header fields use MIME values for their contents. Keeping with the
//! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate
//! is used, such as `ContentType(pub Mime)`.
pub use self::accept::Accept;
pub use self::allow::Allow;
pub use self::authorization::Authorization;
pub use self::cache_control::CacheControl;
pub use self::cookie::Cookies;
pub use self::connection::Connection;
pub use self::content_length::ContentLength;
pub use self::content_type::ContentType;
pub use self::date::Date;
pub use self::etag::Etag;
pub use self::expires::Expires;
pub use self::host::Host;
pub use self::last_modified::LastModified;
pub use self::if_modified_since::IfModifiedSince;
pub use self::location::Location;
pub use self::transfer_encoding::TransferEncoding;
pub use self::upgrade::Upgrade;
pub use self::user_agent::UserAgent;
pub use self::server::Server;
pub use self::set_cookie::SetCookie;
macro_rules! bench_header(
($name:ident, $ty:ty, $value:expr) => {
#[cfg(test)]
mod $name {
use test::Bencher;
use super::*;
use header::{Header, HeaderFormatter};
#[bench]
fn bench_parse(b: &mut Bencher) {
let val = $value;
b.iter(|| {
let _: $ty = Header::parse_header(val[]).unwrap();
});
}
#[bench]
fn bench_format(b: &mut Bencher) {
let val: $ty = Header::parse_header($value[]).unwrap();
let fmt = HeaderFormatter(&val);
b.iter(|| {
format!("{}", fmt);
});
}
}
}
)
macro_rules! deref(
($from:ty -> $to:ty) => {
impl Deref<$to> for $from {
fn deref<'a>(&'a self) -> &'a $to {
&self.0
}
}
impl DerefMut<$to> for $from {
fn deref_mut<'a>(&'a mut self) -> &'a mut $to {
&mut self.0
}
}
}
)
/// Exposes the Accept header.
pub mod accept;
/// Exposes the Allow header.
pub mod allow;<|fim▁hole|>/// Exposes the CacheControl header.
pub mod cache_control;
/// Exposes the Cookie header.
pub mod cookie;
/// Exposes the Connection header.
pub mod connection;
/// Exposes the ContentLength header.
pub mod content_length;
/// Exposes the ContentType header.
pub mod content_type;
/// Exposes the Date header.
pub mod date;
/// Exposes the Etag header.
pub mod etag;
/// Exposes the Expires header.
pub mod expires;
/// Exposes the Host header.
pub mod host;
/// Exposes the LastModified header.
pub mod last_modified;
/// Exposes the If-Modified-Since header.
pub mod if_modified_since;
/// Exposes the Location header.
pub mod location;
/// Exposes the Server header.
pub mod server;
/// Exposes the Set-Cookie header.
pub mod set_cookie;
/// Exposes the TransferEncoding header.
pub mod transfer_encoding;
/// Exposes the Upgrade header.
pub mod upgrade;
/// Exposes the UserAgent header.
pub mod user_agent;
pub mod util;<|fim▁end|> |
/// Exposes the Authorization header.
pub mod authorization;
|
<|file_name|>lang.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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.
//! Runtime calls emitted by the compiler.
use cast::transmute;
use libc::{c_char, c_uchar, c_void, size_t, uintptr_t, c_int};
use str;
use sys;
use rt::{context, OldTaskContext};
use rt::task::Task;
use rt::local::Local;
use rt::borrowck;
#[allow(non_camel_case_types)]
pub type rust_task = c_void;
pub mod rustrt {
use unstable::lang::rust_task;
use libc::{c_char, uintptr_t};
pub extern {
#[rust_stack]
unsafe fn rust_upcall_malloc(td: *c_char, size: uintptr_t) -> *c_char;
#[rust_stack]
unsafe fn rust_upcall_free(ptr: *c_char);
#[fast_ffi]
unsafe fn rust_upcall_malloc_noswitch(td: *c_char,
size: uintptr_t)
-> *c_char;
#[rust_stack]
fn rust_try_get_task() -> *rust_task;
fn rust_dbg_breakpoint();
}
}
#[lang="fail_"]
pub fn fail_(expr: *c_char, file: *c_char, line: size_t) -> ! {
sys::begin_unwind_(expr, file, line);
}
#[lang="fail_bounds_check"]
pub fn fail_bounds_check(file: *c_char, line: size_t,
index: size_t, len: size_t) {
let msg = fmt!("index out of bounds: the len is %d but the index is %d",
len as int, index as int);
do str::as_buf(msg) |p, _len| {
fail_(p as *c_char, file, line);
}
}
#[lang="malloc"]
pub unsafe fn local_malloc(td: *c_char, size: uintptr_t) -> *c_char {
match context() {
OldTaskContext => {
return rustrt::rust_upcall_malloc_noswitch(td, size);
}
_ => {
let mut alloc = ::ptr::null();
do Local::borrow::<Task,()> |task| {
rtdebug!("task pointer: %x, heap pointer: %x",
to_uint(task),
to_uint(&task.heap));
alloc = task.heap.alloc(td as *c_void, size as uint) as *c_char;
}
return alloc;
}
}
}
// NB: Calls to free CANNOT be allowed to fail, as throwing an exception from
// inside a landing pad may corrupt the state of the exception handler. If a
// problem occurs, call exit instead.
#[lang="free"]
pub unsafe fn local_free(ptr: *c_char) {
::rt::local_heap::local_free(ptr);
}
#[lang="borrow_as_imm"]
#[inline]
pub unsafe fn borrow_as_imm(a: *u8, file: *c_char, line: size_t) -> uint {
borrowck::borrow_as_imm(a, file, line)
}
#[lang="borrow_as_mut"]
#[inline]
pub unsafe fn borrow_as_mut(a: *u8, file: *c_char, line: size_t) -> uint {
borrowck::borrow_as_mut(a, file, line)
}
#[lang="record_borrow"]
pub unsafe fn record_borrow(a: *u8, old_ref_count: uint,
file: *c_char, line: size_t) {
borrowck::record_borrow(a, old_ref_count, file, line)
}
#[lang="unrecord_borrow"]
pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint,
file: *c_char, line: size_t) {
borrowck::unrecord_borrow(a, old_ref_count, file, line)
}
#[lang="return_to_mut"]
#[inline]
pub unsafe fn return_to_mut(a: *u8, orig_ref_count: uint,
file: *c_char, line: size_t) {
borrowck::return_to_mut(a, orig_ref_count, file, line)
}
#[lang="check_not_borrowed"]
#[inline]
pub unsafe fn check_not_borrowed(a: *u8,
file: *c_char,
line: size_t) {
borrowck::check_not_borrowed(a, file, line)
}
#[lang="strdup_uniq"]
#[inline]
pub unsafe fn strdup_uniq(ptr: *c_uchar, len: uint) -> ~str {
str::raw::from_buf_len(ptr, len)
}
#[lang="annihilate"]
pub unsafe fn annihilate() {
::cleanup::annihilate()
}
#[lang="start"]
pub fn start(main: *u8, argc: int, argv: **c_char,
crate_map: *u8) -> int {
use rt;
use os;
unsafe {
let use_old_rt = os::getenv("RUST_NEWRT").is_none();<|fim▁hole|> return rust_start(main as *c_void, argc as c_int, argv,
crate_map as *c_void) as int;
} else {
return do rt::start(argc, argv as **u8, crate_map) {
let main: extern "Rust" fn() = transmute(main);
main();
};
}
}
extern {
fn rust_start(main: *c_void, argc: c_int, argv: **c_char,
crate_map: *c_void) -> c_int;
}
}<|fim▁end|> | if use_old_rt { |
<|file_name|>mention.py<|end_file_name|><|fim▁begin|>from typing import Optional, Set, Text
import re
<|fim▁hole|>user_group_mentions = r'(?<![^\s\'\"\(,:<])@(\*[^\*]+\*)'
wildcards = ['all', 'everyone']
def user_mention_matches_wildcard(mention: Text) -> bool:
return mention in wildcards
def extract_name(s: Text) -> Optional[Text]:
if s.startswith("**") and s.endswith("**"):
name = s[2:-2]
if name in wildcards:
return None
return name
# We don't care about @all or @everyone
return None
def possible_mentions(content: Text) -> Set[Text]:
matches = re.findall(find_mentions, content)
names_with_none = (extract_name(match) for match in matches)
names = {name for name in names_with_none if name}
return names
def extract_user_group(matched_text: Text) -> Text:
return matched_text[1:-1]
def possible_user_group_mentions(content: Text) -> Set[Text]:
matches = re.findall(user_group_mentions, content)
return {extract_user_group(match) for match in matches}<|fim▁end|> | # Match multi-word string between @** ** or match any one-word
# sequences after @
find_mentions = r'(?<![^\s\'\"\(,:<])@(\*\*[^\*]+\*\*|all|everyone)' |
<|file_name|>renderer_preferences_util.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_preferences_util.h"
#include <stdint.h>
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/net/convert_explicitly_allowed_network_ports_pref.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/login/demo_mode/demo_session.h"
#endif
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/pref_names.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/renderer_preferences_util.h"
#include "media/media_buildflags.h"
#include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
#include "third_party/blink/public/public_buildflags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/ui_base_features.h"
#if defined(TOOLKIT_VIEWS)
#include "ui/views/controls/textfield/textfield.h"
#endif
#if defined(OS_MAC)
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#include "content/nw/src/common/nw_content_common_hooks.h"
namespace {
// Parses a string |range| with a port range in the form "<min>-<max>".
// If |range| is not in the correct format or contains an invalid range, zero
// is written to |min_port| and |max_port|.
// TODO(guidou): Consider replacing with remoting/protocol/port_range.cc
void ParsePortRange(const std::string& range,
uint16_t* min_port,
uint16_t* max_port) {
*min_port = 0;
*max_port = 0;
if (range.empty())
return;
size_t separator_index = range.find('-');
if (separator_index == std::string::npos)
return;
std::string min_port_string, max_port_string;
base::TrimWhitespaceASCII(range.substr(0, separator_index), base::TRIM_ALL,
&min_port_string);
base::TrimWhitespaceASCII(range.substr(separator_index + 1), base::TRIM_ALL,
&max_port_string);
unsigned min_port_uint, max_port_uint;
if (!base::StringToUint(min_port_string, &min_port_uint) ||
!base::StringToUint(max_port_string, &max_port_uint)) {
return;
}
if (min_port_uint == 0 || min_port_uint > max_port_uint ||
max_port_uint > UINT16_MAX) {
return;
}
*min_port = static_cast<uint16_t>(min_port_uint);
*max_port = static_cast<uint16_t>(max_port_uint);
}
// Extracts the string representation of URLs allowed for local IP exposure.
std::vector<std::string> GetLocalIpsAllowedUrls(
const base::ListValue* allowed_urls) {
std::vector<std::string> ret;
if (allowed_urls) {
const auto& urls = allowed_urls->GetList();
for (const auto& url : urls)
ret.push_back(url.GetString());
}
return ret;
}
std::string GetLanguageListForProfile(Profile* profile,
const std::string& language_list) {
if (profile->IsOffTheRecord()) {
// In incognito mode return only the first language.
return language::GetFirstLanguage(language_list);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// On Chrome OS, if in demo mode, add the demo mode private language list.
if (ash::DemoSession::IsDeviceInDemoMode()) {
return language_list + "," + ash::DemoSession::GetAdditionalLanguageList();
}
#endif
return language_list;
}
} // namespace
namespace renderer_preferences_util {
void UpdateFromSystemSettings(blink::RendererPreferences* prefs,
Profile* profile) {
const PrefService* pref_service = profile->GetPrefs();
prefs->accept_languages = GetLanguageListForProfile(
profile, pref_service->GetString(language::prefs::kAcceptLanguages));
prefs->enable_referrers = pref_service->GetBoolean(prefs::kEnableReferrers);
prefs->enable_do_not_track =
pref_service->GetBoolean(prefs::kEnableDoNotTrack);
prefs->enable_encrypted_media =
pref_service->GetBoolean(prefs::kEnableEncryptedMedia);
prefs->webrtc_ip_handling_policy = std::string();
#if !defined(OS_ANDROID)
prefs->caret_browsing_enabled =
pref_service->GetBoolean(prefs::kCaretBrowsingEnabled);
content::BrowserAccessibilityState::GetInstance()->SetCaretBrowsingState(
prefs->caret_browsing_enabled);
#endif
if (prefs->webrtc_ip_handling_policy.empty()) {
prefs->webrtc_ip_handling_policy =
pref_service->GetString(prefs::kWebRTCIPHandlingPolicy);
}
std::string webrtc_udp_port_range =
pref_service->GetString(prefs::kWebRTCUDPPortRange);
ParsePortRange(webrtc_udp_port_range, &prefs->webrtc_udp_min_port,
&prefs->webrtc_udp_max_port);
const base::ListValue* allowed_urls =
pref_service->GetList(prefs::kWebRtcLocalIpsAllowedUrls);
prefs->webrtc_local_ips_allowed_urls = GetLocalIpsAllowedUrls(allowed_urls);
prefs->webrtc_allow_legacy_tls_protocols =
pref_service->GetBoolean(prefs::kWebRTCAllowLegacyTLSProtocols);
#if defined(USE_AURA)
prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE);
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
// This color is 0x544d90fe modulated with 0xffffff.
prefs->active_selection_bg_color = SkColorSetRGB(0xCB, 0xE4, 0xFA);
prefs->active_selection_fg_color = SK_ColorBLACK;
prefs->inactive_selection_bg_color = SkColorSetRGB(0xEA, 0xEA, 0xEA);
prefs->inactive_selection_fg_color = SK_ColorBLACK;
#endif
#endif
#if defined(TOOLKIT_VIEWS)
prefs->caret_blink_interval = views::Textfield::GetCaretBlinkInterval();
#endif
#if defined(OS_MAC)
base::TimeDelta interval;
if (ui::TextInsertionCaretBlinkPeriod(&interval))
prefs->caret_blink_interval = interval;
#endif
<|fim▁hole|> if (linux_ui) {
if (ThemeServiceFactory::GetForProfile(profile)->UsingSystemTheme()) {
prefs->focus_ring_color = linux_ui->GetFocusRingColor();
prefs->active_selection_bg_color = linux_ui->GetActiveSelectionBgColor();
prefs->active_selection_fg_color = linux_ui->GetActiveSelectionFgColor();
prefs->inactive_selection_bg_color =
linux_ui->GetInactiveSelectionBgColor();
prefs->inactive_selection_fg_color =
linux_ui->GetInactiveSelectionFgColor();
}
// If we have a linux_ui object, set the caret blink interval regardless of
// whether we're in native theme mode.
prefs->caret_blink_interval = linux_ui->GetCursorBlinkInterval();
}
#endif
#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \
defined(OS_WIN)
content::UpdateFontRendererPreferencesFromSystemSettings(prefs);
#endif
#if !defined(OS_MAC)
prefs->plugin_fullscreen_allowed =
pref_service->GetBoolean(prefs::kFullscreenAllowed);
#endif
PrefService* local_state = g_browser_process->local_state();
if (local_state) {
prefs->allow_cross_origin_auth_prompt =
local_state->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
prefs->explicitly_allowed_network_ports =
ConvertExplicitlyAllowedNetworkPortsPref(local_state);
}
#if defined(OS_MAC)
prefs->focus_ring_color = SkColorSetRGB(0x00, 0x5F, 0xCC);
#else
prefs->focus_ring_color = SkColorSetRGB(0x10, 0x10, 0x10);
#endif
std::string user_agent;
if (nw::GetUserAgentFromManifest(&user_agent))
prefs->user_agent_override.ua_string_override = user_agent;
}
} // namespace renderer_preferences_util<|fim▁end|> | #if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
views::LinuxUI* linux_ui = views::LinuxUI::instance(); |
<|file_name|>TorneoGolfWindow.js<|end_file_name|><|fim▁begin|>function TorneoGolfWindow(Window) {
window1 = Titanium.UI.createWindow({
tabBarHidden : true,
backgroundColor : "white",
width : '100%',
height : '100%',
layout : 'vertical'
});
table = Ti.UI.createTableView({
width : '90%',
height : '100%'
});
scrollView_1 = Titanium.UI.createView({
id : "scrollView_1",
backgroundImage : '/images/background.png',
height : '100%',
width : '100%',
layout : 'vertical'
});
scrollView_1.add(table);
imageViewBar = Titanium.UI.createView({
id : "imageViewBar",
backgroundColor : Ti.App.Properties.getString('viewcolor'),
height : 80,
left : 0,
top : 0,
width : '100%',
layout : 'horizontal'
});
imageView = Titanium.UI.createImageView({
id : "imageView",
image : "/images/icongolf.png",
width : 60,
height : 60,
top : 7,
right : 3
});
imageViewBar.add(imageView);
labelTitulo = Titanium.UI.createLabel({
id : "labelTitulo",
height : 'auto',
width : '70%',
text : L('golf'),
font : {
fontSize : '22dp'
},
color : 'white',
textAlign : Ti.UI.TEXT_ALIGNMENT_CENTER
});
imageViewBar.add(labelTitulo);
buttonClose = Titanium.UI.createImageView({
id : "buttonClose",
image : "/images/close.png",
width : 30,
height : 30,
top : 25
});
imageViewBar.add(buttonClose);
window1.add(imageViewBar);
window1.add(scrollView_1);
function populateTable() {
var data = [];
var row = Titanium.UI.createTableViewRow({
id : 2,
title : 'Horarios',
leftImage : '/images/horarios.png',
isparent : true,
opened : false,
hasChild : false,
font : {
fontSize : '22dp'
},
color : 'black'
});
data.push(row);
var row = Titanium.UI.createTableViewRow({
id : 3,
title : 'Mapa',
leftImage : '/images/mapa.png',
isparent : true,
opened : false,
hasChild : false,
font : {
fontSize : '22dp'
},
color : 'black'
});
data.push(row);
table.setData(data);
}
populateTable();
table.addEventListener('click', function(e) {
if (e.rowData.id == 2) {
var Window;
var mainWindow = require("ui/handheld/golf/HorariosWindow");
new mainWindow(Window).open();
} else if (e.rowData.id == 3) {
var Window;
var mainWindow = require("ui/handheld/mapa/MapaWindow");
new mainWindow(Window).open();
}
});
buttonClose.addEventListener('click', function(e) {
Ti.Media.vibrate();
var Window;
var mainWindow = require("ui/handheld/MainWindow");
new mainWindow(Window).open();
});
<|fim▁hole|> window1.addEventListener('android:back', function(e) {
Ti.Media.vibrate();
var Window;
var mainWindow = require("ui/handheld/MainWindow");
new mainWindow(Window).open();
});
return window1;
}
module.exports = TorneoGolfWindow;<|fim▁end|> | |
<|file_name|>01.0_import_su.py<|end_file_name|><|fim▁begin|>import PySeis as ps
import numpy as np
import pylab
#import dataset
input = ps.io.su.SU("./data/sample.su")
input.read("./data/raw.npy")
#initialise dataset
#~ data, params = toolbox.initialise("geometries.su")
#trim data
#~ params['ns'] = 1500
#~ data = toolbox.slice(data, None, **params)
#~ data.tofile("geom_short.su")
#initialise dataset
#data, params = toolbox.initialise("geom_short.su")
#agc
#~ toolbox.agc(data, None, **params)
#params['gamma'] = 1.5
#toolbox.tar(data, None, **params)
#kills = [270, 300, 374, 614] #fldr
#mask = toolbox.build_mask(data['fldr'], kills)
<|fim▁hole|>#data = data[mask]
#data.tofile("prepro.su")
#display
#~ params['primary'] = 'fldr'
#~ params['secondary'] = 'tracf'
#~ params['wiggle'] = True
#~ toolbox.display(data, **params)
#~ pylab.show()<|fim▁end|> | |
<|file_name|>amtrak.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
amtrak
Parse a trip itinerary of amtrak services copied into a text file.
Running the file will take a trip.txt file and output a .json with one record
for each amtrak service in the trip. You can also use the main method of the
module. Both cases, the first parameter would be the input and the second one
would be the output.
Example:
$ python amtrak.py
$ python amtrak.py trip.txt
$ python amtrak.py trip.txt /json/amtrak-trip.json
import amtrak
amtrak.main()
amtrak.main("trip.txt")
amtrak.main("trip.txt", "/json/amtrak-trip.json")
See the "trip.txt" file in this directory for an example of the type of amtrak
itinerary e-mail that is supported for the parsers in this repo.
"""
from __future__ import unicode_literals
import copy
import json
import arrow
import sys
from modules import parsers
class AmtrakServiceParser(object):
"""Parse Amtrak service information from confirmation email lines.<|fim▁hole|>
Attributes:
name (str): Name of the service.
departure_station (str): Station where the service starts.
departure_state (str): State where the service starts.
departure_city (str): City where the service starts.
departure_date (str): Date and time when the service starts.
arrival_station (str): Station where the service ends.
arrival_state (str): State where the service ends.
arrival_city (str): City where the service ends.
arrival_date (str): Date and time when the service ends.
accommodation (str): Type of accommodation.
"""
def __init__(self):
self.name = None
self.departure_station = None
self.departure_state = None
self.departure_city = None
self.departure_date = None
self.arrival_station = None
self.arrival_state = None
self.arrival_city = None
self.arrival_date = None
self.accommodation = None
def parse(self, line):
"""Parse one line of the amtrak itinerary.
It will add information to the parser until last item has been parsed,
then it will return a new record and clean the parser from any data.
Args:
line (str): A line of an amtrak itinerary.
Returns:
dict: All the information parsed of a single service.
Example:
{"name": "49 Lake Shore Ltd.",
"departure_station": "New York (Penn Station), New York",
"departure_state": "New York",
"departure_city": "New York",
"departure_date": '2015-05-18T15:40:00+00:00',
"arrival_station": "Chicago (Chicago Union Station), Illinois",
"arrival_state": "Illinois",
"arrival_city": "Chicago",
"arrival_date": '2015-05-19T09:45:00+00:00',
"accommodation": "1 Reserved Coach Seat"}
"""
for parser in parsers.get_parsers():
if parser.accepts(line):
key, value = parser.parse(line)
if not key == "date":
self.__dict__[key] = value
# date could be departure or arrival, departure is always first
else:
if not self.departure_date:
self.departure_date = value.isoformat()
else:
self.arrival_date = value.isoformat()
if self._service_info_complete():
RV = copy.copy(self.__dict__)
self.__init__()
else:
RV = None
return RV
def _service_info_complete(self):
for value in self.__dict__.values():
if not value:
return False
return True
def parse_services(filename='trip.txt'):
"""Parse all services from an amtrak itinerary.
Args:
filename (str): Path to a text file with an amtrak itinerary.
Yields:
dict: New record with data about a service.
"""
parser = AmtrakServiceParser()
with open(filename, 'rb') as f:
for line in f.readlines():
new_record = parser.parse(line)
if new_record:
yield new_record
def add_calc_fields(service):
"""Write the duration of a service into an new field."""
service["duration"] = _calc_duration(service)
return service
def _calc_duration(service):
"""Calculates the duration of a service."""
duration = arrow.get(service["arrival_date"]) - \
arrow.get(service["departure_date"])
return round(duration.total_seconds() / 60 / 60, 1)
def write_services_to_json(services, file_name="./json/amtrak-trip.json"):
"""Write parsed services to a json file.
Args:
services (dict): Parsed services.
file_name (str): Path of the json file to write in.
"""
with open(file_name, "w") as f:
f.write(json.dumps(services, indent=4))
def main(filename='trip.txt', file_name="./json/amtrak-trip.json"):
services = [add_calc_fields(service) for service
in parse_services(filename)]
write_services_to_json(services, file_name)
if __name__ == '__main__':
if len(sys.argv) == 2:
main(sys.argv[1])
elif len(sys.argv) == 3:
main(sys.argv[1], sys.argv[2])
else:
main()<|fim▁end|> | |
<|file_name|>phraseview.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "globals.h"
#include "mainwindow.h"
#include "messagemodel.h"
#include "phrase.h"
#include "phraseview.h"
#include "phrasemodel.h"
#include "simtexth.h"
#include <QHeaderView>
#include <QKeyEvent>
#include <QSettings>
#include <QTreeView>
#include <QWidget>
#include <QDebug>
QT_BEGIN_NAMESPACE
// Maximum number of guesses to display
static const int MaxCandidates = 5;
static QString phraseViewHeaderKey()
{
return settingPath("PhraseViewHeader");
}
PhraseView::PhraseView(MultiDataModel *model, QList<QHash<QString, QList<Phrase *> > > *phraseDict, QWidget *parent)
: QTreeView(parent),
m_dataModel(model),
m_phraseDict(phraseDict),
m_modelIndex(-1),
m_doGuesses(true)
{
setObjectName(QLatin1String("phrase list view"));
m_phraseModel = new PhraseModel(this);
setModel(m_phraseModel);
setAlternatingRowColors(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
setRootIsDecorated(false);
setItemsExpandable(false);
for (int i = 0; i < 10; i++)
(void) new GuessShortcut(i, this, SLOT(guessShortcut(int)));
header()->setSectionResizeMode(QHeaderView::Interactive);
header()->setSectionsClickable(true);
header()->restoreState(QSettings().value(phraseViewHeaderKey()).toByteArray());
connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(selectPhrase(QModelIndex)));
}
PhraseView::~PhraseView()
{
QSettings().setValue(phraseViewHeaderKey(), header()->saveState());
deleteGuesses();
}
void PhraseView::toggleGuessing()
{
m_doGuesses = !m_doGuesses;
update();
}
void PhraseView::update()
{
setSourceText(m_modelIndex, m_sourceText);
}
void PhraseView::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex index = indexAt(event->pos());
if (!index.isValid())
return;
QMenu *contextMenu = new QMenu(this);
QAction *insertAction = new QAction(tr("Insert"), contextMenu);
connect(insertAction, SIGNAL(triggered()), this, SLOT(selectPhrase()));
QAction *editAction = new QAction(tr("Edit"), contextMenu);
connect(editAction, SIGNAL(triggered()), this, SLOT(editPhrase()));
editAction->setEnabled(model()->flags(index) & Qt::ItemIsEditable);
contextMenu->addAction(insertAction);
contextMenu->addAction(editAction);
contextMenu->exec(event->globalPos());
event->accept();
}
void PhraseView::mouseDoubleClickEvent(QMouseEvent *event)
{
QModelIndex index = indexAt(event->pos());
if (!index.isValid())
return;
emit phraseSelected(m_modelIndex, m_phraseModel->phrase(index)->target());
event->accept();
}
void PhraseView::guessShortcut(int key)
{
foreach (const Phrase *phrase, m_phraseModel->phraseList())
if (phrase->shortcut() == key) {
emit phraseSelected(m_modelIndex, phrase->target());
return;
}
}
void PhraseView::selectPhrase(const QModelIndex &index)
{
emit phraseSelected(m_modelIndex, m_phraseModel->phrase(index)->target());
}
void PhraseView::selectPhrase()
{
emit phraseSelected(m_modelIndex, m_phraseModel->phrase(currentIndex())->target());
}
void PhraseView::editPhrase()
{
edit(currentIndex());
}
static CandidateList similarTextHeuristicCandidates(MultiDataModel *model, int mi,
const char *text, int maxCandidates)
{
QList<int> scores;
CandidateList candidates;
StringSimilarityMatcher stringmatcher(QString::fromLatin1(text));
for (MultiDataModelIterator it(model, mi); it.isValid(); ++it) {
MessageItem *m = it.current();
if (!m)
continue;
TranslatorMessage mtm = m->message();
if (mtm.type() == TranslatorMessage::Unfinished
|| mtm.translation().isEmpty())
continue;
QString s = m->text();
int score = stringmatcher.getSimilarityScore(s);
if (candidates.count() == maxCandidates && score > scores[maxCandidates - 1])
candidates.removeLast();
if (candidates.count() < maxCandidates && score >= textSimilarityThreshold ) {
Candidate cand(s, mtm.translation());
int i;
for (i = 0; i < candidates.size(); ++i) {
if (score >= scores.at(i)) {
if (score == scores.at(i)) {
if (candidates.at(i) == cand)
goto continue_outer_loop;
} else {
break;
}
}
}
scores.insert(i, score);
candidates.insert(i, cand);
}
continue_outer_loop:
;
}
return candidates;
}
void PhraseView::setSourceText(int model, const QString &sourceText)
{
m_modelIndex = model;
m_sourceText = sourceText;
m_phraseModel->removePhrases();
deleteGuesses();
if (model < 0)
return;
foreach (Phrase *p, getPhrases(model, sourceText))
m_phraseModel->addPhrase(p);
if (!sourceText.isEmpty() && m_doGuesses) {
CandidateList cl = similarTextHeuristicCandidates(m_dataModel, model,
sourceText.toLatin1(), MaxCandidates);
int n = 0;
foreach (const Candidate &candidate, cl) {
QString def;
if (n < 9)
def = tr("Guess (%1)").arg(QKeySequence(Qt::CTRL | (Qt::Key_0 + (n + 1))).toString(QKeySequence::NativeText));
else
def = tr("Guess");<|fim▁hole|> m_guesses.append(guess);
m_phraseModel->addPhrase(guess);
++n;
}
}
}
QList<Phrase *> PhraseView::getPhrases(int model, const QString &source)
{
QList<Phrase *> phrases;
QString f = MainWindow::friendlyString(source);
QStringList lookupWords = f.split(QLatin1Char(' '));
foreach (const QString &s, lookupWords) {
if (m_phraseDict->at(model).contains(s)) {
foreach (Phrase *p, m_phraseDict->at(model).value(s)) {
if (f.contains(MainWindow::friendlyString(p->source())))
phrases.append(p);
}
}
}
return phrases;
}
void PhraseView::deleteGuesses()
{
qDeleteAll(m_guesses);
m_guesses.clear();
}
QT_END_NAMESPACE<|fim▁end|> | Phrase *guess = new Phrase(candidate.source, candidate.target, def, n); |
<|file_name|>RenderingRequestCaller.java<|end_file_name|><|fim▁begin|><|fim▁hole|> public void available(RenderingRequest request);
}<|fim▁end|> | package com.xjt.crazypic.edit.pipeline;
public interface RenderingRequestCaller { |
<|file_name|>scrape.rs<|end_file_name|><|fim▁begin|>//! Messaging primitives for scraping.
use std::borrow::Cow;
use std::io::{self, Write};
use bip_util::bt::{self, InfoHash};
use bip_util::convert;
use nom::{IResult, Needed, be_i32};
const SCRAPE_STATS_BYTES: usize = 12;
/// Status for a given InfoHash.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ScrapeStats {
seeders: i32,
downloaded: i32,
leechers: i32,
}
impl ScrapeStats {
/// Create a new ScrapeStats.
pub fn new(seeders: i32, downloaded: i32, leechers: i32) -> ScrapeStats {
ScrapeStats {
seeders: seeders,
downloaded: downloaded,
leechers: leechers,
}
}
/// Construct a ScrapeStats from the given bytes.
fn from_bytes(bytes: &[u8]) -> IResult<&[u8], ScrapeStats> {
parse_stats(bytes)
}
/// Current number of seeders.
pub fn num_seeders(&self) -> i32 {
self.seeders
}
/// Number of times it has been downloaded.
pub fn num_downloads(&self) -> i32 {
self.downloaded
}
/// Current number of leechers.
pub fn num_leechers(&self) -> i32 {
self.leechers
}
}
fn parse_stats(bytes: &[u8]) -> IResult<&[u8], ScrapeStats> {
do_parse!(bytes,
seeders: be_i32 >>
downloaded: be_i32 >>
leechers: be_i32 >>
(ScrapeStats::new(seeders, downloaded, leechers))
)
}
// ----------------------------------------------------------------------------//
/// Scrape request sent from the client to the server.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScrapeRequest<'a> {
hashes: Cow<'a, [u8]>,
}
impl<'a> ScrapeRequest<'a> {
/// Create a new ScrapeRequest.
pub fn new() -> ScrapeRequest<'a> {
ScrapeRequest { hashes: Cow::Owned(Vec::new()) }
}
/// Construct a ScrapeRequest from the given bytes.
pub fn from_bytes(bytes: &'a [u8]) -> IResult<&'a [u8], ScrapeRequest<'a>> {
parse_request(bytes)
}
/// Write the ScrapeRequest to the given writer.
///
/// Ordering of the written InfoHash is identical to that of ScrapeRequest::iter().
pub fn write_bytes<W>(&self, mut writer: W) -> io::Result<()>
where W: Write
{
writer.write_all(&*self.hashes)
}
/// Add the InfoHash to the current request.
pub fn insert(&mut self, hash: InfoHash) {
let hash_bytes: [u8; bt::INFO_HASH_LEN] = hash.into();
self.hashes.to_mut().extend_from_slice(&hash_bytes);
}
/// Iterator over all of the hashes in the request.
pub fn iter<'b>(&'b self) -> ScrapeRequestIter<'b> {
ScrapeRequestIter::new(&*self.hashes)
}
/// Create an owned version of ScrapeRequest.
pub fn to_owned(&self) -> ScrapeRequest<'static> {
ScrapeRequest { hashes: Cow::Owned((*self.hashes).to_vec()) }
}
}
fn parse_request<'a>(bytes: &'a [u8]) -> IResult<&'a [u8], ScrapeRequest<'a>> {
let remainder_bytes = bytes.len() % bt::INFO_HASH_LEN;
if remainder_bytes != 0 {
IResult::Incomplete(Needed::Size(bt::INFO_HASH_LEN - remainder_bytes))
} else {
let end_of_bytes = &bytes[bytes.len()..bytes.len()];
IResult::Done(end_of_bytes, ScrapeRequest { hashes: Cow::Borrowed(bytes) })
}
}
// ----------------------------------------------------------------------------//
/// Scrape response sent from the server to the client.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScrapeResponse<'a> {
stats: Cow<'a, [u8]>,
}
impl<'a> ScrapeResponse<'a> {
/// Create a new ScrapeResponse.
pub fn new() -> ScrapeResponse<'a> {
ScrapeResponse { stats: Cow::Owned(Vec::new()) }
}
/// Construct a ScrapeResponse from the given bytes.
pub fn from_bytes(bytes: &'a [u8]) -> IResult<&'a [u8], ScrapeResponse<'a>> {
parse_response(bytes)
}
/// Write the ScrapeResponse to the given writer.
///
/// Ordering of the written stats is identical to that of ScrapeResponse::iter().
pub fn write_bytes<W>(&self, mut writer: W) -> io::Result<()>
where W: Write
{
writer.write_all(&*self.stats)
}
/// Add the scrape statistics to the current response.
pub fn insert(&mut self, stats: ScrapeStats) {
let seeders_bytes = convert::four_bytes_to_array(stats.num_seeders() as u32);
let downloads_bytes = convert::four_bytes_to_array(stats.num_downloads() as u32);
let leechers_bytes = convert::four_bytes_to_array(stats.num_leechers() as u32);
self.stats.to_mut().reserve(SCRAPE_STATS_BYTES);
self.stats.to_mut().extend_from_slice(&seeders_bytes);
self.stats.to_mut().extend_from_slice(&downloads_bytes);
self.stats.to_mut().extend_from_slice(&leechers_bytes);
}
/// Iterator over each status for every InfoHash in the request.
///
/// Ordering of the status corresponds to the ordering of the InfoHash in the
/// initial request.
pub fn iter<'b>(&'b self) -> ScrapeResponseIter<'b> {
ScrapeResponseIter::new(&*self.stats)
}
/// Create an owned version of ScrapeResponse.
pub fn to_owned(&self) -> ScrapeResponse<'static> {
ScrapeResponse { stats: Cow::Owned((*self.stats).to_vec()) }
}
}
fn parse_response<'a>(bytes: &'a [u8]) -> IResult<&'a [u8], ScrapeResponse<'a>> {
let remainder_bytes = bytes.len() % SCRAPE_STATS_BYTES;
if remainder_bytes != 0 {
IResult::Incomplete(Needed::Size(SCRAPE_STATS_BYTES - remainder_bytes))
} else {
let end_of_bytes = &bytes[bytes.len()..bytes.len()];
IResult::Done(end_of_bytes, ScrapeResponse { stats: Cow::Borrowed(bytes) })
}
}
// ----------------------------------------------------------------------------//
/// Iterator over a number of InfoHashes.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ScrapeRequestIter<'a> {
hashes: &'a [u8],
offset: usize,
}
impl<'a> ScrapeRequestIter<'a> {
fn new(bytes: &'a [u8]) -> ScrapeRequestIter<'a> {
ScrapeRequestIter {
hashes: bytes,
offset: 0,
}
}<|fim▁hole|>
fn next(&mut self) -> Option<InfoHash> {
if self.offset == self.hashes.len() {
None
} else {
let (start, end) = (self.offset, self.offset + bt::INFO_HASH_LEN);
self.offset = end;
Some(InfoHash::from_hash(&self.hashes[start..end]).unwrap())
}
}
}
impl<'a> ExactSizeIterator for ScrapeRequestIter<'a> {
fn len(&self) -> usize {
self.hashes.len() / bt::INFO_HASH_LEN
}
}
// ----------------------------------------------------------------------------//
/// Iterator over a number of ScrapeStats.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ScrapeResponseIter<'a> {
stats: &'a [u8],
offset: usize,
}
impl<'a> ScrapeResponseIter<'a> {
fn new(bytes: &'a [u8]) -> ScrapeResponseIter<'a> {
ScrapeResponseIter {
stats: bytes,
offset: 0,
}
}
}
impl<'a> Iterator for ScrapeResponseIter<'a> {
type Item = ScrapeStats;
fn next(&mut self) -> Option<ScrapeStats> {
if self.offset == self.stats.len() {
None
} else {
let (start, end) = (self.offset, self.offset + SCRAPE_STATS_BYTES);
self.offset = end;
match ScrapeStats::from_bytes(&self.stats[start..end]) {
IResult::Done(_, stats) => Some(stats),
_ => panic!("Bug In ScrapeResponseIter Caused ScrapeStats Parsing To Fail..."),
}
}
}
}
impl<'a> ExactSizeIterator for ScrapeResponseIter<'a> {
fn len(&self) -> usize {
self.stats.len() / SCRAPE_STATS_BYTES
}
}
#[cfg(test)]
mod tests {
use bip_util::bt;
use byteorder::{BigEndian, WriteBytesExt};
use nom::IResult;
use super::{ScrapeRequest, ScrapeResponse, ScrapeStats};
#[test]
fn positive_write_request_empty() {
let mut received = Vec::new();
let request = ScrapeRequest::new();
request.write_bytes(&mut received).unwrap();
let expected = [];
assert_eq!(&received[..], &expected[..]);
}
#[test]
fn positive_write_request_single_hash() {
let mut received = Vec::new();
let expected = [1u8; bt::INFO_HASH_LEN];
let mut request = ScrapeRequest::new();
request.insert(expected.into());
request.write_bytes(&mut received).unwrap();
assert_eq!(&received[..], &expected[..]);
}
#[test]
fn positive_write_request_many_hashes() {
let mut received = Vec::new();
let hash_one = [1u8; bt::INFO_HASH_LEN];
let hash_two = [34u8; bt::INFO_HASH_LEN];
let mut expected = Vec::new();
expected.extend_from_slice(&hash_one);
expected.extend_from_slice(&hash_two);
let mut request = ScrapeRequest::new();
request.insert(hash_one.into());
request.insert(hash_two.into());
request.write_bytes(&mut received).unwrap();
assert_eq!(&received[..], &expected[..]);
}
#[test]
fn positive_write_response_empty() {
let mut received = Vec::new();
let response = ScrapeResponse::new();
response.write_bytes(&mut received).unwrap();
let expected = [];
assert_eq!(&received[..], &expected[..]);
}
#[test]
fn positive_write_response_single_stat() {
let mut received = Vec::new();
let stat_one = ScrapeStats::new(1234, 2342, 0);
let mut response = ScrapeResponse::new();
response.insert(stat_one);
response.write_bytes(&mut received).unwrap();
let mut expected = Vec::new();
expected.write_i32::<BigEndian>(stat_one.num_seeders()).unwrap();
expected.write_i32::<BigEndian>(stat_one.num_downloads()).unwrap();
expected.write_i32::<BigEndian>(stat_one.num_leechers()).unwrap();
assert_eq!(&received[..], &expected[..]);
}
#[test]
fn positive_write_response_many_stats() {
let mut received = Vec::new();
let stat_one = ScrapeStats::new(1234, 2342, 0);
let stat_two = ScrapeStats::new(3333, -23, -2323);
let mut response = ScrapeResponse::new();
response.insert(stat_one);
response.insert(stat_two);
response.write_bytes(&mut received).unwrap();
let mut expected = Vec::new();
expected.write_i32::<BigEndian>(stat_one.num_seeders()).unwrap();
expected.write_i32::<BigEndian>(stat_one.num_downloads()).unwrap();
expected.write_i32::<BigEndian>(stat_one.num_leechers()).unwrap();
expected.write_i32::<BigEndian>(stat_two.num_seeders()).unwrap();
expected.write_i32::<BigEndian>(stat_two.num_downloads()).unwrap();
expected.write_i32::<BigEndian>(stat_two.num_leechers()).unwrap();
assert_eq!(&received[..], &expected[..]);
}
#[test]
fn positive_parse_request_empty() {
let hash_one = [];
let received = ScrapeRequest::from_bytes(&hash_one);
let expected = ScrapeRequest::new();
assert_eq!(received, IResult::Done(&b""[..], expected));
}
#[test]
fn positive_parse_request_single_hash() {
let hash_one = [1u8; bt::INFO_HASH_LEN];
let received = ScrapeRequest::from_bytes(&hash_one);
let mut expected = ScrapeRequest::new();
expected.insert(hash_one.into());
assert_eq!(received, IResult::Done(&b""[..], expected));
}
#[test]
fn positive_parse_request_multiple_hashes() {
let hash_one = [1u8; bt::INFO_HASH_LEN];
let hash_two = [5u8; bt::INFO_HASH_LEN];
let mut bytes = Vec::new();
bytes.extend_from_slice(&hash_one);
bytes.extend_from_slice(&hash_two);
let received = ScrapeRequest::from_bytes(&bytes);
let mut expected = ScrapeRequest::new();
expected.insert(hash_one.into());
expected.insert(hash_two.into());
assert_eq!(received, IResult::Done(&b""[..], expected));
}
#[test]
fn positive_parse_response_empty() {
let stats_bytes = [];
let received = ScrapeResponse::from_bytes(&stats_bytes);
let expected = ScrapeResponse::new();
assert_eq!(received, IResult::Done(&b""[..], expected));
}
#[test]
fn positive_parse_response_single_stat() {
let stats_bytes = [0, 0, 0, 255, 0, 0, 1, 0, 0, 0, 2, 0];
let received = ScrapeResponse::from_bytes(&stats_bytes);
let mut expected = ScrapeResponse::new();
expected.insert(ScrapeStats::new(255, 256, 512));
assert_eq!(received, IResult::Done(&b""[..], expected));
}
#[test]
fn positive_parse_response_many_stats() {
let stats_bytes = [0, 0, 0, 255, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0,
3];
let received = ScrapeResponse::from_bytes(&stats_bytes);
let mut expected = ScrapeResponse::new();
expected.insert(ScrapeStats::new(255, 256, 512));
expected.insert(ScrapeStats::new(1, 2, 3));
assert_eq!(received, IResult::Done(&b""[..], expected));
}
}<|fim▁end|> | }
impl<'a> Iterator for ScrapeRequestIter<'a> {
type Item = InfoHash; |
<|file_name|>interlude.cpp<|end_file_name|><|fim▁begin|>#include <cassert>
#include <cmath>
#include "gtest/gtest.h"
#include "interlude.hpp"
// defined in the header
// #define MAT_SIZE 5
using std::cout;
using std::endl;
// void matDiagSum(int a[][MAT_SIZE], int rows, int cols){
// }
// 1 2 3 4 5 1 2 3 4 5
// 6 7 8 9 10 6 8 10 12 14
// 11 12 13 14 15 11 18 21 24 27
// 16 17 18 19 20 16 28 36 40 44
// 21 22 23 24 25 21 38 51 60 65
// 0,0 0,1 0,2 0,3 0,4
// 1,0 1,1 1,2 1,3 1,4
// 2,0 2,1 2,2 2,3 2,4
// 3,0 3,1 3,2 3,3 3,4
// 4,0 4,1 4,2 4,3 4,4
void printArr(int arr[][MAT_SIZE], int rows, int cols) {
cout << "The two dimensional array:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
// int digitMultiSeq(int n){
// }
// int multiplyDigits(int a){
// }
// bool isPermutation(unsigned int n, unsigned int m){
// }
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerE3.html#Q3
// double standardDeviation(double values[], int length, int size){
// The formula for standard deviation
// a is the avarage of of the values r1 ... rN
// sqrt( ( ((r1 - a) x (r1 - a)) + ((r2-a) x (r2-a)) + ... + ((rN - a) x (rN - a)) ) / N )
// assert(length <= size);
<|fim▁hole|>// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerL6.html#S6-2
double average(double list[], int length, int size){
double total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += list[count];
return (total / length);
}
/*===================================================
Tests
===================================================*/
// TEST(Functions, digit_multi_seq){
// EXPECT_EQ(38, digitMultiSeq(8));
// EXPECT_EQ(62, digitMultiSeq(9));
// EXPECT_EQ(74, digitMultiSeq(10));
// }
// TEST(Functions, multiply_digits){
// int a = 1234;
// EXPECT_EQ(24, multiplyDigits(a));
// }
// TEST(Matrix, mat_diag_sum){
// int mat[MAT_SIZE][MAT_SIZE] = { { 1, 2, 3, 4, 5},
// { 6, 7, 8, 9, 10},
// { 11, 12, 13, 14, 15},
// { 16, 17, 18, 19, 20},
// { 21, 22, 23, 24, 25}};
// int ans[MAT_SIZE][MAT_SIZE] = { {1, 2, 3, 4, 5},
// {6, 8, 10, 12, 14},
// {11, 18,21, 24, 27},
// {16, 28, 36, 40, 44},
// {21, 38, 51, 60, 65}};
// matDiagSum(mat,MAT_SIZE,MAT_SIZE);
// printArr(mat,MAT_SIZE,MAT_SIZE);
// printArr(ans,MAT_SIZE,MAT_SIZE);
// for(int i = 0; i < MAT_SIZE; i++){
// for(int j = 0; j < MAT_SIZE; j++){
// EXPECT_EQ(ans[i][j], mat[i][j]);
// }
// }
// }
// TEST(Arrays, is_permutation){
// int n = 1234;
// int m = 4231;
// int n2 = 456723;
// int m2 = 456724;
// int n3 = 45647235;
// int m3 = 45657234;
// EXPECT_TRUE(isPermutation(n,m));
// EXPECT_FALSE(isPermutation(n2,m2));
// EXPECT_TRUE(isPermutation(n3,m3));
// }
TEST(Functions, average){
int length = 5;
int size = 5;
double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
EXPECT_DOUBLE_EQ(13226.693, average(list,length,size));
}
// TEST(Arrays, standard_deviation){
// int length = 5;
// int size = 5;
// double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
// double epsilon = 0.001;
// EXPECT_TRUE( abs(26132.36913 - standardDeviation(list,length,size)) <= epsilon);
// }<|fim▁end|> | // }
|
<|file_name|>UpdateBlockEntityCodec.java<|end_file_name|><|fim▁begin|>package net.glowstone.net.codec.play.game;
import com.flowpowered.network.Codec;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import net.glowstone.net.GlowBufUtils;
import net.glowstone.net.message.play.game.UpdateBlockEntityMessage;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.util.BlockVector;
<|fim▁hole|> public UpdateBlockEntityMessage decode(ByteBuf buffer) throws IOException {
BlockVector pos = GlowBufUtils.readBlockPosition(buffer);
int action = buffer.readByte();
CompoundTag nbt = GlowBufUtils.readCompound(buffer);
return new UpdateBlockEntityMessage(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(),
action, nbt);
}
@Override
public ByteBuf encode(ByteBuf buf, UpdateBlockEntityMessage message) throws IOException {
GlowBufUtils.writeBlockPosition(buf, message.getX(), message.getY(), message.getZ());
buf.writeByte(message.getAction());
GlowBufUtils.writeCompound(buf, message.getNbt());
return buf;
}
}<|fim▁end|> | public final class UpdateBlockEntityCodec implements Codec<UpdateBlockEntityMessage> {
@Override |
<|file_name|>solicit_reviews.py<|end_file_name|><|fim▁begin|>from django.core.management.base import BaseCommand
from aspc.courses.models import Schedule
from datetime import datetime, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from aspc.settings import EMAIL_HOST_USER
# Assume we send the emails at the end of the semester, we
# should only consider schedules that are at least 3 months old
MIN_DAYS = 90
MAX_DAYS = 300
EMAIL_TITLE = "Have you taken these classes?"
class Command(BaseCommand):
args = ''
help = 'imports terms'
def handle(self, *args, **options):
plaintext = get_template('email/solicit_reviews.txt')
htmly = get_template('email/solicit_reviews.html')
schedules = Schedule.objects.filter(create_ts__lte=datetime.now()-timedelta(days=MIN_DAYS),
create_ts__gte=datetime.now()-timedelta(days=MAX_DAYS))
emails_sent = 0
for schedule in schedules:
try:
context = Context({'user': schedule.user, 'courses': schedule.sections.all()})
text_content = plaintext.render(context)<|fim▁hole|> msg.attach_alternative(html_content, "text/html")
msg.send()
emails_sent += 1
except Exception as e:
self.stdout.write('Error: %s\n' % e)
self.stdout.write('Successfully send %s emails\n' % emails_sent)<|fim▁end|> | html_content = htmly.render(context)
user_data = schedule.user.user.all()
if user_data and user_data[0].subscribed_email:
msg = EmailMultiAlternatives(EMAIL_TITLE, text_content, EMAIL_HOST_USER, [schedule.user.email]) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from .ctp_gateway import CtpGateway<|fim▁end|> | |
<|file_name|>lib.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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead of in script so that these modules won't have
//! to depend on script.
#![deny(missing_docs)]
#![deny(unsafe_code)]
extern crate bluetooth_traits;
extern crate canvas_traits;
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate euclid;
extern crate gfx_traits;
extern crate heapsize;
#[macro_use]
extern crate heapsize_derive;
extern crate hyper;
extern crate hyper_serde;
extern crate ipc_channel;
extern crate libc;
extern crate msg;
extern crate net_traits;
extern crate offscreen_gl_context;
extern crate profile_traits;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate servo_url;
extern crate style_traits;
extern crate time;
extern crate webrender_traits;
extern crate webvr_traits;
mod script_msg;
pub mod webdriver_msg;
use bluetooth_traits::BluetoothRequest;
use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg, WorkerId};
use euclid::Size2D;
use euclid::length::Length;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use gfx_traits::Epoch;
use heapsize::HeapSizeOf;
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use libc::c_void;
use msg::constellation_msg::{FrameId, FrameType, Key, KeyModifiers, KeyState};
use msg::constellation_msg::{PipelineId, PipelineNamespaceId, TraversalDirection};
use net_traits::{ReferrerPolicy, ResourceThreads};
use net_traits::image::base::Image;
use net_traits::image_cache::ImageCache;
use net_traits::response::HttpsState;
use net_traits::storage_thread::StorageType;
use profile_traits::mem;
use profile_traits::time as profile_time;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
use style_traits::{CSSPixel, UnsafeNode};
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_traits::ClipId;
use webvr_traits::{WebVREvent, WebVRMsg};
pub use script_msg::{LayoutMsg, ScriptMsg, EventResult, LogEntry};
pub use script_msg::{ServiceWorkerMsg, ScopeThings, SWManagerMsg, SWManagerSenders, DOMMessage};
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct UntrustedNodeAddress(pub *const c_void);
impl HeapSizeOf for UntrustedNodeAddress {
fn heap_size_of_children(&self) -> usize {
0
}
}
#[allow(unsafe_code)]
unsafe impl Send for UntrustedNodeAddress {}
impl Serialize for UntrustedNodeAddress {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(self.0 as usize).serialize(s)
}
}
impl Deserialize for UntrustedNodeAddress {
fn deserialize<D: Deserializer>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
let value: usize = try!(Deserialize::deserialize(d));
Ok(UntrustedNodeAddress::from_id(value))
}
}
impl UntrustedNodeAddress {
/// Creates an `UntrustedNodeAddress` from the given pointer address value.
#[inline]
pub fn from_id(id: usize) -> UntrustedNodeAddress {
UntrustedNodeAddress(id as *const c_void)
}
}
/// Messages sent to the layout thread from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout thread exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetStackingContextScrollStates(Vec<StackingContextScrollState>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
}
/// can be passed to `LoadUrl` to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoadData {
/// The URL.
pub url: ServoUrl,
/// The creator pipeline id if this is an about:blank load.
pub creator_pipeline_id: Option<PipelineId>,
/// The method.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub method: Method,
/// The headers.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub headers: Headers,
/// The data.
pub data: Option<Vec<u8>>,
/// The referrer policy.
pub referrer_policy: Option<ReferrerPolicy>,
/// The referrer URL.
pub referrer_url: Option<ServoUrl>,
}
impl LoadData {
/// Create a new `LoadData` object.
pub fn new(url: ServoUrl,
creator_pipeline_id: Option<PipelineId>,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<ServoUrl>)
-> LoadData {
LoadData {
url: url,
creator_pipeline_id: creator_pipeline_id,
method: Method::Get,
headers: Headers::new(),
data: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
/// The initial data required to create a new layout attached to an existing script thread.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// The ID of the parent pipeline and frame type, if any.
/// If `None`, this is a root pipeline.
pub parent_info: Option<(PipelineId, FrameType)>,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the frame associated with this pipeline.
pub frame_id: FrameId,
/// Network request data which will be initiated by the script thread.
pub load_data: LoadData,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: Option<IpcSender<()>>,
/// Number of threads to use for layout.
pub layout_threads: usize,
}
/// When a pipeline is closed, should its browsing context be discarded too?
#[derive(Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum DiscardBrowsingContext {
/// Discard the browsing context
Yes,
/// Don't discard the browsing context
No,
}
/// Is a document fully active, active or inactive?
/// A document is active if it is the current active document in its session history,
/// it is fuly active if it is active and all of its ancestors are active,
/// and it is inactive otherwise.
/// https://html.spec.whatwg.org/multipage/#active-document
/// https://html.spec.whatwg.org/multipage/#fully-active
#[derive(Copy, Clone, PartialEq, Eq, Hash, HeapSizeOf, Debug, Deserialize, Serialize)]
pub enum DocumentActivity {
/// An inactive document
Inactive,
/// An active but not fully active document
Active,
/// A fully active document
FullyActive,
}
/// The reason why the pipeline id of an iframe is being updated.
#[derive(Copy, Clone, PartialEq, Eq, Hash, HeapSizeOf, Debug, Deserialize, Serialize)]
pub enum UpdatePipelineIdReason {
/// The pipeline id is being updated due to a navigation.
Navigation,
/// The pipeline id is being updated due to a history traversal.
Traversal,
}
/// Messages sent from the constellation or layout to the script thread.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout thread, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData, WindowSizeType),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, DiscardBrowsingContext),
/// Notifies the script that the whole thread should be closed.
ExitScriptThread,
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Notifies script of a new set of scroll offsets.
SetScrollState(PipelineId, Vec<(UntrustedNodeAddress, Point2D<f32>)>),
/// Requests that the script thread immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script thread of a change to one of its document's activity
SetDocumentActivity(PipelineId, DocumentActivity),
/// Notifies script thread whether frame is visible
ChangeFrameVisibilityStatus(PipelineId, bool),
/// Notifies script thread that frame visibility change is complete
/// PipelineId is for the parent, FrameId is for the actual frame.
NotifyVisibilityChange(PipelineId, FrameId, bool),
/// Notifies script thread that a url should be loaded in this iframe.
/// PipelineId is for the parent, FrameId is for the actual frame.
Navigate(PipelineId, FrameId, LoadData, bool),
/// Post a message to a given window.
PostMessage(PipelineId, Option<ImmutableOrigin>, Vec<u8>),
/// Requests the script thread forward a mozbrowser event to an iframe it owns,
/// or to the window if no child frame id is provided.
MozBrowserEvent(PipelineId, Option<FrameId>, MozBrowserEvent),
/// Updates the current pipeline ID of a given iframe.
/// First PipelineId is for the parent, second is the new PipelineId for the frame.
UpdatePipelineId(PipelineId, FrameId, PipelineId, UpdatePipelineIdReason),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
/// PipelineId is for the parent, FrameId is for the actual frame.
FocusIFrame(PipelineId, FrameId),
/// Passes a webdriver command to the script thread for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script thread that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script thread of a transition end
TransitionEnd(UnsafeNode, String, f64),
/// Notifies the script thread that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
/// Cause a `load` event to be dispatched at the appropriate frame element.
DispatchFrameLoadEvent {
/// The frame that has been marked as loaded.
target: FrameId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId,
/// The pipeline that has completed loading.
child: PipelineId,
},
/// Cause a `storage` event to be dispatched at the appropriate window.
/// The strings are key, old value and new value.
DispatchStorageEvent(PipelineId, StorageType, ServoUrl, Option<String>, Option<String>, Option<String>),
/// Report an error from a CSS parser for the given pipeline
ReportCSSError(PipelineId, String, usize, usize, String),
/// Reload the given page.
Reload(PipelineId),
/// Notifies the script thread of WebVR events.
WebVREvents(PipelineId, Vec<WebVREvent>)
}
impl fmt::Debug for ConstellationControlMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationControlMsg::*;
let variant = match *self {
AttachLayout(..) => "AttachLayout",
Resize(..) => "Resize",
ResizeInactive(..) => "ResizeInactive",
ExitPipeline(..) => "ExitPipeline",
ExitScriptThread => "ExitScriptThread",
SendEvent(..) => "SendEvent",
Viewport(..) => "Viewport",
SetScrollState(..) => "SetScrollState",
GetTitle(..) => "GetTitle",
SetDocumentActivity(..) => "SetDocumentActivity",
ChangeFrameVisibilityStatus(..) => "ChangeFrameVisibilityStatus",
NotifyVisibilityChange(..) => "NotifyVisibilityChange",
Navigate(..) => "Navigate",
PostMessage(..) => "PostMessage",
MozBrowserEvent(..) => "MozBrowserEvent",
UpdatePipelineId(..) => "UpdatePipelineId",
FocusIFrame(..) => "FocusIFrame",
WebDriverScriptCommand(..) => "WebDriverScriptCommand",
TickAllAnimations(..) => "TickAllAnimations",
TransitionEnd(..) => "TransitionEnd",
WebFontLoaded(..) => "WebFontLoaded",
DispatchFrameLoadEvent { .. } => "DispatchFrameLoadEvent",
DispatchStorageEvent(..) => "DispatchStorageEvent",
ReportCSSError(..) => "ReportCSSError",
Reload(..) => "Reload",
WebVREvents(..) => "WebVREvents",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
/// For a given pipeline, whether any animations are currently running
/// and any animation callbacks are queued
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
/// Animations are active but no callbacks are queued
AnimationsPresent,
/// Animations are active and callbacks are queued
AnimationCallbacksPresent,
/// No animations are active and no callbacks are queued
NoAnimationsPresent,
/// No animations are active but callbacks are queued
NoAnimationCallbacksPresent,
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// http://w3c.github.io/touch-events/#widl-Touch-identifier
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TouchId(pub i32);
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// The types of mouse events
#[derive(Deserialize, HeapSizeOf, Serialize)]
pub enum MouseEventType {
/// Mouse button clicked
Click,
/// Mouse button down
MouseDown,
/// Mouse button up
MouseUp,
}
/// Events from the compositor that the script thread needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData, WindowSizeType),
/// A mouse button state changed.
MouseButtonEvent(MouseEventType, MouseButton, Point2D<f32>),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>),
/// Touchpad pressure event
TouchpadPressureEvent(Point2D<f32>, f32, TouchpadPressurePhase),
/// A key was pressed.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
}
/// Touchpad pressure phase for `TouchpadPressureEvent`.
#[derive(Copy, Clone, HeapSizeOf, PartialEq, Deserialize, Serialize)]
pub enum TouchpadPressurePhase {
/// Pressure before a regular click.
BeforeClick,
/// Pressure after a regular click.
AfterFirstClick,
/// Pressure after a "forceTouch" click
AfterSecondClick,
}
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>, pub TimerSource, pub TimerEventId, pub MsDuration);
/// Type of messages that can be sent to the timer scheduler.
#[derive(Deserialize, Serialize)]
pub enum TimerSchedulerMsg {
/// Message to schedule a new timer event.
Request(TimerEventRequest),
/// Message to exit the timer scheduler.
Exit,
}
/// Notifies the script thread to fire due timers.
/// `TimerSource` must be `FromWindow` when dispatched to `ScriptThread` and
/// must be `FromWorker` when dispatched to a `DedicatedGlobalWorkerScope`
#[derive(Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
/// Describes the thread that requested the TimerEvent.
#[derive(Copy, Clone, HeapSizeOf, Deserialize, Serialize)]
pub enum TimerSource {
/// The event was requested from a window (ScriptThread).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker,
}
/// The id to be used for a `TimerEvent` is defined by the corresponding `TimerEventRequest`.
#[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf, Deserialize, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Nanoseconds {}
/// Amount of milliseconds.
pub type MsDuration = Length<u64, Milliseconds>;
/// Amount of nanoseconds.
pub type NsDuration = Length<u64, Nanoseconds>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<(PipelineId, FrameType)>,
/// The ID of the frame this script is part of.
pub frame_id: FrameId,
/// The ID of the top-level frame this script is part of.
pub top_level_frame_id: FrameId,
/// A channel with which messages can be sent to us (the script thread).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub constellation_chan: IpcSender<ScriptMsg>,
/// A sender for the layout thread to communicate to the constellation.
pub layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerSchedulerMsg>,
/// A channel to the resource manager thread.
pub resource_threads: ResourceThreads,
/// A channel to the bluetooth thread.
pub bluetooth_thread: IpcSender<BluetoothRequest>,
/// The image cache for this script thread.
pub image_cache: Arc<ImageCache>,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
/// A channel to the webvr thread, if available.
pub webvr_thread: Option<IpcSender<WebVRMsg>>
}
/// This trait allows creating a `ScriptThread` without depending on the `script`
/// crate.
pub trait ScriptThreadFactory {
/// Type of message sent from script to layout.
type Message;
/// Create a `ScriptThread`.
fn create(state: InitialScriptState, load_data: LoadData)
-> (Sender<Self::Message>, Receiver<Self::Message>);
}
/// Whether the sandbox attribute is present for an iframe element
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
/// Sandbox attribute is present
IFrameSandboxed,
/// Sandbox attribute is not present
IFrameUnsandboxed,
}
/// Specifies the information required to load an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfo {
/// Pipeline ID of the parent of this iframe
pub parent_pipeline_id: PipelineId,
/// The ID for this iframe.
pub frame_id: FrameId,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Whether this iframe should be considered private
pub is_private: bool,
/// Whether this iframe is a mozbrowser iframe
pub frame_type: FrameType,
/// Wether this load should replace the current entry (reload). If true, the current
/// entry will be replaced instead of a new entry being added.
pub replace: bool,
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfoWithData {
/// The information required to load an iframe.
pub info: IFrameLoadInfo,
/// Load data containing the url to load
pub load_data: Option<LoadData>,
/// The old pipeline ID for this iframe, if a page was previously loaded.
pub old_pipeline_id: Option<PipelineId>,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
// https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events
/// The events fired in a Browser API context (`<iframe mozbrowser>`)
#[derive(Deserialize, Serialize)]
pub enum MozBrowserEvent {
/// Sent when the scroll position within a browser `<iframe>` changes.
AsyncScroll,
/// Sent when window.close() is called within a browser `<iframe>`.
Close,
/// Sent when a browser `<iframe>` tries to open a context menu. This allows
/// handling `<menuitem>` element available within the browser `<iframe>`'s content.
ContextMenu,
/// Sent when an error occurred while trying to load content within a browser `<iframe>`.
/// Includes a human-readable description, and a machine-readable report.
Error(MozBrowserErrorType, String, String),
/// Sent when the favicon of a browser `<iframe>` changes.
IconChange(String, String, String),
/// Sent when the browser `<iframe>` has reached the server.
Connected,
/// Sent when the browser `<iframe>` has finished loading all its assets.
LoadEnd,
/// Sent when the browser `<iframe>` starts to load a new page.
LoadStart,
/// Sent when a browser `<iframe>`'s location changes.
LocationChange(String, bool, bool),
/// Sent when a new tab is opened within a browser `<iframe>` as a result of the user
/// issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
/// Includes the URL.
OpenTab(String),
/// Sent when a new window is opened within a browser `<iframe>`.
/// Includes the URL, target browsing context name, and features.
OpenWindow(String, Option<String>, Option<String>),
/// Sent when the SSL state changes within a browser `<iframe>`.
SecurityChange(HttpsState),
/// Sent when alert(), confirm(), or prompt() is called within a browser `<iframe>`.
ShowModalPrompt(String, String, String, String), // TODO(simartin): Handle unblock()
/// Sent when the document.title changes within a browser `<iframe>`.
TitleChange(String),
/// Sent when an HTTP authentification is requested.
UsernameAndPasswordRequired,
/// Sent when a link to a search engine is found.
OpenSearch,
/// Sent when visibility state changes.
VisibilityChange(bool),
}
impl MozBrowserEvent {
/// Get the name of the event as a `& str`
pub fn name(&self) -> &'static str {
match *self {
MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll",<|fim▁hole|> MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu",
MozBrowserEvent::Error(_, _, _) => "mozbrowsererror",
MozBrowserEvent::IconChange(_, _, _) => "mozbrowsericonchange",
MozBrowserEvent::LoadEnd => "mozbrowserloadend",
MozBrowserEvent::LoadStart => "mozbrowserloadstart",
MozBrowserEvent::LocationChange(_, _, _) => "mozbrowserlocationchange",
MozBrowserEvent::OpenTab(_) => "mozbrowseropentab",
MozBrowserEvent::OpenWindow(_, _, _) => "mozbrowseropenwindow",
MozBrowserEvent::SecurityChange(_) => "mozbrowsersecuritychange",
MozBrowserEvent::ShowModalPrompt(_, _, _, _) => "mozbrowsershowmodalprompt",
MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange",
MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired",
MozBrowserEvent::OpenSearch => "mozbrowseropensearch",
MozBrowserEvent::VisibilityChange(_) => "mozbrowservisibilitychange",
}
}
}
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsererror
/// The different types of Browser error events
#[derive(Deserialize, Serialize)]
pub enum MozBrowserErrorType {
// For the moment, we are just reporting panics, using the "fatal" type.
/// A fatal error
Fatal,
}
impl MozBrowserErrorType {
/// Get the name of the error type as a `& str`
pub fn name(&self) -> &'static str {
match *self {
MozBrowserErrorType::Fatal => "fatal",
}
}
}
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
/// The script thread.
Script,
/// The layout thread.
Layout,
}
/// The scroll state of a stacking context.
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub struct StackingContextScrollState {
/// The ID of the scroll root.
pub scroll_root_id: ClipId,
/// The scrolling offset of this stacking context.
pub scroll_offset: Point2D<f32>,
}
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[derive(Copy, Clone, Debug)]
pub enum DevicePixel {}
/// Data about the window size.
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<f32, CSSPixel>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>,
}
/// The type of window size change.
#[derive(Deserialize, Eq, PartialEq, Serialize, Copy, Clone, HeapSizeOf)]
pub enum WindowSizeType {
/// Initial load.
Initial,
/// Window resize.
Resize,
}
/// Messages to the constellation originating from the WebDriver server.
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
/// Get the window size.
GetWindowSize(PipelineId, IpcSender<WindowSizeData>),
/// Load a URL in the pipeline with the given ID.
LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>),
/// Refresh the pipeline with the given ID.
Refresh(PipelineId, IpcSender<LoadStatus>),
/// Pass a webdriver command to the script thread of the pipeline with the
/// given ID for execution.
ScriptCommand(PipelineId, WebDriverScriptCommand),
/// Act as if keys were pressed in the pipeline with the given ID.
SendKeys(PipelineId, Vec<(Key, KeyModifiers, KeyState)>),
/// Set the window size.
SetWindowSize(PipelineId, Size2D<u32>, IpcSender<WindowSizeData>),
/// Take a screenshot of the window, if the pipeline with the given ID is
/// the root pipeline.
TakeScreenshot(PipelineId, IpcSender<Option<Image>>),
}
/// Messages to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ConstellationMsg {
/// Exit the constellation.
Exit,
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel.
/// Also returns a boolean saying whether the document has finished loading or not.
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
/// Request to load the initial page.
InitLoadUrl(ServoUrl),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Inform the constellation of a key event.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Request to load a page.
LoadUrl(PipelineId, LoadData),
/// Request to traverse the joint session history.
TraverseHistory(Option<PipelineId>, TraversalDirection),
/// Inform the constellation of a window being resized.
WindowSize(WindowSizeData, WindowSizeType),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
/// Reload the current page.
Reload,
/// A log entry, with the top-level frame id and thread name
LogEntry(Option<FrameId>, Option<String>, LogEntry),
/// Set the WebVR thread channel.
SetWebVRThread(IpcSender<WebVRMsg>),
/// Dispatch WebVR events to the subscribed script threads.
WebVREvents(Vec<PipelineId>, Vec<WebVREvent>),
}
/// Resources required by workerglobalscopes
#[derive(Serialize, Deserialize, Clone)]
pub struct WorkerGlobalScopeInit {
/// Chan to a resource thread
pub resource_threads: ResourceThreads,
/// Chan to the memory profiler
pub mem_profiler_chan: mem::ProfilerChan,
/// Chan to the time profiler
pub time_profiler_chan: profile_time::ProfilerChan,
/// To devtools sender
pub to_devtools_sender: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// From devtools sender
pub from_devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>,
/// Messages to send to constellation
pub constellation_chan: IpcSender<ScriptMsg>,
/// Message to send to the scheduler
pub scheduler_chan: IpcSender<TimerSchedulerMsg>,
/// The worker id
pub worker_id: WorkerId,
/// The pipeline id
pub pipeline_id: PipelineId,
/// The origin
pub origin: ImmutableOrigin,
}
/// Common entities representing a network load origin
#[derive(Deserialize, Serialize, Clone)]
pub struct WorkerScriptLoadOrigin {
/// referrer url
pub referrer_url: Option<ServoUrl>,
/// the referrer policy which is used
pub referrer_policy: Option<ReferrerPolicy>,
/// the pipeline id of the entity requesting the load
pub pipeline_id: Option<PipelineId>,
}<|fim▁end|> | MozBrowserEvent::Close => "mozbrowserclose",
MozBrowserEvent::Connected => "mozbrowserconnected", |
<|file_name|>iterator_self_move_assign_neg.cc<|end_file_name|><|fim▁begin|>// Copyright (C) 2012-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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 library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along<|fim▁hole|>// { dg-require-debug-mode "" }
#include <set>
void test01()
{
std::set<int> s1;
auto it1 = s1.begin();
it1 = std::move(it1);
}
int main()
{
test01();
return 0;
}<|fim▁end|> | // with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
//
// { dg-do run { target c++11 xfail *-*-* } } |
<|file_name|>tool_base.py<|end_file_name|><|fim▁begin|># Copyright (C) 2013-2015 MetaMorph Software, Inc
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this data, including any software or models in source or binary
# form, as well as any drawings, specifications, and documentation
# (collectively "the Data"), to deal in the Data without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Data, and to
# permit persons to whom the Data is furnished to do so, subject to the
# following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Data.
# THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
# =======================
# This version of the META tools is a fork of an original version produced
# by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
# Their license statement:
# Copyright (C) 2011-2014 Vanderbilt University
# Developed with the sponsorship of the Defense Advanced Research Projects
# Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
# as defined in DFARS 252.227-7013.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this data, including any software or models in source or binary
# form, as well as any drawings, specifications, and documentation
# (collectively "the Data"), to deal in the Data without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Data, and to
# permit persons to whom the Data is furnished to do so, subject to the
# following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Data.
# THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
import os
import datetime
import logging
from py_modelica.exception_classes import ModelicaInstantiationError
from abc import ABCMeta, abstractmethod
class ToolBase:
__metaclass__ = ABCMeta
tool_name = ''
tool_version = ''
tool_version_nbr = ''
model_config = None
date_time = ''
## instance variables
tool_path = '' # path to the bin folder of the tool
model_file_name = '' # file that needs to be loaded
model_name = '' # name of the model in the loaded packages
msl_version = '' # version of Modelica Standard Library
mos_file_name = '' # modelica script files for compiling the model
result_mat = '' # contains the latest simulation results
base_result_mat = '' # contains the expected simulation results
working_dir = '' # contains the temporary files and executables
root_dir = ''
mo_dir = '' # contains the modelica file, (package or model)
output_dir = '' # relative or absolute
variable_filter = [] # list of names of variables to save/load to/from mat-file
experiment = {} # dictionary with StartTime, StopTime, Tolerance,
# NumberOfIntervals, Interval and Algorithm.
model_is_compiled = False # flag for telling if the model was compiled
model_did_simulate = False # flag for telling if the model has been simulated
lib_package_paths = [] # paths to additional packages
lib_package_names = [] # names of additional packages
max_simulation_time = 43200 # (=12h) time threshold before simulation is aborted
## Variables with execution statistics
compilation_time = -1
translation_time = -1
make_time = -1
simulation_time = -1
total_time = -1
def _initialize(self,
model_config):
"""
Creates a new instance of a modelica simulation.
dictionary : model_config
Mandatory Keys : 'model_name' (str), 'model_file_name' (str)
<|fim▁hole|> """
print ' --- ===== See debug.log for error/debug messages ===== --- \n'
print ' in {0}'.format(os.getcwd())
# create a logger, (will only be written to if no other logger defined 'higher' up)
logging.basicConfig(filename="debug.log",
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
log = logging.getLogger()
# always use highest level of debugging
log.setLevel(logging.DEBUG)
log.debug(" --- ==== ******************************* ==== ---")
log.info(" --- ==== ******* New Run Started ******* ==== ---")
self.date_time = '{0}'.format(datetime.datetime.today())
log.debug(" --- ==== * {0} ** ==== ---".format(self.date_time))
log.debug(" --- ==== ******************************* ==== ---")
log.debug("Entered _initialize")
log.info("tool_name : {0}".format(self.tool_name))
log.info("tool_path : {0}".format(self.tool_path))
self.root_dir = os.getcwd()
self.model_config = model_config
# Mandatory keys in dictionary
try:
model_file_name = self.model_config['model_file_name']
if model_file_name == "":
self.model_file_name = ""
log.info("No model_file name given, assumes model is in Modelica Standard Library")
else:
self.model_file_name = os.path.normpath(os.path.join(os.getcwd(), model_file_name))
self.mo_dir = os.path.dirname(self.model_file_name)
log.info("mo_dir : {}".format(self.mo_dir))
log.info("model_file_name : {0}".format(self.model_file_name))
model_name = self.model_config['model_name']
if model_name == "":
base_name = os.path.basename(model_file_name)
self.model_name = os.path.splitext(base_name)[0]
log.info("No model_name given, uses model_file_name without .mo")
else:
self.model_name = model_name
log.info("model_name : {0}".format(self.model_name))
except KeyError as err:
raise ModelicaInstantiationError("Mandatory key missing in model_config : {0}".format(err.message))
# optional keys in dictionary
if 'MSL_version' in model_config:
self.msl_version = self.model_config['MSL_version']
else:
self.msl_version = "3.2"
log.info("msl_version : {0}".format(self.msl_version))
if 'experiment' in model_config:
self.experiment = dict(
StartTime=model_config['experiment']['StartTime'],
StopTime=model_config['experiment']['StopTime'],
NumberOfIntervals=model_config['experiment']['NumberOfIntervals'],
Tolerance=model_config['experiment']['Tolerance'])
# Algorithm
if 'Algorithm' in model_config['experiment']:
if self.tool_name.startswith('Dymola'):
self.experiment.update({'Algorithm':
self.model_config['experiment']['Algorithm']['Dymola']})
elif self.tool_name == 'OpenModelica':
self.experiment.update({'Algorithm':
self.model_config['experiment']['Algorithm']['OpenModelica']})
elif self.tool_name == 'JModelica':
self.experiment.update({'Algorithm':
self.model_config['experiment']['Algorithm']['JModelica']})
else: # py_modelica 12.09
self.experiment.update({'Algorithm': 'dassl'})
# Interval
if 'IntervalMethod' in model_config['experiment']:
if model_config['experiment']['IntervalMethod'] == 'Interval':
self.experiment.update({"NumberOfIntervals": "0"})
self.experiment.update({"Interval": model_config['experiment']['Interval']})
else:
self.experiment.update({"NumberOfIntervals":
model_config['experiment']['NumberOfIntervals']})
self.experiment.update({"Interval": "0"})
else: # py_modelica 12.09
self.experiment.update({"NumberOfIntervals":
model_config['experiment']['NumberOfIntervals']})
self.experiment.update({"Interval": "0"})
else:
self.experiment = dict(StartTime='0',
StopTime='1',
NumberOfIntervals='500',
Interval='0',
Tolerance='1e-5',
Algorithm='dassl')
log.info("No experiment data given, default values will be used...")
log.info("Experiment settings : {0}".format(self.experiment))
if 'lib_package_paths' in model_config:
for lib_path in self.model_config['lib_package_paths']:
if lib_path:
self.lib_package_paths.append(str(lib_path))
if 'lib_package_names' in model_config:
for lib_name in self.model_config['lib_package_names']:
if lib_name:
self.lib_package_names.append(lib_name)
if os.name == 'nt':
try:
import _winreg as wr
key = wr.OpenKey(wr.HKEY_LOCAL_MACHINE, r'software\meta', 0, wr.KEY_READ)
try:
self.max_simulation_time = wr.QueryValueEx(key, 'MAX_SIMULATION_TIME')[0]
print 'Found MAX_SIMULATION_TIME in registry, value was {0} (={1:.1f} h).'\
.format(self.max_simulation_time, float(self.max_simulation_time)/3600)
except WindowsError:
print 'MAX_SIMULATION_TIME not set in registry, using default {0} (={1:.1f} h).'\
.format(self.max_simulation_time, float(self.max_simulation_time)/3600)
except WindowsError:
print 'META-Tools not installed, using default max_simulation_time at {0} (={1:.1f} h).'\
.format(self.max_simulation_time, float(self.max_simulation_time)/3600)
# end of __initialize__
@abstractmethod
def compile_model(self):
return bool
@abstractmethod
def simulate_model(self):
return bool
@abstractmethod
def change_experiment(self,
start_time='0',
stop_time='1',
increment='',
n_interval='500',
tolerance='1e-5',
max_fixed_step='',
solver='dassl',
output_format='',
variable_filter=''):
return bool
@abstractmethod
def change_parameter(self, change_dict):
return bool<|fim▁end|> |
Optional Keys : 'MSL_version' (str), 'variable_filter' ([str]),
'result_file' (str), 'experiment' ({str})
|
<|file_name|>test_quadf_coef.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
using namespace mfem;
namespace qf_coeff
{
TEST_CASE("Quadrature Function Coefficients",
"[Quadrature Function Coefficients]")
{
int order_h1 = 2, n = 4, dim = 3;
double tol = 1e-14;
Mesh mesh = Mesh::MakeCartesian3D(
n, n, n, Element::HEXAHEDRON, 1.0, 1.0, 1.0);
mesh.SetCurvature(order_h1);
int intOrder = 2 * order_h1 + 1;
QuadratureSpace qspace(&mesh, intOrder);
QuadratureFunction quadf_coeff(&qspace, 1);
QuadratureFunction quadf_vcoeff(&qspace, dim);
const IntegrationRule ir = qspace.GetElementIntRule(0);
const GeometricFactors *geom_facts =
mesh.GetGeometricFactors(ir, GeometricFactors::COORDINATES);
{
int nelems = quadf_coeff.Size() / quadf_coeff.GetVDim() / ir.GetNPoints();
int vdim = ir.GetNPoints();
for (int i = 0; i < nelems; i++)
{
for (int j = 0; j < vdim; j++)
{
//X has dims nqpts x sdim x ne
quadf_coeff((i * vdim) + j) =
geom_facts->X((i * vdim * dim) + (vdim * 2) + j );
}
}
}
{
int nqpts = ir.GetNPoints();
int nelems = quadf_vcoeff.Size() / quadf_vcoeff.GetVDim() / nqpts;<|fim▁hole|>
for (int i = 0; i < nelems; i++)
{
for (int j = 0; j < vdim; j++)
{
for (int k = 0; k < nqpts; k++)
{
//X has dims nqpts x sdim x ne
quadf_vcoeff((i * nqpts * vdim) + (k * vdim ) + j) =
geom_facts->X((i * nqpts * vdim) + (j * nqpts) + k);
}
}
}
}
QuadratureFunctionCoefficient qfc(quadf_coeff);
VectorQuadratureFunctionCoefficient qfvc(quadf_vcoeff);
SECTION("Operators on VecQuadFuncCoeff")
{
std::cout << "Testing VecQuadFuncCoeff: " << std::endl;
#ifdef MFEM_USE_EXCEPTIONS
std::cout << " Setting Component" << std::endl;
REQUIRE_THROWS(qfvc.SetComponent(3, 1));
REQUIRE_THROWS(qfvc.SetComponent(-1, 1));
REQUIRE_NOTHROW(qfvc.SetComponent(1, 2));
REQUIRE_THROWS(qfvc.SetComponent(0, 4));
REQUIRE_THROWS(qfvc.SetComponent(1, 3));
REQUIRE_NOTHROW(qfvc.SetComponent(0, 2));
REQUIRE_THROWS(qfvc.SetComponent(0, 0));
#endif
qfvc.SetComponent(0, 3);
}
SECTION("Operators on VectorQuadratureLFIntegrator")
{
std::cout << "Testing VectorQuadratureLFIntegrator: " << std::endl;
H1_FECollection fec_h1(order_h1, dim);
FiniteElementSpace fespace_h1(&mesh, &fec_h1, dim);
GridFunction nodes(&fespace_h1);
mesh.GetNodes(nodes);
Vector output(nodes.Size());
output = 0.0;
LinearForm lf(&fespace_h1);
lf.AddDomainIntegrator(new VectorQuadratureLFIntegrator(qfvc, NULL));
lf.Assemble();
BilinearForm L2(&fespace_h1);
L2.AddDomainIntegrator(new VectorMassIntegrator());
L2.Assemble();
SparseMatrix mat = L2.SpMat();
mat.Mult(nodes, output);
output -= lf;
REQUIRE(output.Norml2() < tol);
}
SECTION("Operators on QuadratureLFIntegrator")
{
std::cout << "Testing QuadratureLFIntegrator: " << std::endl;
H1_FECollection fec_h1(order_h1, dim);
FiniteElementSpace fespace_h1(&mesh, &fec_h1, 1);
FiniteElementSpace fespace_h3(&mesh, &fec_h1, 3);
GridFunction nodes(&fespace_h3);
mesh.GetNodes(nodes);
Vector output(nodes.Size() / dim);
Vector nz(nodes.Size() / dim);
output = 0.0;
nz.MakeRef(nodes, nz.Size() * 2);
LinearForm lf(&fespace_h1);
lf.AddDomainIntegrator(new QuadratureLFIntegrator(qfc, NULL));
lf.Assemble();
BilinearForm L2(&fespace_h1);
L2.AddDomainIntegrator(new MassIntegrator(&ir));
L2.Assemble();
SparseMatrix mat = L2.SpMat();
mat.Mult(nz, output);
output -= lf;
REQUIRE(output.Norml2() < tol);
}
}
} // namespace qf_coeff<|fim▁end|> | int vdim = quadf_vcoeff.GetVDim(); |
<|file_name|>test_node.ts<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// Use the CPU backend for running tests.
import '@tensorflow/tfjs-backend-cpu';<|fim▁hole|>const jasmineCtor = require('jasmine');
// tslint:disable-next-line:no-require-imports
Error.stackTraceLimit = Infinity;
process.on('unhandledRejection', e => {
throw e;
});
jasmine_util.setTestEnvs(
[{name: 'test-inference-api', backendName: 'cpu', flags: {}}]);
const unitTests = 'src/**/*_test.ts';
const runner = new jasmineCtor();
runner.loadConfig({spec_files: [unitTests], random: false});
runner.execute();<|fim▁end|> | // tslint:disable-next-line:no-imports-from-dist
import * as jasmine_util from '@tensorflow/tfjs-core/dist/jasmine_util';
// tslint:disable-next-line:no-require-imports |
<|file_name|>JksHandler.py<|end_file_name|><|fim▁begin|>'''
Created on 16 Sep 2016
@author: rizarse
'''
import jks, textwrap, base64
from os.path import expanduser
import os.path
import atexit
import shutil
from os import makedirs
class JksHandler(object):
def __init__(self, params):
pass
@staticmethod
def writePkAndCerts(ks, token):
uid = None
home = expanduser("~")
def deleteCerts(self, path):<|fim▁hole|> atexit.register(deleteCerts, home + '/magistral/' + token)
for alias, pk in ks.private_keys.items():
uid = alias
if pk.algorithm_oid == jks.util.RSA_ENCRYPTION_OID:
if os.path.exists(home + '/magistral/' + token) == False:
makedirs(home + '/magistral/' + token)
key = home + '/magistral/' + token + '/key.pem'
if os.path.exists(key): os.remove(key)
with open(key, 'wb') as f:
f.seek(0)
f.write(bytearray(b"-----BEGIN RSA PRIVATE KEY-----\r\n"))
f.write(bytes("\r\n".join(textwrap.wrap(base64.b64encode(pk.pkey).decode('ascii'), 64)), 'utf-8'))
f.write(bytearray(b"\r\n-----END RSA PRIVATE KEY-----"))
f.close()
counter = 0;
cert = home + '/magistral/' + token + '/certificate.pem'
if os.path.exists(cert): os.remove(cert)
with open(cert, 'wb') as f:
f.seek(0)
for c in pk.cert_chain:
f.write(bytearray(b"-----BEGIN CERTIFICATE-----\r\n"))
f.write(bytes("\r\n".join(textwrap.wrap(base64.b64encode(c[1]).decode('ascii'), 64)), 'utf-8'))
f.write(bytearray(b"\r\n-----END CERTIFICATE-----\r\n"))
counter = counter + 1
if (counter == 2): break
f.close()
ca = home + '/magistral/' + token + '/ca.pem'
if os.path.exists(ca): os.remove(ca)
with open(ca, 'wb') as f:
for alias, c in ks.certs.items():
f.write(bytearray(b"-----BEGIN CERTIFICATE-----\r\n"))
f.write(bytes("\r\n".join(textwrap.wrap(base64.b64encode(c.cert).decode('ascii'), 64)), 'utf-8'))
f.write(bytearray(b"\r\n-----END CERTIFICATE-----\r\n"))
f.close()
return uid
@staticmethod
def printJks(ks):
def print_pem(der_bytes, _type_):
print("-----BEGIN %s-----" % _type_)
print("\r\n".join(textwrap.wrap(base64.b64encode(der_bytes).decode('ascii'), 64)))
print("-----END %s-----" % _type_)
for _, pk in ks.private_keys.items():
print("Private key: %s" % pk.alias)
if pk.algorithm_oid == jks.util.RSA_ENCRYPTION_OID:
print_pem(pk.pkey, "RSA PRIVATE KEY")
else:
print_pem(pk.pkey_pkcs8, "PRIVATE KEY")
for c in pk.cert_chain:
print_pem(c[1], "CERTIFICATE")
print()
for _, c in ks.certs.items():
print("Certificate: %s" % c.alias)
print_pem(c.cert, "CERTIFICATE")
print()
for _, sk in ks.secret_keys.items():
print("Secret key: %s" % sk.alias)
print(" Algorithm: %s" % sk.algorithm)
print(" Key size: %d bits" % sk.key_size)
print(" Key: %s" % "".join("{:02x}".format(b) for b in bytearray(sk.key)))
print()<|fim▁end|> | shutil.rmtree(path)
|
<|file_name|>loadbalancerloadbalancingrules.go<|end_file_name|><|fim▁begin|>package network
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// LoadBalancerLoadBalancingRulesClient is the network Client
type LoadBalancerLoadBalancingRulesClient struct {
BaseClient
}
// NewLoadBalancerLoadBalancingRulesClient creates an instance of the LoadBalancerLoadBalancingRulesClient client.
func NewLoadBalancerLoadBalancingRulesClient(subscriptionID string) LoadBalancerLoadBalancingRulesClient {
return NewLoadBalancerLoadBalancingRulesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewLoadBalancerLoadBalancingRulesClientWithBaseURI creates an instance of the LoadBalancerLoadBalancingRulesClient
// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI
// (sovereign clouds, Azure stack).
func NewLoadBalancerLoadBalancingRulesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerLoadBalancingRulesClient {
return LoadBalancerLoadBalancingRulesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get gets the specified load balancer load balancing rule.
// Parameters:
// resourceGroupName - the name of the resource group.
// loadBalancerName - the name of the load balancer.
// loadBalancingRuleName - the name of the load balancing rule.
func (client LoadBalancerLoadBalancingRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (result LoadBalancingRule, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, loadBalancingRuleName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client LoadBalancerLoadBalancingRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"loadBalancerName": autorest.Encode("path", loadBalancerName),
"loadBalancingRuleName": autorest.Encode("path", loadBalancingRuleName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-10-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancerLoadBalancingRulesClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
<|fim▁hole|>// closes the http.Response Body.
func (client LoadBalancerLoadBalancingRulesClient) GetResponder(resp *http.Response) (result LoadBalancingRule, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all the load balancing rules in a load balancer.
// Parameters:
// resourceGroupName - the name of the resource group.
// loadBalancerName - the name of the load balancer.
func (client LoadBalancerLoadBalancingRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List")
defer func() {
sc := -1
if result.lblbrlr.Response.Response != nil {
sc = result.lblbrlr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.lblbrlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure sending request")
return
}
result.lblbrlr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure responding to request")
return
}
if result.lblbrlr.hasNextLink() && result.lblbrlr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListPreparer prepares the List request.
func (client LoadBalancerLoadBalancingRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"loadBalancerName": autorest.Encode("path", loadBalancerName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-10-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancerLoadBalancingRulesClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client LoadBalancerLoadBalancingRulesClient) ListResponder(resp *http.Response) (result LoadBalancerLoadBalancingRuleListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client LoadBalancerLoadBalancingRulesClient) listNextResults(ctx context.Context, lastResults LoadBalancerLoadBalancingRuleListResult) (result LoadBalancerLoadBalancingRuleListResult, err error) {
req, err := lastResults.loadBalancerLoadBalancingRuleListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client LoadBalancerLoadBalancingRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx, resourceGroupName, loadBalancerName)
return
}<|fim▁end|> | // GetResponder handles the response to the Get request. The method always |
<|file_name|>impl-wf-cycle-1.rs<|end_file_name|><|fim▁begin|>// Regression test for #79714
trait Baz {}
impl Baz for () {}
impl<T> Baz for (T,) {}
trait Fiz {}
impl Fiz for bool {}
trait Grault {
type A;
type B;
}
impl<T: Grault> Grault for (T,)
where
Self::A: Baz,
Self::B: Fiz,
{
type A = ();
//~^ ERROR overflow evaluating the requirement `<(T,) as Grault>::A == _`
type B = bool;
//~^ ERROR overflow evaluating the requirement `<(T,) as Grault>::A == _`
}
//~^^^^^^^^^^ ERROR overflow evaluating the requirement `<(T,) as Grault>::A == _`
fn main() {
let x: <(_,) as Grault>::A = ();<|fim▁hole|>}<|fim▁end|> | |
<|file_name|>globals.d.ts<|end_file_name|><|fim▁begin|>/// <reference lib="es2015" />
type StackTraceRecord = {
[key: string]: string;
}
declare class Exception extends Error {
name: string;
previous?: Exception|Error;
code: number;
/**
* The parsed stack trace for this exception.
*/
readonly stackTrace: StackTraceRecord[];
/**<|fim▁hole|> * The exception message.
*/
message: string;
/**
* Constructor.
*/
__construct(message?: string, code?: number, previous?: Error): void;
constructor(message?: string, code?: number, previous?: Error);
/**
* Parses the stack trace of the given error and
* returns it as an key-value object.
*/
static parseStackTrace(error: Error): StackTraceRecord[];
private _message: string;
private _stackTrace: Record<string, string>[];
private _originalStack: string;
}
declare class BadMethodCallException extends Exception {}
declare class DomainException extends Exception {}
declare class InvalidArgumentException extends Exception {}
declare class LogicException extends Exception {}
declare class OutOfBoundsException extends Exception {}
declare class RuntimeException extends Exception {}
declare class UnderflowException extends Exception {}
declare class UnexpectedValueException extends Exception {}
export {};
declare global {
namespace NodeJS {
interface Global {
Exception: Newable<Exception>;
BadMethodCallException: Newable<BadMethodCallException>;
DomainException: Newable<DomainException>;
InvalidArgumentException: Newable<InvalidArgumentException>;
LogicException: Newable<LogicException>;
OutOfBoundsException: Newable<OutOfBoundsException>;
RuntimeException: Newable<RuntimeException>;
UnderflowException: Newable<UnderflowException>;
UnexpectedValueException: Newable<UnexpectedValueException>;
}
}
}<|fim▁end|> | |
<|file_name|>flasher.py<|end_file_name|><|fim▁begin|>import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flasher_cli.command(short_help='Upload binaries to the microcontroller.', aliases=['upload'])
@click.option('-sfs/-dfs', '--save-file-system/--delete-file-system', is_flag=True, default=False,
help='Specify whether or not to save the file system when writing to the Cortex. Saving the '
'file system takes more time.')
@click.option('-y', is_flag=True, default=False,
help='Automatically say yes to all confirmations.')
@click.option('-f', '-b', '--file', '--binary', default='default', metavar='FILE',
help='Specifies a binary file, project directory, or project config file.')
@click.option('-p', '--port', default='auto', metavar='PORT', help='Specifies the serial port.')
@click.option('--no-poll', is_flag=True, default=False)
@click.option('-r', '--retry', default=2,
help='Specify the number of times the flasher should retry the flash when it detects a failure'
<|fim▁hole|># help='Specify the microcontroller upload strategy. Not currently used.')
def flash(ctx, save_file_system, y, port, binary, no_poll, retry):
"""Upload binaries to the microcontroller. A serial port and binary file need to be specified.
By default, the port is automatically selected (if you want to be pedantic, 'auto').
Otherwise, a system COM port descriptor needs to be used. In Windows/NT, this takes the form of COM1.
In *nx systems, this takes the form of /dev/tty1 or /dev/acm1 or similar.
\b
Specifying 'all' as the COM port will automatically upload to all available microcontrollers.
By default, the CLI will look around for a proper binary to upload to the microcontroller. If one was not found, or
if you want to change the default binary, you can specify it.
"""
click.echo(' ====:: PROS Flasher v{} ::===='.format(get_version()))
if port == 'auto':
ports = prosflasher.ports.list_com_ports()
if len(ports) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
click.get_current_context().abort()
sys.exit(1)
port = ports[0].device
if len(ports) > 1 and port is not None and y is False:
port = None
for p in ports:
if click.confirm('Download to ' + p.device, default=True):
port = p.device
break
if port is None:
click.echo('No additional ports found.')
click.get_current_context().abort()
sys.exit(1)
if port == 'all':
port = [p.device for p in prosflasher.ports.list_com_ports()]
if len(port) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
click.get_current_context().abort()
sys.exit(1)
if y is False:
click.confirm('Download to ' + ', '.join(port), default=True, abort=True, prompt_suffix='?')
else:
port = [port]
if binary == 'default':
binary = os.getcwd()
if ctx.verbosity > 3:
click.echo('Default binary selected, new directory is {}'.format(binary))
binary = find_binary(binary)
if binary is None:
click.echo('No binary was found! Ensure you are in a built PROS project (run make) '
'or specify the file with the -f flag',
err=True)
click.get_current_context().exit()
if ctx.verbosity > 3:
click.echo('Final binary is {}'.format(binary))
click.echo('Flashing ' + binary + ' to ' + ', '.join(port))
for p in port:
tries = 1
code = prosflasher.upload.upload(p, y, binary, no_poll, ctx)
while tries <= retry and (not code or code == -1000):
click.echo('Retrying...')
code = prosflasher.upload.upload(p, y, binary, no_poll, ctx)
tries += 1
def find_binary(path):
"""
Helper function for finding the binary associated with a project
The algorithm is as follows:
- if it is a file, then check if the name of the file is 'pros.config':
- if it is 'pros.config', then find the binary based off the pros.config value (or default 'bin/output.bin')
- otherwise, can only assume it is the binary file to upload
- if it is a directory, start recursively searching up until 'pros.config' is found. max 10 times
- if the pros.config file was found, find binary based off of the pros.config value
- if no pros.config file was found, start recursively searching up (from starting path) until a directory
named bin is found
- if 'bin' was found, return 'bin/output.bin'
:param path: starting path to start the search
:param ctx:
:return:
"""
# logger = logging.getLogger(ctx.log_key)
# logger.debug('Finding binary for {}'.format(path))
if os.path.isfile(path):
if ntpath.basename(path) == 'pros.config':
pros_cfg = prosconfig.ProjectConfig(path)
return os.path.join(path, pros_cfg.output)
return path
elif os.path.isdir(path):
try:
cfg = prosconfig.ProjectConfig(path, raise_on_error=True)
if cfg is not None and os.path.isfile(os.path.join(cfg.directory, cfg.output)):
return os.path.join(cfg.directory, cfg.output)
except prosconfig.ConfigNotFoundException:
search_dir = path
for n in range(10):
dirs = [d for d in os.listdir(search_dir)
if os.path.isdir(os.path.join(path, search_dir, d)) and d == 'bin']
if len(dirs) == 1: # found a bin directory
if os.path.isfile(os.path.join(path, search_dir, 'bin', 'output.bin')):
return os.path.join(path, search_dir, 'bin', 'output.bin')
search_dir = ntpath.split(search_dir)[:-1][0] # move to parent dir
return None
@flasher_cli.command('poll', short_help='Polls a microcontroller for its system info')
@click.option('-y', '--yes', is_flag=True, default=False,
help='Automatically say yes to all confirmations.')
@click.argument('port', default='all')
@default_cfg
def get_sys_info(cfg, yes, port):
if port == 'auto':
ports = prosflasher.ports.list_com_ports()
if len(ports) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
sys.exit(1)
port = prosflasher.ports.list_com_ports()[0].device
if port is not None and yes is False:
click.confirm('Poll ' + port, default=True, abort=True, prompt_suffix='?')
if port == 'all':
port = [p.device for p in prosflasher.ports.list_com_ports()]
if len(port) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
sys.exit(1)
else:
port = [port]
for p in port:
sys_info = prosflasher.upload.ask_sys_info(prosflasher.ports.create_serial(p, serial.PARITY_EVEN), cfg)
click.echo(repr(sys_info))
pass
@flasher_cli.command(short_help='List connected microcontrollers')
@default_cfg
def lsusb(cfg):
if len(prosflasher.ports.list_com_ports()) == 0 or prosflasher.ports.list_com_ports() is None:
click.echo('No serial ports found.')
else:
click.echo('Available Ports:')
click.echo(prosflasher.ports.create_port_list(cfg.verbosity > 0))
# @flasher_cli.command(name='dump-cortex', short_help='Dumps user flash contents to a specified file')
# @click.option('-v', '--verbose', is_flag=True)
# @click.argument('file', default=sys.stdout, type=click.File())
# def dump_cortex(file, verbose):
# pass<|fim▁end|> | ' (default two times).')
@default_cfg
# @click.option('-m', '--strategy', default='cortex', metavar='STRATEGY',
|
<|file_name|>data.rs<|end_file_name|><|fim▁begin|>import!();
requests!(DataQuery, data);
impl<'c> DataQuery<'c> {
path!(data_bag);
path!(item);<|fim▁hole|><|fim▁end|> | acls!();
} |
<|file_name|>askpass_client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- Mode: python -*-
# Copyright (c) 2009, Andrew McNabb
"""Implementation of SSH_ASKPASS to get a password to ssh from pssh.
The password is read from the socket specified by the environment variable
PSSH_ASKPASS_SOCKET. The other end of this socket is pssh.
The ssh man page discusses SSH_ASKPASS as follows:
If ssh needs a passphrase, it will read the passphrase from the current
terminal if it was run from a terminal. If ssh does not have a terminal
associated with it but DISPLAY and SSH_ASKPASS are set, it will execute
the program specified by SSH_ASKPASS and open an X11 window to read the
passphrase. This is particularly useful when calling ssh from a .xsession
or related script. (Note that on some machines it may be necessary to
redirect the input from /dev/null to make this work.)
"""
import os
import socket
import sys
import textwrap
bin_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
askpass_bin_path = os.path.join(bin_dir, 'pssh-askpass')
ASKPASS_PATHS = (askpass_bin_path,<|fim▁hole|> '/usr/local/libexec/pssh/pssh-askpass',
'/usr/lib/pssh/pssh-askpass',
'/usr/local/lib/pssh/pssh-askpass')
_executable_path = None
def executable_path():
"""Determines the value to use for SSH_ASKPASS.
The value is cached since this may be called many times.
"""
global _executable_path
if _executable_path is None:
for path in ASKPASS_PATHS:
if os.access(path, os.X_OK):
_executable_path = path
break
else:
_executable_path = ''
sys.stderr.write(textwrap.fill("Warning: could not find an"
" executable path for askpass because PSSH was not"
" installed correctly. Password prompts will not work."))
sys.stderr.write('\n')
return _executable_path
def askpass_main():
"""Connects to pssh over the socket specified at PSSH_ASKPASS_SOCKET."""
verbose = os.getenv('PSSH_ASKPASS_VERBOSE')
# It's not documented anywhere, as far as I can tell, but ssh may prompt
# for a password or ask a yes/no question. The command-line argument
# specifies what is needed.
if len(sys.argv) > 1:
prompt = sys.argv[1]
if verbose:
sys.stderr.write('pssh-askpass received prompt: "%s"\n' % prompt)
if not prompt.strip().lower().endswith('password:'):
sys.stderr.write(prompt)
sys.stderr.write('\n')
sys.exit(1)
else:
sys.stderr.write('Error: pssh-askpass called without a prompt.\n')
sys.exit(1)
address = os.getenv('PSSH_ASKPASS_SOCKET')
if not address:
sys.stderr.write(textwrap.fill("pssh error: SSH requested a password."
" Please create SSH keys or use the -A option to provide a"
" password."))
sys.stderr.write('\n')
sys.exit(1)
sock = socket.socket(socket.AF_UNIX)
try:
sock.connect(address)
except socket.error:
_, e, _ = sys.exc_info()
message = e.args[1]
sys.stderr.write("Couldn't bind to %s: %s.\n" % (address, message))
sys.exit(2)
try:
password = sock.makefile().read()
except socket.error:
sys.stderr.write("Socket error.\n")
sys.exit(3)
print(password)
if __name__ == '__main__':
askpass_main()<|fim▁end|> | '/usr/libexec/pssh/pssh-askpass', |
<|file_name|>cell.js<|end_file_name|><|fim▁begin|>var STATE_START = 0;
var STATE_END = 1;
var STATE_GROUND = 2;
var STATE_FOREST = 3;
var STATE_WATER = 4;
function Cell(col, row) {
this.col = col;
this.row = row;
this.state = STATE_GROUND;
}
Cell.prototype.draw = function() {
stroke(66);
switch (this.state) {
case STATE_START:
Color.Material.light_green[5].fill();
break;
case STATE_END:
Color.Material.red[5].fill();
break;
case STATE_GROUND:
Color.Material.green[5].fill();
break;
case STATE_FOREST:
Color.Material.green[9].fill();
break;
case STATE_WATER:
Color.Material.light_blue[5].fill();
break;<|fim▁hole|> }
rect(this.col * scl, this.row * scl, scl, scl);
};
Cell.prototype.incrementState = function(bool) {
if (bool) { // Cycle from 0 to 1
this.state = (++this.state > 1) ? 0 : this.state;
} else { // Cycle from 2 to 4
this.state = (++this.state < 2 || this.state > 4) ? 2 : this.state;
}
//this.state = (++this.state > 4) ? 0 : this.state;
//loop();
};<|fim▁end|> | default:
fill(255, 0, 0); |
<|file_name|>AbstractHiloIdGenerator.ts<|end_file_name|><|fim▁begin|>import { IHiloIdGenerator } from "./IHiloIdGenerator";
import { IDocumentStore } from "../../Documents/IDocumentStore";
import { DocumentConventions } from "../../Documents/Conventions/DocumentConventions";
import { IRavenObject } from "../../Types/IRavenObject";
import { getLogger } from "../../Utility/LogUtil";
const log = getLogger({ module: "HiloIdGenerator" });
export abstract class AbstractHiloIdGenerator {
protected _generators: IRavenObject<IHiloIdGenerator> = {};
protected _store: IDocumentStore;
protected _conventions: DocumentConventions;
protected _dbName: string;
protected _tag: string;
protected constructor(store: IDocumentStore, dbName?: string, tag?: string) {
this._tag = tag;
this._store = store;
this._conventions = store.conventions;
this._dbName = dbName || store.database;
}
public returnUnusedRange(): Promise<void> {
const returnPromises = Object.keys(this._generators)
.map(key => {
return Promise.resolve()
.then(() => this._generators[key].returnUnusedRange())
.catch(err => {
log.warn(err, "Error returning unused range");
});
});<|fim▁hole|> // tslint:disable-next-line:no-empty
.then(() => {
});
}
}<|fim▁end|> |
return Promise.all(returnPromises) |
<|file_name|>RTBench.java<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2010-11 The AEminium Project (see AUTHORS file)
*
<|fim▁hole|> * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plaid Programming Language 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 Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>.
*/
package aeminium.runtime.tools.benchmark;
public class RTBench {
private static Benchmark[] benchmarks = {
new TaskCreationBenchmark(),
new IndependentTaskGraph(),
new LinearTaskGraph(),
new FixedParallelMaxDependencies(),
new ChildTaskBenchmark(),
new FibonacciBenchmark()
};
public static void usage() {
System.out.println();
System.out.println("java aeminium.runtime.tools.benchmark.RTBench COMMAND");
System.out.println("");
System.out.println("COMMANDS:");
System.out.println(" list - List available benchmarks.");
System.out.println(" run BENCHMARK - Run specified benchmark.");
System.out.println();
}
public static void main(String[] args) {
if ( args.length == 0 ) {
usage();
return;
}
if ( args[0].equals("list") ) {
for( Benchmark benchmark : benchmarks ) {
System.out.println(benchmark.getName());
}
} else if ( args[0].equals("run") && args.length == 2 ) {
Benchmark benchmark = null;
for ( Benchmark b : benchmarks ) {
if ( b.getName().equals(args[1])) {
benchmark = b;
}
}
if ( benchmark != null ) {
Reporter reporter = new StringBuilderReporter();
reporter.startBenchmark(benchmark.getName());
benchmark.run(reporter);
reporter.stopBenchmark(benchmark.getName());
reporter.flush();
} else {
usage();
}
} else {
usage();
}
}
protected static void reportVMStats(Reporter reporter) {
reporter.reportLn(String.format("Memory (TOTAL/MAX/FREE) (%d,%d,%d)", Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory(),
Runtime.getRuntime().freeMemory()));
}
}<|fim▁end|> | * This file is part of Plaid Programming Language.
*
* Plaid Programming Language is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
|
<|file_name|>image_provider.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
import random
import paddle.utils.image_util as image_util
from paddle.trainer.PyDataProvider2 import *
#
# {'img_size': 32,
# 'settings': a global object,
# 'color': True,
# 'mean_img_size': 32,
# 'meta': './data/cifar-out/batches/batches.meta',
# 'num_classes': 10,
# 'file_list': ('./data/cifar-out/batches/train_batch_000',),
# 'use_jpeg': True}
def hook(settings, img_size, mean_img_size, num_classes, color, meta, use_jpeg,
is_train, **kwargs):
settings.mean_img_size = mean_img_size
settings.img_size = img_size
settings.num_classes = num_classes
settings.color = color
settings.is_train = is_train<|fim▁hole|> else:
settings.img_raw_size = settings.img_size * settings.img_size
settings.meta_path = meta
settings.use_jpeg = use_jpeg
settings.img_mean = image_util.load_meta(settings.meta_path,
settings.mean_img_size,
settings.img_size, settings.color)
settings.logger.info('Image size: %s', settings.img_size)
settings.logger.info('Meta path: %s', settings.meta_path)
settings.input_types = {
'image': dense_vector(settings.img_raw_size),
'label': integer_value(settings.num_classes)
}
settings.logger.info('DataProvider Initialization finished')
@provider(init_hook=hook, min_pool_size=0)
def processData(settings, file_list):
"""
The main function for loading data.
Load the batch, iterate all the images and labels in this batch.
file_list: the batch file list.
"""
with open(file_list, 'r') as fdata:
lines = [line.strip() for line in fdata]
random.shuffle(lines)
for file_name in lines:
with io.open(file_name.strip(), 'rb') as file:
data = cPickle.load(file)
indexes = list(range(len(data['images'])))
if settings.is_train:
random.shuffle(indexes)
for i in indexes:
if settings.use_jpeg == 1:
img = image_util.decode_jpeg(data['images'][i])
else:
img = data['images'][i]
img_feat = image_util.preprocess_img(
img, settings.img_mean, settings.img_size,
settings.is_train, settings.color)
label = data['labels'][i]
yield {
'image': img_feat.astype('float32'),
'label': int(label)
}<|fim▁end|> |
if settings.color:
settings.img_raw_size = settings.img_size * settings.img_size * 3 |
<|file_name|>startup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# 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/>.
from gRefer import log
def start_notifier():
import os
from gRefer.config_constants import dir_name, bibfiler_log_file
from gRefer.log import NotifyHandler
import logging
import logging.handlers
logger = logging.getLogger(name="Notifier")
if not os.path.exists(dir_name):
os.makedirs(dir_name)
fh = logging.handlers.TimedRotatingFileHandler(
os.path.join(dir_name,bibfiler_log_file),
when="midnight",
backupCount="7"
)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.root.addHandler(NotifyHandler())
logger.root.addHandler(fh)
logger.setLevel(log.TRACE)<|fim▁hole|>
run_systray()<|fim▁end|> | logger.root.setLevel(log.TRACE)
from gRefer.filer.systray import run_systray |
<|file_name|>coreclrcallbacks.cpp<|end_file_name|><|fim▁begin|>//<|fim▁hole|>//
#include "standardpch.h"
#include "coreclrcallbacks.h"
#include "iexecutionengine.h"
typedef LPVOID (__stdcall * pfnEEHeapAllocInProcessHeap)(DWORD dwFlags, SIZE_T dwBytes);
typedef BOOL (__stdcall * pfnEEHeapFreeInProcessHeap)(DWORD dwFlags, LPVOID lpMem);
CoreClrCallbacks *original_CoreClrCallbacks = nullptr;
pfnEEHeapAllocInProcessHeap original_EEHeapAllocInProcessHeap = nullptr;
pfnEEHeapFreeInProcessHeap original_EEHeapFreeInProcessHeap = nullptr;
IExecutionEngine* STDMETHODCALLTYPE IEE_t()
{
interceptor_IEE *iee = new interceptor_IEE();
iee->original_IEE = original_CoreClrCallbacks->m_pfnIEE();
return iee;
}
/*#pragma warning( suppress :4996 ) //deprecated
HRESULT STDMETHODCALLTYPE GetCORSystemDirectory(LPWSTR pbuffer, DWORD cchBuffer, DWORD* pdwlength)
{
DebugBreakorAV(131);
return 0;
}
*/
LPVOID STDMETHODCALLTYPE EEHeapAllocInProcessHeap (DWORD dwFlags, SIZE_T dwBytes)
{
if(original_EEHeapAllocInProcessHeap == nullptr)
__debugbreak();
return original_EEHeapAllocInProcessHeap(dwFlags, dwBytes);
}
BOOL STDMETHODCALLTYPE EEHeapFreeInProcessHeap (DWORD dwFlags, LPVOID lpMem)
{
if(original_EEHeapFreeInProcessHeap == nullptr)
__debugbreak();
return original_EEHeapFreeInProcessHeap(dwFlags, lpMem);
}
void* STDMETHODCALLTYPE GetCLRFunction(LPCSTR functionName)
{
if(strcmp(functionName, "EEHeapAllocInProcessHeap")==0)
{
original_EEHeapAllocInProcessHeap =
(pfnEEHeapAllocInProcessHeap)original_CoreClrCallbacks->m_pfnGetCLRFunction("EEHeapAllocInProcessHeap");
return (void*)EEHeapAllocInProcessHeap;
}
if(strcmp(functionName, "EEHeapFreeInProcessHeap")==0)
{
original_EEHeapFreeInProcessHeap =
(pfnEEHeapFreeInProcessHeap)original_CoreClrCallbacks->m_pfnGetCLRFunction("EEHeapFreeInProcessHeap");
return (void*)EEHeapFreeInProcessHeap;
}
return original_CoreClrCallbacks->m_pfnGetCLRFunction(functionName);
}<|fim▁end|> | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
<|file_name|>plotLFs-color-mag-trends.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
"""
This script produces quality plots to check that the LFs are fine compared to simumlations.
"""
import sys
import os
from os.path import join
data_dir = os.environ['DATA_DIR']
import glob
from lib_plot import *
#from lineListAir import *
SNlim = 5
# "D:\data\LF-O\LFmodels\data\trends_color_mag\O2_3728-VVDSDEEPI24-z0.947.txt"
plotDir="/home/comparat/database/Simulations/galform-lightcone/products/emissionLineLuminosityFunctions/plots/"
dir="/home/comparat/database/Simulations/galform-lightcone/products/emissionLineLuminosityFunctions/O2_3728/"
lf_measurement_files_ref=n.array(glob.glob(dir+"*MagLimR-24.2-z0.7*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*MagLimR-*z0.7*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ len(lf_measurement_files), len(dataRef[0]) ])
label = n.array([ "R<23.0","R<23.5", "R<24.2"])
for ii,el in enumerate(lf_measurement_files) :
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((1e40,1e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=2)
p.savefig(join(plotDir,"trends_O2_3728_Rmag-z0.7.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*MagLimR-24.2-z0.9*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*MagLimR-*z0.9*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ len(lf_measurement_files), len(dataRef[0]) ])
label = n.array([ "R<23.0","R<23.5", "R<24.2"])
for ii,el in enumerate(lf_measurement_files) :
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((1e40,1e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=2)
p.savefig(join(plotDir,"trends_O2_3728_Rmag-z0.9.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*MagLimR-24.2-z1.*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*MagLimR-*z1.*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ len(lf_measurement_files), len(dataRef[0]) ])
label = n.array([ "R<23.0","R<23.5", "R<24.2"])
for ii,el in enumerate(lf_measurement_files) :
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((1e40,1e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=2)
p.savefig(join(plotDir,"trends_O2_3728_Rmag-z1.2.pdf"))
p.clf()
########################################33
lf_measurement_files_ref=n.array(glob.glob(dir+"*MagLimI-24-z1.*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*MagLimI-*z1.*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ len(lf_measurement_files), len(dataRef[0]) ])
label = n.array([ "I<22.5", "I<23.0","I<23.5","I<24.0"])
for jj,el in enumerate(lf_measurement_files) :
data= n.loadtxt( el, unpack=True)
phiRatio[jj] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((1e40,1e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=2)
p.savefig(join(plotDir,"trends_O2_3728_Imag-z1.2.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*MagLimI-24-z0.9*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*MagLimI-*z0.9*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ len(lf_measurement_files), len(dataRef[0]) ])
label = n.array([ "I<22.5", "I<23.0","I<23.5","I<24.0"])
for jj,el in enumerate(lf_measurement_files) :
data= n.loadtxt( el, unpack=True)
phiRatio[jj] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((1e40,1e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=2)
p.savefig(join(plotDir,"trends_O2_3728_Imag-z0.9.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*MagLimI-24-z0.7*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*MagLimI-*z0.7*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ len(lf_measurement_files), len(dataRef[0]) ])
label = n.array([ "I<22.5", "I<23.0","I<23.5","I<24.0"])
for jj,el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[jj] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((1e40,1e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=2)
p.savefig(join(plotDir,"trends_O2_3728_Imag-z0.75.pdf"))
p.clf()
#####################################3
#####################################3
# R-Z
#####################################3
#####################################3
lf_measurement_files_ref=n.array(glob.glob(dir+"*VVDSrz_gt_0.0-z0.7*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*VVDSrz_?t_*z0.7*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
label = n.array(["r-z>0", "r-z>0.5", "r-z>1", "r-z>1.5", "r-z<1", "r-z<1.5", "r-z<2"])
phiRatio = n.empty([ 7, len(dataRef[0]) ])
for ii, el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=4)
p.savefig(join(plotDir,"trends_O2_3728_I22.5_RZ-z0.75.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*VVDSrz_gt_0.0-z0.9*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*VVDSrz_?t_*z0.9*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ 7, len(dataRef[0]) ])
for ii, el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=4)
p.savefig(join(plotDir,"trends_O2_3728_I22.5_RZ-z0.9.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*VVDSrz_gt_0.0-z1.*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*VVDSrz_?t_*z1.*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
phiRatio = n.empty([ 7, len(dataRef[0]) ])
for ii, el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=4)
p.savefig(join(plotDir,"trends_O2_3728_I22.5_RZ-z1.2.pdf"))
p.clf()
#####################################3
#####################################3
# G-R
#####################################3
#####################################3
lf_measurement_files_ref=n.array(glob.glob(dir+"*VVDSgr_gt_0.0-z0.7*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*VVDSgr_?t_*z0.7*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
label = n.array(["g-r>0", "g-r>0.5", "g-r>1", "g-r>1.5", "g-r<1", "g-r<1.5", "g-r<2"])
phiRatio = n.empty([ 7, len(dataRef[0]) ])
for ii, el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=4)
p.savefig(join(plotDir,"trends_O2_3728_I22.5_GR-z0.75.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*VVDSgr_gt_0.0-z0.9*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*VVDSgr_?t_*z0.9*.txt"))
lf_measurement_files.sort()<|fim▁hole|>
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
label = n.array(["g-r>0", "g-r>0.5", "g-r>1", "g-r>1.5", "g-r<1", "g-r<1.5", "g-r<2"])
phiRatio = n.empty([ 7, len(dataRef[0]) ])
for ii, el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=4)
p.savefig(join(plotDir,"trends_O2_3728_I22.5_GR-z0.9.pdf"))
p.clf()
lf_measurement_files_ref=n.array(glob.glob(dir+"*VVDSgr_gt_0.0-z1.*.txt"))
lf_measurement_files=n.array(glob.glob(dir+"*VVDSgr_?t_*z1.*.txt"))
lf_measurement_files.sort()
dataRef = n.loadtxt( lf_measurement_files_ref[0], unpack=True)
label = n.array(["g-r>0", "g-r>0.5", "g-r>1", "g-r>1.5", "g-r<1", "g-r<1.5", "g-r<2"])
phiRatio = n.empty([ 7, len(dataRef[0]) ])
for ii, el in enumerate(lf_measurement_files):
data= n.loadtxt( el, unpack=True)
phiRatio[ii] = data[3] / dataRef[3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.ylim((-0.05,1.05))
p.grid()
p.legend(loc=4)
p.savefig(join(plotDir,"trends_O2_3728_I22.5_GR-z1.2.pdf"))
p.clf()<|fim▁end|> | |
<|file_name|>workspace.rs<|end_file_name|><|fim▁begin|>// use layout::{Layout, LayoutMessage};
use core::Stack;
use std::fmt::Debug;
/// Represents a single workspace with a `tag` (name),
/// `id`, a `layout` and a `stack` for all windows.
/// A workspace is in charge of all windows belonging
/// to that workspace. At each time, a single screen
/// holds one workspace, while all the other
/// workspaces are hidden in the background, while
/// still being managed.
///
/// # Immutable
///
/// Note that this [`Workspace`] implementation is immutable
/// and that each operation that would modify it, instead
/// returns a new copy of the [`Workspace`] with the modified state.
///
/// [`Workspace`]: struct.Stack.html
pub struct Workspace<Window> {
///
pub id: u32,
///
pub tag: String,
///
pub stack: Option<Stack<Window>>,
}
impl<Window: Clone> Clone for Workspace<Window> {
fn clone(&self) -> Workspace<Window> {
Workspace {
id: self.id,
tag: self.tag.clone(),
stack: self.stack.clone(),
}
}
}
impl<Window: Copy + Clone + PartialEq + Eq + Debug> Workspace<Window> {
/// Create a new workspace
///
/// # Examples
///
/// ```
/// # use sabiwm::core::{Stack, Workspace};
/// let stack = Stack::from(42u32);
/// let workspace = Workspace::new(0, "Desktop 0", Some(stack));
/// assert_eq!(1, workspace.len());
/// ```
pub fn new<S: Into<String>>(id: u32,
tag: S,
stack: Option<Stack<Window>>)
-> Workspace<Window> {
let tag = tag.into();
trace!("workspace_tag {}, workspace_id {}: creating new workspace",
tag,
id);
Workspace {
id: id,
tag: tag,
stack: stack,
}
}
/// Add a new window to the workspace by adding it to the stack.
/// If the stack doesn't exist yet, create one.
///
/// # Examples
///
/// ```
/// # use sabiwm::core::Workspace;
/// let workspace : Workspace<u32> = Workspace::new(0, "Desktop 0", None);
/// assert_eq!(0, workspace.len());
/// ```
pub fn add(&self, window: Window) -> Workspace<Window> {
trace!("workspace_tag {}, workspace_id {}: adding window {:?} to workspace",
self.tag,
self.id,
window);<|fim▁hole|> self.tag.clone(),
Some(self.stack
.clone()
.map_or(Stack::from(window), |s| s.add(window))))
}
/// Remove the given window from the workspace.
///
/// # Arguments
/// `window` - The window to remove
///
/// # Return value
/// A new [`Workspace`] without the window
///
/// [`Workspace`]: struct.Workspace.html
pub fn remove(&self, window: Window) -> Workspace<Window> {
trace!("workspace_tag {}, workspace_id {}: removing window {:?} from workspace",
self.tag,
self.id,
window);
Workspace::new(self.id,
self.tag.clone(),
self.stack
.clone()
.map_or(None, |s| s.filter(|&w| w != window)))
}
/// Returns the number of windows contained in this [`Workspace`]
///
/// # Return value
/// Number of windows in this [`Workspace`]
/// [`Workspace`]: struct.Workspace.html
pub fn len(&self) -> usize {
self.stack.clone().map_or(0, |x| x.len())
}
/// Checks if the [`Workspace`] is empty, i.e. if it is not
/// managing any windows.
///
/// # Return value
/// `true` if the [`Workspace`] is empty
/// [`Workspace`]: struct.Workspace.html
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Checks if the workspace contains the given window
/// [`Workspace`]: struct.Workspace.html
pub fn contains(&self, window: Window) -> bool {
trace!("workspace_tag {}, workspace_id {}: checking if workspace contains window {:?}",
self.tag,
self.id,
window);
self.stack.clone().map_or(false, |x| x.contains(window))
}
/// [`Workspace`]: struct.Workspace.html
pub fn windows(&self) -> Vec<Window> {
self.stack.clone().map_or(Vec::new(), |s| s.integrate())
}
/// [`Workspace`]: struct.Workspace.html
pub fn peek(&self) -> Option<Window> {
self.stack.clone().map(|s| s.focus)
}
/// [`Workspace`]: struct.Workspace.html
pub fn map<F>(&self, f: F) -> Workspace<Window>
where F: Fn(Stack<Window>) -> Stack<Window>
{
trace!("workspace_tag {}, workspace_id {}: mapping over workspace",
self.tag,
self.id);
Workspace::new(self.id, self.tag.clone(), self.stack.clone().map(f))
}
/// [`Workspace`]: struct.Workspace.html
pub fn map_option<F>(&self, f: F) -> Workspace<Window>
where F: Fn(Stack<Window>) -> Option<Stack<Window>>
{
trace!("workspace_tag {}, workspace_id {}: mapping optional over workspace",
self.tag,
self.id);
Workspace::new(self.id,
self.tag.clone(),
self.stack.clone().map_or(None, f))
}
/// [`Workspace`]: struct.Workspace.html
pub fn map_or<F>(&self, default: Stack<Window>, f: F) -> Workspace<Window>
where F: Fn(Stack<Window>) -> Stack<Window>
{
trace!("workspace_tag {}, workspace_id {}: mapping default over workspace",
self.tag,
self.id);
Workspace::new(self.id,
self.tag.clone(),
Some(self.stack.clone().map_or(default, f)))
}
}<|fim▁end|> | Workspace::new(self.id, |
<|file_name|>webui.go<|end_file_name|><|fim▁begin|>package corehttp
// TODO: move to IPNS
const WebUIPath = "/ipfs/QmXc9raDM1M5G5fpBnVyQ71vR4gbnskwnB9iMEzBuLgvoZ"
<|fim▁hole|> "/ipfs/QmUnXcWZC5Ve21gUseouJsH5mLAyz5JPp8aHsg8qVUUK8e",
"/ipfs/QmSDgpiHco5yXdyVTfhKxr3aiJ82ynz8V14QcGKicM3rVh",
"/ipfs/QmRuvWJz1Fc8B9cTsAYANHTXqGmKR9DVfY5nvMD1uA2WQ8",
"/ipfs/QmQLXHs7K98JNQdWrBB2cQLJahPhmupbDjRuH1b9ibmwVa",
"/ipfs/QmXX7YRpU7nNBKfw75VG7Y1c3GwpSAGHRev67XVPgZFv9R",
"/ipfs/QmXdu7HWdV6CUaUabd9q2ZeA4iHZLVyDRj3Gi4dsJsWjbr",
"/ipfs/QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w",
"/ipfs/QmSHDxWsMPuJQKWmVA1rB5a3NX2Eme5fPqNb63qwaqiqSp",
"/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz",
"/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6",
"/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm",
"/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr",
"/ipfs/QmU3o9bvfenhTKhxUakbYrLDnZU7HezAVxPM6Ehjw9Xjqy",
"/ipfs/QmPhnvn747LqwPYMJmQVorMaGbMSgA7mRRoyyZYz3DoZRQ",
}
var WebUIOption = RedirectOption("webui", WebUIPath)<|fim▁end|> | // this is a list of all past webUI paths.
var WebUIPaths = []string{
WebUIPath,
"/ipfs/QmenEBWcAk3tN94fSKpKFtUMwty1qNwSYw3DMDFV6cPBXA", |
<|file_name|>test_game.py<|end_file_name|><|fim▁begin|>from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board, None)
self.assertEqual(self.game.width, self.width)
self.assertEqual(self.game.height, self.height)
self.assertEqual(self.game.num_of_players, self.num_of_players)
self.assertEqual(self.game.players, [])
self.assertEqual(self.game.round_counter, 0)<|fim▁hole|> self.assertEqual(self.game.on_turn, 0)
def test_setup(self):
input_seq = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
expected = [('Luke', 'x'), ('Leia', 'o')]
for e, p in zip(expected, self.game.players):
self.assertEqual(p.name, e[0])
self.assertEqual(p.symbol, e[1])
def test_play_round(self):
# setup
input_seq = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
input_seq = ['2', '5', '3', '1', '9', '6', '7', '4']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.play_round()
finished, winner = self.game.board.finished()
self.assertTrue(finished)
self.assertEqual(winner, 1)
expected_board = [[1, 0, 0], [1, 1, 1], [0, None, 0]]
self.assertEqual(self.game.board.grid, expected_board)<|fim▁end|> | |
<|file_name|>keyboard.rs<|end_file_name|><|fim▁begin|>use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use hashbrown::HashSet;
use d7keymap::{KeyAction, KeyCodes, KeyMap, KeySymbol};
use libd7::ipc::{self, protocol::keyboard::KeyboardEvent};
pub struct Keyboard {
keycodes: KeyCodes,
keymap: KeyMap,
pub pressed_modifiers: HashSet<KeySymbol>,
}
impl Keyboard {
pub fn new() -> Self {
let keycodes_json: Vec<u8> =
ipc::request("initrd/read", "keycodes.json".to_owned()).unwrap();
let keymap_json: Vec<u8> = ipc::request("initrd/read", "keymap.json".to_owned()).unwrap();<|fim▁hole|>
Self {
keycodes: serde_json::from_slice(&keycodes_json).unwrap(),
keymap: serde_json::from_slice(&keymap_json).unwrap(),
pressed_modifiers: HashSet::new(),
}
}
pub fn process_event(&mut self, event: KeyboardEvent) -> EventAction {
if let Some(keysym) = self.keycodes.clone().get(&event.keycode) {
if self.keymap.modifiers.contains(&keysym) {
if event.release {
self.pressed_modifiers.remove(keysym);
} else {
self.pressed_modifiers.insert(keysym.clone());
}
EventAction::Ignore
} else if !event.release {
let result = self.process_keysym_press(&keysym);
if let Some(action) = result {
EventAction::KeyAction(action)
} else {
EventAction::Unmatched(keysym.clone(), self.pressed_modifiers.clone())
}
} else {
EventAction::Ignore
}
} else {
EventAction::NoSuchSymbol
}
}
pub fn process_keysym_press(&mut self, keysym: &KeySymbol) -> Option<KeyAction> {
for (k, v) in &self.keymap.mapping {
if k.matches(keysym, &self.pressed_modifiers) {
return Some(if let KeyAction::Remap(to) = v.clone() {
self.process_keysym_press(&to)?
} else {
v.clone()
});
}
}
None
}
}
#[derive(Debug)]
#[must_use]
pub enum EventAction {
KeyAction(KeyAction),
Unmatched(KeySymbol, HashSet<KeySymbol>),
Ignore,
NoSuchSymbol,
}<|fim▁end|> | |
<|file_name|>q2_sigmoid.py<|end_file_name|><|fim▁begin|>import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your original input x.
"""
f = f * (1. - f)
return f
def test_sigmoid_basic():
"""
Some simple tests to get you started.
Warning: these are not exhaustive.
"""
print "Running basic tests..."
x = np.array([[1, 2], [-1, -2]])
f = sigmoid(x)
g = sigmoid_grad(f)
print f
assert np.amax(f - np.array([[0.73105858, 0.88079708],
[0.26894142, 0.11920292]])) <= 1e-6
print g
assert np.amax(g - np.array([[0.19661193, 0.10499359],
[0.19661193, 0.10499359]])) <= 1e-6
print "You should verify these results!\n"
def test_sigmoid():
"""<|fim▁hole|> """
print "Running your tests..."
### YOUR CODE HERE
raise NotImplementedError
### END YOUR CODE
if __name__ == "__main__":
test_sigmoid_basic();
#test_sigmoid()<|fim▁end|> | Use this space to test your sigmoid implementation by running:
python q2_sigmoid.py
This function will not be called by the autograder, nor will
your tests be graded. |
<|file_name|>simple-struct.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 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<|fim▁hole|>
// compile-flags:-Z extra-debug-info
// debugger:set print pretty off
// debugger:break zzz
// debugger:run
// debugger:finish
// debugger:print no_padding16
// check:$1 = {x = 10000, y = -10001}
// debugger:print no_padding32
// check:$2 = {x = -10002, y = -10003.5, z = 10004}
// debugger:print no_padding64
// check:$3 = {x = -10005.5, y = 10006, z = 10007}
// debugger:print no_padding163264
// check:$4 = {a = -10008, b = 10009, c = 10010, d = 10011}
// debugger:print internal_padding
// check:$5 = {x = 10012, y = -10013}
// debugger:print padding_at_end
// check:$6 = {x = -10014, y = 10015}
struct NoPadding16 {
x: u16,
y: i16
}
struct NoPadding32 {
x: i32,
y: f32,
z: u32
}
struct NoPadding64 {
x: f64,
y: i64,
z: u64
}
struct NoPadding163264 {
a: i16,
b: u16,
c: i32,
d: u64
}
struct InternalPadding {
x: u16,
y: i64
}
struct PaddingAtEnd {
x: i64,
y: u16
}
fn main() {
let no_padding16 = NoPadding16 { x: 10000, y: -10001 };
let no_padding32 = NoPadding32 { x: -10002, y: -10003.5, z: 10004 };
let no_padding64 = NoPadding64 { x: -10005.5, y: 10006, z: 10007 };
let no_padding163264 = NoPadding163264 { a: -10008, b: 10009, c: 10010, d: 10011 };
let internal_padding = InternalPadding { x: 10012, y: -10013 };
let padding_at_end = PaddingAtEnd { x: -10014, y: 10015 };
zzz();
}
fn zzz() {()}<|fim▁end|> | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-win32 Broken because of LLVM bug: http://llvm.org/bugs/show_bug.cgi?id=16249 |
<|file_name|>XHRLoader.js<|end_file_name|><|fim▁begin|>/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.XHRLoader = function ( manager ) {
this.cache = new THREE.Cache();
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.XHRLoader.prototype = {
constructor: THREE.XHRLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var cached = scope.cache.get( url );
if ( cached !== undefined ) {
if ( onLoad ) onLoad( cached );
return;
}
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
scope.cache.add( url, this.response );
if ( onLoad ) onLoad( this.response );
scope.manager.itemEnd( url );<|fim▁hole|> if ( onProgress !== undefined ) {
request.addEventListener( 'progress', function ( event ) {
onProgress( event );
}, false );
}
if ( onError !== undefined ) {
request.addEventListener( 'error', function ( event ) {
onError( event );
}, false );
}
if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
if ( this.responseType !== undefined ) request.responseType = this.responseType;
request.send( null );
scope.manager.itemStart( url );
},
setResponseType: function ( value ) {
this.responseType = value;
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
}
};<|fim▁end|> |
}, false );
|
<|file_name|>test_misc.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014-present PlatformIO <[email protected]>
#
# 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 pytest
import requests
from platformio import exception, util
def test_platformio_cli():
result = util.exec_command(["pio", "--help"])
assert result["returncode"] == 0
assert "Usage: pio [OPTIONS] COMMAND [ARGS]..." in result["out"]
def test_ping_internet_ips():
for host in util.PING_REMOTE_HOSTS:
requests.get("http://%s" % host, allow_redirects=False, timeout=2)
def test_api_internet_offline(without_internet, isolated_pio_home):<|fim▁hole|>
def test_api_cache(monkeypatch, isolated_pio_home):
api_kwargs = {"url": "/stats", "cache_valid": "10s"}
result = util.get_api_result(**api_kwargs)
assert result and "boards" in result
monkeypatch.setattr(util, "_internet_on", lambda: False)
assert util.get_api_result(**api_kwargs) == result<|fim▁end|> | with pytest.raises(exception.InternetIsOffline):
util.get_api_result("/stats") |
<|file_name|>autoderef-method-twice.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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.
// run-pass
#![allow(non_camel_case_types)]
#![feature(box_syntax)]
trait double {
fn double(self: Box<Self>) -> usize;
}
impl double for usize {
fn double(self: Box<usize>) -> usize { *self * 2 }
}
pub fn main() {
let x: Box<Box<_>> = box box 3;<|fim▁hole|>}<|fim▁end|> | assert_eq!(x.double(), 6); |
<|file_name|>generic.py<|end_file_name|><|fim▁begin|># Copyright 2020 Red Hat, Inc. Jake Hunsaker <[email protected]>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.
<|fim▁hole|>import os
import tarfile
class DataDirArchive(SoSObfuscationArchive):
"""A plain directory on the filesystem that is not directly associated with
any known or supported collection utility
"""
type_name = 'data_dir'
description = 'unassociated directory'
@classmethod
def check_is_type(cls, arc_path):
return os.path.isdir(arc_path)
def set_archive_root(self):
return os.path.abspath(self.archive_path)
class TarballArchive(SoSObfuscationArchive):
"""A generic tar archive that is not associated with any known or supported
collection utility
"""
type_name = 'tarball'
description = 'unassociated tarball'
@classmethod
def check_is_type(cls, arc_path):
try:
return tarfile.is_tarfile(arc_path)
except Exception:
return False
def set_archive_root(self):
if self.tarobj.firstmember.isdir():
return self.tarobj.firstmember.name
return ''<|fim▁end|> | from sos.cleaner.archives import SoSObfuscationArchive
|
<|file_name|>game-show.ts<|end_file_name|><|fim▁begin|>import * as Immutable from "immutable";
import * as Command from "../../command";
import * as Game from "../game";
export class State extends Immutable.Record({
command: "",
commandPos: 0,
commandFocused: false,
submittingCommand: false,
commandError: undefined as string | undefined,
suggestions: Immutable.List(),
allSuggestions: Immutable.List(),
subMenuOpen: false,
}) { }
export const UPDATE_COMMAND = "brdgme/pages/game-show/UPDATE_COMMAND";
export const TOGGLE_SUB_MENU = "brdgme/pages/game-show/TOGGLE_SUB_MENU";
export const COMMAND_FOCUS = "brdgme/pages/game-show/COMMAND_FOCUS";
export const COMMAND_BLUR = "brdgme/pages/game-show/COMMAND_BLUR";
export interface IUpdateCommand {
type: typeof UPDATE_COMMAND;
payload: {
command: string;
commandPos: number;
commandSpec?: Immutable.Map<any, any>,
};
}
export const updateCommand = (
command: string,
commandPos: number,
commandSpec?: Immutable.Map<any, any>,
): IUpdateCommand => ({
type: UPDATE_COMMAND,
payload: { command, commandPos, commandSpec },
});
export interface IToggleSubMenu {
type: typeof TOGGLE_SUB_MENU;
}
export const toggleSubMenu = (): IToggleSubMenu => ({ type: TOGGLE_SUB_MENU });
export interface ICommandFocus {
type: typeof COMMAND_FOCUS;
}
export const commandFocus = (): ICommandFocus => ({ type: COMMAND_FOCUS });
export interface ICommandBlur {
type: typeof COMMAND_BLUR;
}
export const commandBlur = (): ICommandBlur => ({ type: COMMAND_BLUR });
type Action
= IUpdateCommand<|fim▁hole|> | Game.Action;
export function reducer(state = new State(), action: Action): State {
switch (action.type) {
case UPDATE_COMMAND: return state
.set("command", action.payload.command)
.set("commandPos", action.payload.commandPos);
case COMMAND_FOCUS: return state.set("commandFocused", true);
case COMMAND_BLUR: return state.set("commandFocused", false);
case TOGGLE_SUB_MENU: return state.update("subMenuOpen", (s) => !s);
case Game.SUBMIT_COMMAND:
case Game.SUBMIT_UNDO:
return state.set("submittingCommand", true);
case Game.SUBMIT_COMMAND_SUCCESS:
case Game.SUBMIT_UNDO_SUCCESS:
return state
.set("submittingCommand", false)
.set("command", "")
.set("commandPos", 0)
.remove("commandError");
case Game.SUBMIT_COMMAND_FAIL: return state
.set("commandError", action.payload)
.set("submittingCommand", false);
case Game.SUBMIT_UNDO_FAIL: return state
.set("submittingCommand", false);
default: return state;
}
}<|fim▁end|> | | IToggleSubMenu
| ICommandFocus
| ICommandBlur |
<|file_name|>TermSource.java<|end_file_name|><|fim▁begin|>//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.magetab;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* A repository of controlled vocabulary terms. Must have a non-null, non-empty name
*/
public final class TermSource {
private String name;
private String file;
private String version;
/**
* Create new TermSource with given name.
* @param name the repository name; must not be blank or null
*/
public TermSource(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Term source name must not be blank");
}
this.name = name;
}
/**
* Create new TermSource with given name, url and version.
* @param name the repository name
* @param file the url (called file in MAGE TAB terminology)
* @param version the version;
*/
public TermSource(String name, String file, String version) {
this(name);
this.file = file;
this.version = version;
}
/**
* @return the file
*/
public String getFile() {
return this.file;
}
/**
* @param file the file to set
*/
public void setFile(String file) {
this.file = file;
}
/**
* @return the name
*/
public String getName() {
<|fim▁hole|>
/**
* @param name the name to set
*/
public void setName(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Term source name must not be blank");
}
this.name = name;
}
/**
* @return the version
*/
public String getVersion() {
return this.version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
this.version = version;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TermSource)) {
return false;
}
if (obj == this) {
return true;
}
TermSource ts = (TermSource) obj;
return new EqualsBuilder().append(this.getName(), ts.getName()).append(this.getFile(), ts.getFile()).append(
this.getVersion(), ts.getVersion()).isEquals();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.getName()).append(this.getFile()).append(this.getVersion())
.toHashCode();
}
}<|fim▁end|> | return this.name;
}
|
<|file_name|>dweet.py<|end_file_name|><|fim▁begin|>"""
A component which allows you to send data to Dweet.io.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/dweet/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNKNOWN
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import state as state_helper
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
DOMAIN = "dweet"
DEPENDENCIES = []
REQUIREMENTS = ['dweepy==0.2.0']
CONF_NAME = 'name'
CONF_WHITELIST = 'whitelist'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)<|fim▁hole|> vol.Required(CONF_WHITELIST): cv.string,
}),
}, extra=vol.ALLOW_EXTRA)
# pylint: disable=too-many-locals
def setup(hass, config):
"""Setup the Dweet.io component."""
conf = config[DOMAIN]
name = conf[CONF_NAME]
whitelist = conf.get(CONF_WHITELIST, [])
json_body = {}
def dweet_event_listener(event):
"""Listen for new messages on the bus and sends them to Dweet.io."""
state = event.data.get('new_state')
if state is None or state.state in (STATE_UNKNOWN, '') \
or state.entity_id not in whitelist:
return
try:
_state = state_helper.state_as_number(state)
except ValueError:
_state = state.state
json_body[state.attributes.get('friendly_name')] = _state
send_data(name, json_body)
hass.bus.listen(EVENT_STATE_CHANGED, dweet_event_listener)
return True
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def send_data(name, msg):
"""Send the collected data to Dweet.io."""
import dweepy
try:
dweepy.dweet_for(name, msg)
except dweepy.DweepyError:
_LOGGER.error("Error saving data '%s' to Dweet.io", msg)<|fim▁end|> |
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_NAME): cv.string, |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import Http404
from django.shortcuts import render_to_response
from django.conf import settings
from django.template import RequestContext
from django.core.cache import parse_backend_uri
from django_memcached.util import get_memcached_stats
from django.contrib.auth.decorators import user_passes_test
_, hosts, _ = parse_backend_uri(settings.CACHE_BACKEND)
SERVERS = hosts.split(';')
def server_list(request):
statuses = zip(range(len(SERVERS)), SERVERS, map(get_memcached_stats, SERVERS))
context = {
'statuses': statuses,
}
return render_to_response(
'memcached/server_list.html',
context,
context_instance=RequestContext(request)
)
def server_status(request, index):
try:
index = int(index)<|fim▁hole|> except ValueError:
raise Http404
if 'memcached' not in settings.CACHE_BACKEND:
raise Http404
if not SERVERS:
raise Http404
try:
server = SERVERS[index]
except IndexError:
raise Http404
stats = get_memcached_stats(server)
if not stats:
raise Http404
context = {
'server': server,
'stats': stats.items(),
}
return render_to_response(
'memcached/server_status.html',
context,
context_instance=RequestContext(request)
)
if getattr(settings, 'DJANGO_MEMCACHED_REQUIRE_STAFF', False):
server_list = user_passes_test(lambda u: u.is_staff)(server_list)
server_status = user_passes_test(lambda u: u.is_staff)(server_status)<|fim▁end|> | |
<|file_name|>CGGuildApply.cpp<|end_file_name|><|fim▁begin|>#include "stdafx.h"
#include "CGGuildApply.h"
BOOL CGGuildApply::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
iStream.Read( (CHAR*)(m_GuildName), m_GuildNameSize );
}
iStream.Read( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
iStream.Read( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
BOOL CGGuildApply::Write( SocketOutputStream& oStream ) const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
oStream.Write( (CHAR*)(m_GuildName), m_GuildNameSize );
}
oStream.Write( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
oStream.Write( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
UINT CGGuildApply::Execute( Player* pPlayer )
{<|fim▁hole|>__ENTER_FUNCTION
return CGGuildApplyHandler::Execute( this, pPlayer );
__LEAVE_FUNCTION
return FALSE;
}<|fim▁end|> | |
<|file_name|>question-form.component.ts<|end_file_name|><|fim▁begin|>import 'rxjs/add/operator/switchMap';
import { Component, OnInit,ElementRef } from '@angular/core';
import { ActivatedRoute ,Router} from '@angular/router';
import { Location } from '@angular/common';
import { Question } from '../question/question';
import { QuestionService } from '../question/question.service';
import { Item } from '../item/item';
import { ItemService } from '../item/item.service';
import { Response } from '../question/response';
@Component({
moduleId: module.id,
selector: 'question-form',
templateUrl:'question-form.component.html',
styleUrls:['../../assets/css/forms.css']
})
export class QuestionFormComponent implements OnInit {
public question:Question;
public item: Item[];
public index:number;
public answerNumber:number;
constructor(
private itemService: ItemService,
private questionService: QuestionService,
private route:ActivatedRoute,
private router: Router,
private location: Location,
public element: ElementRef
) {
}
getIndex(itemId:string): void {
this.questionService
.getNextIndex(itemId)
.then(index => this.index = index);
}
ngOnInit(): void {
this.question=new Question();
this.route.params.subscribe(params => {
var id = params['item_id'];
this.question.item = id;
this.getIndex(id);
});
}
createRange(number:number):number[]{
var items: number[] = [];
for(var i = 0; i < number; i++){
items.push(i);
}
return items;
}
setNumberOfAnswer(answerNumber:number):void{
this.answerNumber=answerNumber;
console.log( this.answerNumber);
}
newQuestion():void{
this.question.index=this.index;
<|fim▁hole|> this.setAnswer();
for(var i = 0; i < this.answerNumber; i++){
console.log(this.question.answer[i].libelle);
}
this.questionService.newQuestion(this.question);
this.location.replaceState('/'); // clears browser history so they can't navigate with back button
this.router.navigate(['/items']);
}
setAnswer():void{
var el = this.element.nativeElement;
for(var i = 0; i < this.answerNumber; i++){
var answerValue = el.querySelector('#answer'+i).value;
var statusValue = el.querySelector('#status'+i).value;
var response = new Response();
response.status=statusValue;
response.libelle=answerValue;
this.question.answer.push(response);
}
}
}<|fim▁end|> | |
<|file_name|>dom_wrapper.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/. */
//! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes
//! escape, and from generally doing anything that it isn't supposed to. This is accomplished via
//! a simple whitelist of allowed operations, along with some lifetime magic to prevent nodes from
//! escaping.
//!
//! As a security wrapper is only as good as its whitelist, be careful when adding operations to
//! this list. The cardinal rules are:
//!
//! 1. Layout is not allowed to mutate the DOM.
//!
//! 2. Layout is not allowed to see anything with `LayoutDom` in the name, because it could hang
//! onto these objects and cause use-after-free.
//!
//! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you
//! will race and cause spurious thread failure. (Note that I do not believe these races are
//! exploitable, but they'll result in brokenness nonetheless.)
//!
//! Rules of the road for this file:
//!
//! * Do not call any methods on DOM nodes without checking to see whether they use borrow flags.
//!
//! o Instead of `get_attr()`, use `.get_attr_val_for_layout()`.
//!
//! o Instead of `html_element_in_html_document()`, use
//! `html_element_in_html_document_for_layout()`.
#![allow(unsafe_code)]
use atomic_refcell::{AtomicRef, AtomicRefMut, AtomicRefCell};
use gfx_traits::ByteIndex;
use html5ever::{LocalName, Namespace};
use layout::data::StyleAndLayoutData;
use layout::wrapper::GetRawData;
use msg::constellation_msg::{BrowsingContextId, PipelineId};
use range::Range;
use script::layout_exports::{CharacterDataTypeId, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use script::layout_exports::{Document, Element, Node, Text};
use script::layout_exports::{LayoutCharacterDataHelpers, LayoutDocumentHelpers};
use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, LayoutDom, RawLayoutElementHelpers};
use script::layout_exports::NodeFlags;
use script::layout_exports::PendingRestyle;
use script_layout_interface::{HTMLCanvasData, LayoutNodeType, SVGSVGData, TrustedNodeAddress};
use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData};
use script_layout_interface::wrapper_traits::{DangerousThreadSafeLayoutNode, GetLayoutData, LayoutNode};
use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
use selectors::matching::{ElementSelectorFlags, MatchingContext, QuirksMode};
use selectors::matching::VisitedHandlingMode;
use selectors::sink::Push;
use servo_arc::{Arc, ArcBorrow};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::fmt;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::sync::atomic::Ordering;
use style::CaseSensitivityExt;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::attr::AttrValue;
use style::context::SharedStyleContext;
use style::data::ElementData;
use style::dom::{DomChildren, LayoutIterator, NodeInfo, OpaqueNode};
use style::dom::{TDocument, TElement, TNode, TShadowRoot};
use style::element_state::*;
use style::font_metrics::ServoMetricsProvider;
use style::properties::{ComputedValues, PropertyDeclarationBlock};
use style::selector_parser::{AttrValue as SelectorAttrValue, NonTSPseudoClass, PseudoClassStringArg};
use style::selector_parser::{PseudoElement, SelectorImpl, extended_filtering};
use style::shared_lock::{SharedRwLock as StyleSharedRwLock, Locked as StyleLocked};
use style::str::is_whitespace;
use style::stylist::CascadeData;
pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) {
let ptr = data.ptr.as_ptr() as *mut StyleData;
let non_opaque: *mut StyleAndLayoutData = ptr as *mut _;
let _ = Box::from_raw(non_opaque);
}
#[derive(Clone, Copy)]
pub struct ServoLayoutNode<'a> {
/// The wrapped node.
node: LayoutDom<Node>,
/// Being chained to a PhantomData prevents `LayoutNode`s from escaping.
chain: PhantomData<&'a ()>,
}
impl<'ln> Debug for ServoLayoutNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element() {
el.fmt(f)
} else {
if self.is_text_node() {
write!(f, "<text node> ({:#x})", self.opaque().0)
} else {
write!(f, "<non-text node> ({:#x})", self.opaque().0)
}
}
}
}
impl<'a> PartialEq for ServoLayoutNode<'a> {
#[inline]
fn eq(&self, other: &ServoLayoutNode) -> bool {
self.node == other.node
}
}
impl<'ln> ServoLayoutNode<'ln> {
fn from_layout_js(n: LayoutDom<Node>) -> ServoLayoutNode<'ln> {
ServoLayoutNode {
node: n,
chain: PhantomData,
}
}
pub unsafe fn new(address: &TrustedNodeAddress) -> ServoLayoutNode {
ServoLayoutNode::from_layout_js(LayoutDom::from_trusted_node_address(*address))
}
/// Creates a new layout node with the same lifetime as this layout node.
pub unsafe fn new_with_this_lifetime(&self, node: &LayoutDom<Node>) -> ServoLayoutNode<'ln> {
ServoLayoutNode {
node: *node,
chain: self.chain,
}
}
fn script_type_id(&self) -> NodeTypeId {
unsafe {
self.node.type_id_for_layout()
}
}
}
impl<'ln> NodeInfo for ServoLayoutNode<'ln> {
fn is_element(&self) -> bool {
unsafe {
self.node.is_element_for_layout()
}
}
fn is_text_node(&self) -> bool {
self.script_type_id() == NodeTypeId::CharacterData(CharacterDataTypeId::Text)
}
}
#[derive(Clone, Copy, PartialEq)]
enum Impossible { }
#[derive(Clone, Copy, PartialEq)]
pub struct ShadowRoot<'lr>(Impossible, PhantomData<&'lr ()>);
impl<'lr> TShadowRoot for ShadowRoot<'lr> {
type ConcreteNode = ServoLayoutNode<'lr>;
fn as_node(&self) -> Self::ConcreteNode {
match self.0 { }
}
fn host(&self) -> ServoLayoutElement<'lr> {
match self.0 { }
}
fn style_data<'a>(&self) -> &'a CascadeData
where
Self: 'a,
{
match self.0 { }
}
}
impl<'ln> TNode for ServoLayoutNode<'ln> {
type ConcreteDocument = ServoLayoutDocument<'ln>;
type ConcreteElement = ServoLayoutElement<'ln>;
type ConcreteShadowRoot = ShadowRoot<'ln>;
fn parent_node(&self) -> Option<Self> {
unsafe {
self.node.parent_node_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn first_child(&self) -> Option<Self> {
unsafe {
self.node.first_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn last_child(&self) -> Option<Self> {
unsafe {
self.node.last_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn prev_sibling(&self) -> Option<Self> {
unsafe {
self.node.prev_sibling_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn next_sibling(&self) -> Option<Self> {
unsafe {
self.node.next_sibling_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn owner_doc(&self) -> Self::ConcreteDocument {
ServoLayoutDocument::from_layout_js(unsafe { self.node.owner_doc_for_layout() })
}
fn traversal_parent(&self) -> Option<ServoLayoutElement<'ln>> {
self.parent_element()
}
fn opaque(&self) -> OpaqueNode {
unsafe { self.get_jsmanaged().opaque() }
}
fn debug_id(self) -> usize {
self.opaque().0
}
fn as_element(&self) -> Option<ServoLayoutElement<'ln>> {
as_element(self.node)
}
fn as_document(&self) -> Option<ServoLayoutDocument<'ln>> {
self.node.downcast().map(ServoLayoutDocument::from_layout_js)
}
fn as_shadow_root(&self) -> Option<ShadowRoot<'ln>> {
None
}
fn is_in_document(&self) -> bool {
unsafe { self.node.get_flag(NodeFlags::IS_IN_DOC) }
}
}
impl<'ln> LayoutNode for ServoLayoutNode<'ln> {
type ConcreteThreadSafeLayoutNode = ServoThreadSafeLayoutNode<'ln>;
fn to_threadsafe(&self) -> Self::ConcreteThreadSafeLayoutNode {
ServoThreadSafeLayoutNode::new(self)
}
fn type_id(&self) -> LayoutNodeType {
self.script_type_id().into()
}
unsafe fn initialize_data(&self) {
if self.get_raw_data().is_none() {
let ptr: *mut StyleAndLayoutData =
Box::into_raw(Box::new(StyleAndLayoutData::new()));
let opaque = OpaqueStyleAndLayoutData {
ptr: NonNull::new_unchecked(ptr as *mut StyleData),
};
self.init_style_and_layout_data(opaque);
};
}
unsafe fn init_style_and_layout_data(&self, data: OpaqueStyleAndLayoutData) {
self.get_jsmanaged().init_style_and_layout_data(data);
}
unsafe fn take_style_and_layout_data(&self) -> OpaqueStyleAndLayoutData {
self.get_jsmanaged().take_style_and_layout_data()
}
}
impl<'ln> GetLayoutData for ServoLayoutNode<'ln> {
fn get_style_and_layout_data(&self) -> Option<OpaqueStyleAndLayoutData> {
unsafe {
self.get_jsmanaged().get_style_and_layout_data()
}
}
}
impl<'le> GetLayoutData for ServoLayoutElement<'le> {
fn get_style_and_layout_data(&self) -> Option<OpaqueStyleAndLayoutData> {
self.as_node().get_style_and_layout_data()
}
}
impl<'ln> GetLayoutData for ServoThreadSafeLayoutNode<'ln> {
fn get_style_and_layout_data(&self) -> Option<OpaqueStyleAndLayoutData> {
self.node.get_style_and_layout_data()
}
}
impl<'le> GetLayoutData for ServoThreadSafeLayoutElement<'le> {
fn get_style_and_layout_data(&self) -> Option<OpaqueStyleAndLayoutData> {
self.element.as_node().get_style_and_layout_data()
}
}
impl<'ln> ServoLayoutNode<'ln> {
/// Returns the interior of this node as a `LayoutDom`. This is highly unsafe for layout to
/// call and as such is marked `unsafe`.
pub unsafe fn get_jsmanaged(&self) -> &LayoutDom<Node> {
&self.node
}
}
// A wrapper around documents that ensures ayout can only ever access safe properties.
#[derive(Clone, Copy)]
pub struct ServoLayoutDocument<'ld> {
document: LayoutDom<Document>,
chain: PhantomData<&'ld ()>,
}
impl<'ld> TDocument for ServoLayoutDocument<'ld> {
type ConcreteNode = ServoLayoutNode<'ld>;
fn as_node(&self) -> Self::ConcreteNode {
ServoLayoutNode::from_layout_js(self.document.upcast())
}
fn quirks_mode(&self) -> QuirksMode {
unsafe { self.document.quirks_mode() }
}
fn is_html_document(&self) -> bool {
unsafe { self.document.is_html_document_for_layout() }
}
}
impl<'ld> ServoLayoutDocument<'ld> {
pub fn root_element(&self) -> Option<ServoLayoutElement<'ld>> {
self.as_node().dom_children().flat_map(|n| n.as_element()).next()
}
pub fn drain_pending_restyles(&self) -> Vec<(ServoLayoutElement<'ld>, PendingRestyle)> {
let elements = unsafe { self.document.drain_pending_restyles() };
elements.into_iter().map(|(el, snapshot)| (ServoLayoutElement::from_layout_js(el), snapshot)).collect()
}
pub fn needs_paint_from_layout(&self) {
unsafe { self.document.needs_paint_from_layout(); }
}
pub fn will_paint(&self) {
unsafe { self.document.will_paint(); }
}
pub fn style_shared_lock(&self) -> &StyleSharedRwLock {
unsafe { self.document.style_shared_lock() }
}
pub fn from_layout_js(doc: LayoutDom<Document>) -> ServoLayoutDocument<'ld> {
ServoLayoutDocument {
document: doc,
chain: PhantomData,
}
}
}
/// A wrapper around elements that ensures layout can only ever access safe properties.
#[derive(Clone, Copy)]
pub struct ServoLayoutElement<'le> {
element: LayoutDom<Element>,
chain: PhantomData<&'le ()>,
}
impl<'le> fmt::Debug for ServoLayoutElement<'le> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{}", self.element.local_name())?;
if let Some(id) = self.id() {
write!(f, " id={}", id)?;
}
write!(f, "> ({:#x})", self.as_node().opaque().0)
}
}
impl<'le> TElement for ServoLayoutElement<'le> {
type ConcreteNode = ServoLayoutNode<'le>;
type TraversalChildrenIterator = DomChildren<Self::ConcreteNode>;
type FontMetricsProvider = ServoMetricsProvider;
fn as_node(&self) -> ServoLayoutNode<'le> {
ServoLayoutNode::from_layout_js(self.element.upcast())
}
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator> {
LayoutIterator(self.as_node().dom_children())
}
fn is_html_element(&self) -> bool {
unsafe { self.element.is_html_element() }
}
fn style_attribute(&self) -> Option<ArcBorrow<StyleLocked<PropertyDeclarationBlock>>> {
unsafe {
(*self.element.style_attribute()).as_ref().map(|x| x.borrow_arc())
}
}
fn state(&self) -> ElementState {
self.element.get_state_for_layout()
}
#[inline]
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool {
self.get_attr(namespace, attr).is_some()
}
#[inline]
fn id(&self) -> Option<&Atom> {
unsafe {
(*self.element.id_attribute()).as_ref()
}
}
#[inline(always)]
fn each_class<F>(&self, mut callback: F) where F: FnMut(&Atom) {
unsafe {
if let Some(ref classes) = self.element.get_classes_for_layout() {
for class in *classes {
callback(class)
}
}
}
}
fn has_dirty_descendants(&self) -> bool {
unsafe { self.as_node().node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) }
}
fn has_snapshot(&self) -> bool {
unsafe { self.as_node().node.get_flag(NodeFlags::HAS_SNAPSHOT) }
}
fn handled_snapshot(&self) -> bool {
unsafe { self.as_node().node.get_flag(NodeFlags::HANDLED_SNAPSHOT) }
}
unsafe fn set_handled_snapshot(&self) {
self.as_node().node.set_flag(NodeFlags::HANDLED_SNAPSHOT, true);
}
unsafe fn set_dirty_descendants(&self) {
debug_assert!(self.as_node().is_in_document());
self.as_node().node.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true)
}
unsafe fn unset_dirty_descendants(&self) {
self.as_node().node.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, false)
}
fn store_children_to_process(&self, n: isize) {
let data = self.get_style_data().unwrap();
data.parallel.children_to_process.store(n, Ordering::Relaxed);
}
fn did_process_child(&self) -> isize {
let data = self.get_style_data().unwrap();
let old_value = data.parallel.children_to_process.fetch_sub(1, Ordering::Relaxed);
debug_assert!(old_value >= 1);
old_value - 1
}
unsafe fn clear_data(&self) {
if self.get_raw_data().is_some() {
drop_style_and_layout_data(self.as_node().take_style_and_layout_data());
}
}
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData> {
self.as_node().initialize_data();
self.mutate_data().unwrap()
}
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>> {
unsafe {
self.get_style_and_layout_data().map(|d| {
&(*(d.ptr.as_ptr() as *mut StyleData)).element_data
})
}
}
fn skip_item_display_fixup(&self) -> bool {
false
}
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags) {
self.element.insert_selector_flags(flags);
}
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool {
self.element.has_selector_flags(flags)
}
fn has_animations(&self) -> bool {
// We use this function not only for Gecko but also for Servo to know if this element has
// animations, so we maybe try to get the important rules of this element. This is used for
// off-main thread animations, but we don't support it on Servo, so return false directly.
false
}
fn has_css_animations(&self) -> bool {
unreachable!("this should be only called on gecko");
}
fn has_css_transitions(&self) -> bool {
unreachable!("this should be only called on gecko");
}
#[inline]
fn lang_attr(&self) -> Option<SelectorAttrValue> {
self.get_attr(&ns!(xml), &local_name!("lang"))
.or_else(|| self.get_attr(&ns!(), &local_name!("lang")))
.map(|v| String::from(v as &str))
}
fn match_element_lang(
&self,
override_lang: Option<Option<SelectorAttrValue>>,
value: &PseudoClassStringArg,
) -> bool {
// Servo supports :lang() from CSS Selectors 4, which can take a comma-
// separated list of language tags in the pseudo-class, and which
// performs RFC 4647 extended filtering matching on them.
//
// FIXME(heycam): This is wrong, since extended_filtering accepts
// a string containing commas (separating each language tag in
// a list) but the pseudo-class instead should be parsing and
// storing separate <ident> or <string>s for each language tag.
//
// FIXME(heycam): Look at `element`'s document's Content-Language
// HTTP header for language tags to match `value` against. To
// do this, we should make `get_lang_for_layout` return an Option,
// so we can decide when to fall back to the Content-Language check.
let element_lang = match override_lang {
Some(Some(lang)) => lang,
Some(None) => String::new(),
None => self.element.get_lang_for_layout(),
};
extended_filtering(&element_lang, &*value)
}
fn is_html_document_body_element(&self) -> bool {
// This is only used for the "tables inherit from body" quirk, which we
// don't implement.
//
// FIXME(emilio): We should be able to give the right answer though!
false
}
fn synthesize_presentational_hints_for_legacy_attributes<V>(
&self,
_visited_handling: VisitedHandlingMode,
hints: &mut V,
)
where
V: Push<ApplicableDeclarationBlock>,
{
unsafe {
self.element.synthesize_presentational_hints_for_legacy_attributes(hints);
}
}
fn shadow_root(&self) -> Option<ShadowRoot<'le>> {
None
}
fn containing_shadow(&self) -> Option<ShadowRoot<'le>> {
None
}
}
impl<'le> PartialEq for ServoLayoutElement<'le> {
fn eq(&self, other: &Self) -> bool {
self.as_node() == other.as_node()
}
}
impl<'le> Hash for ServoLayoutElement<'le> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.element.hash(state);
}
}
impl<'le> Eq for ServoLayoutElement<'le> {}
impl<'le> ServoLayoutElement<'le> {
fn from_layout_js(el: LayoutDom<Element>) -> ServoLayoutElement<'le> {
ServoLayoutElement {
element: el,
chain: PhantomData,
}
}
#[inline]
fn get_attr_enum(&self, namespace: &Namespace, name: &LocalName) -> Option<&AttrValue> {
unsafe {
(*self.element.unsafe_get()).get_attr_for_layout(namespace, name)
}
}
#[inline]
fn get_attr(&self, namespace: &Namespace, name: &LocalName) -> Option<&str> {
unsafe {
(*self.element.unsafe_get()).get_attr_val_for_layout(namespace, name)
}
}
fn get_style_data(&self) -> Option<&StyleData> {
unsafe {
self.get_style_and_layout_data().map(|d| &*(d.ptr.as_ptr() as *mut StyleData))
}
}
pub unsafe fn unset_snapshot_flags(&self) {
self.as_node().node.set_flag(NodeFlags::HAS_SNAPSHOT | NodeFlags::HANDLED_SNAPSHOT, false);
}
pub unsafe fn set_has_snapshot(&self) {
self.as_node().node.set_flag(NodeFlags::HAS_SNAPSHOT, true);
}
pub unsafe fn note_dirty_descendant(&self) {
use ::selectors::Element;
let mut current = Some(*self);
while let Some(el) = current {
// FIXME(bholley): Ideally we'd have the invariant that any element
// with has_dirty_descendants also has the bit set on all its
// ancestors. However, there are currently some corner-cases where
// we get that wrong. I have in-flight patches to fix all this
// stuff up, so we just always propagate this bit for now.
el.set_dirty_descendants();
current = el.parent_element();
}
}
}
fn as_element<'le>(node: LayoutDom<Node>) -> Option<ServoLayoutElement<'le>> {
node.downcast().map(ServoLayoutElement::from_layout_js)
}
impl<'le> ::selectors::Element for ServoLayoutElement<'le> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(self.as_node().opaque().0 as *const ())
}
fn parent_element(&self) -> Option<ServoLayoutElement<'le>> {
unsafe {
self.element.upcast().parent_node_ref().and_then(as_element)
}
}
fn parent_node_is_shadow_root(&self) -> bool {
false
}
fn containing_shadow_host(&self) -> Option<Self> {
None
}
fn first_child_element(&self) -> Option<ServoLayoutElement<'le>> {
self.as_node().dom_children().filter_map(|n| n.as_element()).next()
}
fn last_child_element(&self) -> Option<ServoLayoutElement<'le>> {<|fim▁hole|> self.as_node().rev_children().filter_map(|n| n.as_element()).next()
}
fn prev_sibling_element(&self) -> Option<ServoLayoutElement<'le>> {
let mut node = self.as_node();
while let Some(sibling) = node.prev_sibling() {
if let Some(element) = sibling.as_element() {
return Some(element)
}
node = sibling;
}
None
}
fn next_sibling_element(&self) -> Option<ServoLayoutElement<'le>> {
let mut node = self.as_node();
while let Some(sibling) = node.next_sibling() {
if let Some(element) = sibling.as_element() {
return Some(element)
}
node = sibling;
}
None
}
fn attr_matches(&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&String>)
-> bool {
match *ns {
NamespaceConstraint::Specific(ref ns) => {
self.get_attr_enum(ns, local_name)
.map_or(false, |value| value.eval_selector(operation))
}
NamespaceConstraint::Any => {
let values = unsafe {
(*self.element.unsafe_get()).get_attr_vals_for_layout(local_name)
};
values.iter().any(|value| value.eval_selector(operation))
}
}
}
fn is_root(&self) -> bool {
match self.as_node().parent_node() {
None => false,
Some(node) => {
match node.script_type_id() {
NodeTypeId::Document(_) => true,
_ => false
}
},
}
}
fn is_empty(&self) -> bool {
self.as_node().dom_children().all(|node| match node.script_type_id() {
NodeTypeId::Element(..) => false,
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => unsafe {
node.node.downcast().unwrap().data_for_layout().is_empty()
},
_ => true
})
}
#[inline]
fn local_name(&self) -> &LocalName {
self.element.local_name()
}
#[inline]
fn namespace(&self) -> &Namespace {
self.element.namespace()
}
fn match_pseudo_element(
&self,
_pseudo: &PseudoElement,
_context: &mut MatchingContext<Self::Impl>,
) -> bool {
false
}
fn match_non_ts_pseudo_class<F>(
&self,
pseudo_class: &NonTSPseudoClass,
_: &mut MatchingContext<Self::Impl>,
_: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
match *pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::Link |
NonTSPseudoClass::AnyLink => self.is_link(),
NonTSPseudoClass::Visited => false,
NonTSPseudoClass::Lang(ref lang) => self.match_element_lang(None, &*lang),
NonTSPseudoClass::ServoNonZeroBorder => unsafe {
match (*self.element.unsafe_get()).get_attr_for_layout(&ns!(), &local_name!("border")) {
None | Some(&AttrValue::UInt(_, 0)) => false,
_ => true,
}
},
NonTSPseudoClass::ServoCaseSensitiveTypeAttr(ref expected_value) => {
self.get_attr_enum(&ns!(), &local_name!("type"))
.map_or(false, |attr| attr == expected_value)
}
NonTSPseudoClass::ReadOnly =>
!self.element.get_state_for_layout().contains(pseudo_class.state_flag()),
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::Indeterminate |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::PlaceholderShown |
NonTSPseudoClass::Target =>
self.element.get_state_for_layout().contains(pseudo_class.state_flag())
}
}
#[inline]
fn is_link(&self) -> bool {
unsafe {
match self.as_node().script_type_id() {
// https://html.spec.whatwg.org/multipage/#selector-link
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) =>
(*self.element.unsafe_get()).get_attr_val_for_layout(&ns!(), &local_name!("href")).is_some(),
_ => false,
}
}
}
#[inline]
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
unsafe {
(*self.element.id_attribute())
.as_ref()
.map_or(false, |atom| case_sensitivity.eq_atom(atom, id))
}
}
#[inline]
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
unsafe {
self.element.has_class_for_layout(name, case_sensitivity)
}
}
fn is_html_slot_element(&self) -> bool {
unsafe {
self.element.is_html_element() &&
self.local_name() == &local_name!("slot")
}
}
fn is_html_element_in_html_document(&self) -> bool {
unsafe {
if !self.element.is_html_element() {
return false;
}
}
self.as_node().owner_doc().is_html_document()
}
}
#[derive(Clone, Copy, Debug)]
pub struct ServoThreadSafeLayoutNode<'ln> {
/// The wrapped node.
node: ServoLayoutNode<'ln>,
/// The pseudo-element type, with (optionally)
/// a specified display value to override the stylesheet.
pseudo: PseudoElementType,
}
impl<'a> PartialEq for ServoThreadSafeLayoutNode<'a> {
#[inline]
fn eq(&self, other: &ServoThreadSafeLayoutNode<'a>) -> bool {
self.node == other.node
}
}
impl<'ln> DangerousThreadSafeLayoutNode for ServoThreadSafeLayoutNode<'ln> {
unsafe fn dangerous_first_child(&self) -> Option<Self> {
self.get_jsmanaged().first_child_ref()
.map(|node| self.new_with_this_lifetime(&node))
}
unsafe fn dangerous_next_sibling(&self) -> Option<Self> {
self.get_jsmanaged().next_sibling_ref()
.map(|node| self.new_with_this_lifetime(&node))
}
}
impl<'ln> ServoThreadSafeLayoutNode<'ln> {
/// Creates a new layout node with the same lifetime as this layout node.
pub unsafe fn new_with_this_lifetime(&self, node: &LayoutDom<Node>) -> ServoThreadSafeLayoutNode<'ln> {
ServoThreadSafeLayoutNode {
node: self.node.new_with_this_lifetime(node),
pseudo: PseudoElementType::Normal,
}
}
/// Creates a new `ServoThreadSafeLayoutNode` from the given `ServoLayoutNode`.
pub fn new<'a>(node: &ServoLayoutNode<'a>) -> ServoThreadSafeLayoutNode<'a> {
ServoThreadSafeLayoutNode {
node: node.clone(),
pseudo: PseudoElementType::Normal,
}
}
/// Returns the interior of this node as a `LayoutDom`. This is highly unsafe for layout to
/// call and as such is marked `unsafe`.
unsafe fn get_jsmanaged(&self) -> &LayoutDom<Node> {
self.node.get_jsmanaged()
}
}
impl<'ln> NodeInfo for ServoThreadSafeLayoutNode<'ln> {
fn is_element(&self) -> bool {
self.node.is_element()
}
fn is_text_node(&self) -> bool {
self.node.is_text_node()
}
}
impl<'ln> ThreadSafeLayoutNode for ServoThreadSafeLayoutNode<'ln> {
type ConcreteNode = ServoLayoutNode<'ln>;
type ConcreteThreadSafeLayoutElement = ServoThreadSafeLayoutElement<'ln>;
type ConcreteElement = ServoLayoutElement<'ln>;
type ChildrenIterator = ThreadSafeLayoutNodeChildrenIterator<Self>;
fn opaque(&self) -> OpaqueNode {
unsafe { self.get_jsmanaged().opaque() }
}
fn type_id(&self) -> Option<LayoutNodeType> {
if self.pseudo == PseudoElementType::Normal {
Some(self.node.type_id())
} else {
None
}
}
fn parent_style(&self) -> Arc<ComputedValues> {
let parent = self.node.parent_node().unwrap().as_element().unwrap();
let parent_data = parent.get_data().unwrap().borrow();
parent_data.styles.primary().clone()
}
fn debug_id(self) -> usize {
self.node.debug_id()
}
fn children(&self) -> LayoutIterator<Self::ChildrenIterator> {
LayoutIterator(ThreadSafeLayoutNodeChildrenIterator::new(*self))
}
fn as_element(&self) -> Option<ServoThreadSafeLayoutElement<'ln>> {
self.node.as_element().map(|el| ServoThreadSafeLayoutElement {
element: el,
pseudo: self.pseudo,
})
}
fn get_style_and_layout_data(&self) -> Option<OpaqueStyleAndLayoutData> {
self.node.get_style_and_layout_data()
}
fn is_ignorable_whitespace(&self, context: &SharedStyleContext) -> bool {
unsafe {
let text: LayoutDom<Text> = match self.get_jsmanaged().downcast() {
Some(text) => text,
None => return false
};
if !is_whitespace(text.upcast().data_for_layout()) {
return false
}
// NB: See the rules for `white-space` here:
//
// http://www.w3.org/TR/CSS21/text.html#propdef-white-space
//
// If you implement other values for this property, you will almost certainly
// want to update this check.
!self.style(context).get_inheritedtext().white_space.preserve_newlines()
}
}
unsafe fn unsafe_get(self) -> Self::ConcreteNode {
self.node
}
fn node_text_content(&self) -> String {
let this = unsafe { self.get_jsmanaged() };
return this.text_content();
}
fn selection(&self) -> Option<Range<ByteIndex>> {
let this = unsafe { self.get_jsmanaged() };
this.selection().map(|range| {
Range::new(ByteIndex(range.start as isize),
ByteIndex(range.len() as isize))
})
}
fn image_url(&self) -> Option<ServoUrl> {
let this = unsafe { self.get_jsmanaged() };
this.image_url()
}
fn canvas_data(&self) -> Option<HTMLCanvasData> {
let this = unsafe { self.get_jsmanaged() };
this.canvas_data()
}
fn svg_data(&self) -> Option<SVGSVGData> {
let this = unsafe { self.get_jsmanaged() };
this.svg_data()
}
// Can return None if the iframe has no nested browsing context
fn iframe_browsing_context_id(&self) -> Option<BrowsingContextId> {
let this = unsafe { self.get_jsmanaged() };
this.iframe_browsing_context_id()
}
// Can return None if the iframe has no nested browsing context
fn iframe_pipeline_id(&self) -> Option<PipelineId> {
let this = unsafe { self.get_jsmanaged() };
this.iframe_pipeline_id()
}
fn get_colspan(&self) -> u32 {
unsafe {
self.get_jsmanaged().downcast::<Element>().unwrap().get_colspan()
}
}
fn get_rowspan(&self) -> u32 {
unsafe {
self.get_jsmanaged().downcast::<Element>().unwrap().get_rowspan()
}
}
}
pub struct ThreadSafeLayoutNodeChildrenIterator<ConcreteNode: ThreadSafeLayoutNode> {
current_node: Option<ConcreteNode>,
parent_node: ConcreteNode,
}
impl<ConcreteNode> ThreadSafeLayoutNodeChildrenIterator<ConcreteNode>
where ConcreteNode: DangerousThreadSafeLayoutNode {
pub fn new(parent: ConcreteNode) -> Self {
let first_child: Option<ConcreteNode> = match parent.get_pseudo_element_type() {
PseudoElementType::Normal => {
parent.get_before_pseudo().or_else(|| parent.get_details_summary_pseudo()).or_else(|| {
unsafe { parent.dangerous_first_child() }
})
},
PseudoElementType::DetailsContent | PseudoElementType::DetailsSummary => {
unsafe { parent.dangerous_first_child() }
},
_ => None,
};
ThreadSafeLayoutNodeChildrenIterator {
current_node: first_child,
parent_node: parent,
}
}
}
impl<ConcreteNode> Iterator for ThreadSafeLayoutNodeChildrenIterator<ConcreteNode>
where ConcreteNode: DangerousThreadSafeLayoutNode {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
use ::selectors::Element;
match self.parent_node.get_pseudo_element_type() {
PseudoElementType::Before | PseudoElementType::After => None,
PseudoElementType::DetailsSummary => {
let mut current_node = self.current_node.clone();
loop {
let next_node = if let Some(ref node) = current_node {
if let Some(element) = node.as_element() {
if element.local_name() == &local_name!("summary") &&
element.namespace() == &ns!(html) {
self.current_node = None;
return Some(node.clone());
}
}
unsafe { node.dangerous_next_sibling() }
} else {
self.current_node = None;
return None
};
current_node = next_node;
}
}
PseudoElementType::DetailsContent => {
let node = self.current_node.clone();
let node = node.and_then(|node| {
if node.is_element() &&
node.as_element().unwrap().local_name() == &local_name!("summary") &&
node.as_element().unwrap().namespace() == &ns!(html) {
unsafe { node.dangerous_next_sibling() }
} else {
Some(node)
}
});
self.current_node = node.and_then(|node| unsafe { node.dangerous_next_sibling() });
node
}
PseudoElementType::Normal => {
let node = self.current_node.clone();
if let Some(ref node) = node {
self.current_node = match node.get_pseudo_element_type() {
PseudoElementType::Before => {
self.parent_node.get_details_summary_pseudo()
.or_else(|| unsafe { self.parent_node.dangerous_first_child() })
.or_else(|| self.parent_node.get_after_pseudo())
},
PseudoElementType::Normal => {
unsafe { node.dangerous_next_sibling() }.or_else(|| self.parent_node.get_after_pseudo())
},
PseudoElementType::DetailsSummary => self.parent_node.get_details_content_pseudo(),
PseudoElementType::DetailsContent => self.parent_node.get_after_pseudo(),
PseudoElementType::After => None,
};
}
node
}
}
}
}
/// A wrapper around elements that ensures layout can only
/// ever access safe properties and cannot race on elements.
#[derive(Clone, Copy, Debug)]
pub struct ServoThreadSafeLayoutElement<'le> {
element: ServoLayoutElement<'le>,
/// The pseudo-element type, with (optionally)
/// a specified display value to override the stylesheet.
pseudo: PseudoElementType,
}
impl<'le> ThreadSafeLayoutElement for ServoThreadSafeLayoutElement<'le> {
type ConcreteThreadSafeLayoutNode = ServoThreadSafeLayoutNode<'le>;
type ConcreteElement = ServoLayoutElement<'le>;
fn as_node(&self) -> ServoThreadSafeLayoutNode<'le> {
ServoThreadSafeLayoutNode {
node: self.element.as_node(),
pseudo: self.pseudo.clone(),
}
}
fn get_pseudo_element_type(&self) -> PseudoElementType {
self.pseudo
}
fn with_pseudo(&self, pseudo: PseudoElementType) -> Self {
ServoThreadSafeLayoutElement {
element: self.element.clone(),
pseudo,
}
}
fn type_id(&self) -> Option<LayoutNodeType> {
self.as_node().type_id()
}
unsafe fn unsafe_get(self) -> ServoLayoutElement<'le> {
self.element
}
fn get_attr_enum(&self, namespace: &Namespace, name: &LocalName) -> Option<&AttrValue> {
self.element.get_attr_enum(namespace, name)
}
fn get_attr<'a>(&'a self, namespace: &Namespace, name: &LocalName) -> Option<&'a str> {
self.element.get_attr(namespace, name)
}
fn style_data(&self) -> AtomicRef<ElementData> {
self.element.get_data()
.expect("Unstyled layout node?")
.borrow()
}
}
/// This implementation of `::selectors::Element` is used for implementing lazy
/// pseudo-elements.
///
/// Lazy pseudo-elements in Servo only allows selectors using safe properties,
/// i.e., local_name, attributes, so they can only be used for **private**
/// pseudo-elements (like `::-servo-details-content`).
///
/// Probably a few more of this functions can be implemented (like `has_class`, etc.),
/// but they have no use right now.
///
/// Note that the element implementation is needed only for selector matching,
/// not for inheritance (styles are inherited appropiately).
impl<'le> ::selectors::Element for ServoThreadSafeLayoutElement<'le> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(self.as_node().opaque().0 as *const ())
}
fn parent_element(&self) -> Option<Self> {
warn!("ServoThreadSafeLayoutElement::parent_element called");
None
}
fn parent_node_is_shadow_root(&self) -> bool {
false
}
fn containing_shadow_host(&self) -> Option<Self> {
None
}
fn first_child_element(&self) -> Option<Self> {
warn!("ServoThreadSafeLayoutElement::first_child_element called");
None
}
// Skips non-element nodes
fn last_child_element(&self) -> Option<Self> {
warn!("ServoThreadSafeLayoutElement::last_child_element called");
None
}
// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self> {
warn!("ServoThreadSafeLayoutElement::prev_sibling_element called");
None
}
// Skips non-element nodes
fn next_sibling_element(&self) -> Option<Self> {
warn!("ServoThreadSafeLayoutElement::next_sibling_element called");
None
}
fn is_html_slot_element(&self) -> bool {
self.element.is_html_slot_element()
}
fn is_html_element_in_html_document(&self) -> bool {
debug!("ServoThreadSafeLayoutElement::is_html_element_in_html_document called");
true
}
#[inline]
fn local_name(&self) -> &LocalName {
self.element.local_name()
}
#[inline]
fn namespace(&self) -> &Namespace {
self.element.namespace()
}
fn match_pseudo_element(
&self,
_pseudo: &PseudoElement,
_context: &mut MatchingContext<Self::Impl>
) -> bool {
false
}
fn attr_matches(&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&String>)
-> bool {
match *ns {
NamespaceConstraint::Specific(ref ns) => {
self.get_attr_enum(ns, local_name)
.map_or(false, |value| value.eval_selector(operation))
}
NamespaceConstraint::Any => {
let values = unsafe {
(*self.element.element.unsafe_get()).get_attr_vals_for_layout(local_name)
};
values.iter().any(|v| v.eval_selector(operation))
}
}
}
fn match_non_ts_pseudo_class<F>(
&self,
_: &NonTSPseudoClass,
_: &mut MatchingContext<Self::Impl>,
_: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
// NB: This could maybe be implemented
warn!("ServoThreadSafeLayoutElement::match_non_ts_pseudo_class called");
false
}
fn is_link(&self) -> bool {
warn!("ServoThreadSafeLayoutElement::is_link called");
false
}
fn has_id(&self, _id: &Atom, _case_sensitivity: CaseSensitivity) -> bool {
debug!("ServoThreadSafeLayoutElement::has_id called");
false
}
fn has_class(&self, _name: &Atom, _case_sensitivity: CaseSensitivity) -> bool {
debug!("ServoThreadSafeLayoutElement::has_class called");
false
}
fn is_empty(&self) -> bool {
warn!("ServoThreadSafeLayoutElement::is_empty called");
false
}
fn is_root(&self) -> bool {
warn!("ServoThreadSafeLayoutElement::is_root called");
false
}
}<|fim▁end|> | |
<|file_name|>AbstractDao.java<|end_file_name|><|fim▁begin|>package it.ads.activitiesmanager.model.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
//Segnala che si tratta di una classe DAO (o Repository)
@Repository
//Significa che tutti i metodi della classe sono definiti come @Transactional
@Transactional
public abstract class AbstractDao<T extends Serializable> {
private Class<T> c;
@PersistenceContext
EntityManager em;
public final void setClass(Class<T> c){
this.c = c;
}
public T find(Integer id) {<|fim▁hole|> String SELECT = "SELECT * FROM " + c.getName();
Query query = em.createQuery(SELECT);
return query.getResultList();
}
public void save(T entity){
em.persist(entity);
}
public void update(T entity){
em.merge(entity);
}
public void delete(T entity){
em.remove(entity);
}
public void deleteById(Integer id){
T entity = find(id);
delete(entity);
}
}<|fim▁end|> | return em.find(c,id);
}
public List<T> findAll(){ |
<|file_name|>PrintMediumSuccess.java<|end_file_name|><|fim▁begin|>package testclasses;<|fim▁hole|>import util.printer.SecurePrinter;
public class PrintMediumSuccess {
public static void main(String[] args) {
String med = "This is medium information";
med = DynamicLabel.makeMedium(med);
SecurePrinter.printMedium(med);
String low = "This is low information";
low = DynamicLabel.makeLow(low);
SecurePrinter.printMedium(low);
}
}<|fim▁end|> |
import de.unifreiburg.cs.proglang.jgs.support.DynamicLabel; |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! A simple dsp node for multiplying the amplitude of its inputs by some given multiplier.
extern crate dsp;
extern crate time_calc as time;
/// A simple dsp node for multiplying the amplitude of its inputs by the held multiplier.
#[derive(Copy, Clone, Debug)]
pub struct Volume {
maybe_prev: Option<f32>,
pub current: f32,
pub interpolation_ms: time::calc::Ms,
}
impl Volume {
/// Constructor for a new default volume. The default volume is 1.0, having no impact on the
/// input signal. The default interpolation_ms is 10ms to avoid clipping.
pub fn new() -> Volume {
Volume {
maybe_prev: None,
current: 1.0,
interpolation_ms: 10.0,
}
}
/// Builder for constructing a Volume with some given volume.
pub fn volume(mut self, volume: f32) -> Volume {
self.current = volume;
self
}
/// Builder for constructing a Volume with some given interpolation length in Ms.
/// The interpolation length is how long it takes the volume to progress from some previous
/// volume to a new current volume. It is mainly used to avoid clipping.
///
/// The default interpolation_ms is 10ms - just enough to avoid clipping.
pub fn interpolation_ms(mut self, ms: time::calc::Ms) -> Volume {
self.interpolation_ms = ms;
self
}
/// Set the new current volume.
pub fn set(&mut self, volume: f32) {
self.current = volume;
}
}
impl<F> dsp::Node<F> for Volume
where F: dsp::Frame,
{
#[inline]
fn audio_requested(&mut self, buffer: &mut [F], sample_hz: f64) {
use dsp::{Frame, Sample};
match self.maybe_prev {
<|fim▁hole|> // If the volume used for the previous buffer is different to the volume used for the
// current buffer, we should interpolate from it to the current volume to avoid
// clipping.
Some(prev) if prev != self.current && self.interpolation_ms > 0.0 => {
// Calculate the interpolation duration in frames along with the volume increment
// to use for interpolation.
let interpolation_frames = std::cmp::min(
buffer.len(),
time::Ms(self.interpolation_ms).samples(sample_hz) as usize,
);
let volume_diff = self.current - prev;
let volume_increment = volume_diff * (1.0 / interpolation_frames as f32);
let mut volume = prev;
// Interpolated frames.
for idx in 0..interpolation_frames {
volume += volume_increment;
let frame = &mut buffer[idx];
*frame = frame.scale_amp(volume.to_sample());
}
// Remaining frames.
for idx in interpolation_frames..buffer.len() {
let frame = &mut buffer[idx];
*frame = frame.scale_amp(volume.to_sample());
}
},
// Otherwise, simply multiply every sample by the current volume.
_ => for frame in buffer.iter_mut() {
*frame = frame.scale_amp(self.current.to_sample());
},
}
// Always set the current volume as the new `maybe_prev`.
self.maybe_prev = Some(self.current);
}
}<|fim▁end|> | |
<|file_name|>const_curve25519.rs<|end_file_name|><|fim▁begin|>pub(crate) const D: [i32; 10] = [
-10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448,
-12055116,
];
pub(crate) const D2: [i32; 10] = [
-21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968,
9444199,
];
pub(crate) const SQRTM1: [i32; 10] = [
-32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686,
11406482,
];
pub(crate) const BI: [[[i32; 10]; 3]; 8] = [
[
[
25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271,
-6079156, 2047605,
],
[
-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929,
-15469378,
],
[
-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899,
-24514362, -4438546,
],
],
[
[
15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189,
28944400, -1550024,
],
[
16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962,
7689662, 11199574,
],
[
30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326,
-17749093, -9920357,
],
],
[
[
10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107,
-15438304, 10819380,
],
[
4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688,
-12668491, 5581306,
],
[
19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243,
-23678021, -15815942,
],
],
[
[
5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439,
-15175766,
],
[
-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125,
30598449, 7715701,
],
[
28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553,
-1409300,
],
],
[
[
-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450,
-13062696, 13821877,
],
[
-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327,
18853322, -14220951,
],
[
4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137,
2207753, -3209784,
],
],
[
[
-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000,
-31111463, -16132436,
],
[
25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356,
6466918,
],
[
23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058,
-30714912, 16193877,
],
],
[
[
-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455,
-18074513, 9256800,
],
[
-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698,
-19827198, 630305,
],
[
-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994,
-2449256, -14291300,
],
],
[
[
-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784,
25105118, -7894876,
],
[
-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887,
2198790, -15804619,
],
[
-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442,
-32461234, -12290683,
],
],
];
pub(crate) const BASE: [[[[i32; 10]; 3]; 8]; 32] = [
[
[
[
25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271,
-6079156, 2047605,
],
[
-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384,
19500929, -15469378,
],
[
-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899,
-24514362, -4438546,
],
],
[
[
-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903,
-3814571, -358445, -10211303,
],
[
-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268,
-26829678, -5319081,
],
[
26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118,
-15472047, -4166697,
],
],
[
[
15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189,
28944400, -1550024,
],
[
16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962,
7689662, 11199574,
],
[
30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326,
-17749093, -9920357,
],
],
[
[
-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023,
3284568, -6276540,
],
[
23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445,
13059162, 10374397,
],
[
7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045,
-641708, -101325,
],
],
[
[
10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107,
-15438304, 10819380,
],
[
4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688,
-12668491, 5581306,
],
[
19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243,
-23678021, -15815942,
],
],
[
[
-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819,
-9818940, -12085777,
],
[
-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887,
1762328, 14866737,
],
[
-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421,
27914454, 4383652,
],
],
[
[
5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134,
-23952439, -15175766,
],
[
-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125,
30598449, 7715701,
],
[
28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708,
29794553, -1409300,
],
],
[
[
14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454,
-33154098, 2381726,
],
[
-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005,
-32300832, 15351955,
],
[
27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515,
29551813, 10109425,
],
],
],
[
[
[
-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556,
10092783, -4764171,
],
[
27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538,
-17810127, 12803510,
],
[
17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194,
18016357, 4397660,
],
],
[
[
-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525,
-17477504, 982639,
],
[
29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128,
-21047696, 9934963,
],
[
5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895,
-30123922, -10897950,
],
],
[
[
-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697,
-13338309, 5500568,
],
[
12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343,
10874051, 13524335,
],
[
25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568,
-22528059, 5376628,
],
],
[
[
-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443,
4535768, 1569007,
],
[
-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290,
31848280, 12543772,
],
[
-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731,
7718482, 14474653,
],
],
[
[
2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665,
24316168, -5253567,
],
[
13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532,
-20729456, 8321686,
],
[
21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838,
-9984458, 608372,
],
],
[
[
-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577,
27229399, 23887,
],
[
-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308,
-1633405, 16678954,
],
[
-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045,
-17169265, 4904953,
],
],
[
[
24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880,
2128236, -4326833,
],
[
-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033,
-6882542, -2986532,
],
[
-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829,
15736322, 4143876,
],
],
[
[
2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663,
23527084, -16458268,
],
[
33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881,
-15188911, -14416214,
],
[
1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868,
-4774191, -16323038,
],
],
],
[
[
[
6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732,
7390890, 2759800,
],
[
4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057,
1244380, -12919645,
],
[
-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236,
15886429, 16489664,
],
],
[
[
1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369,
-30606455, -712933,
],
[
-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947,
-30836462, 5113182,
],
[
-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386,
13847711, 5387222,
],
],
[
[
-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786,
-19600662, 10370991,
],
[
20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092,
32232924, 16763880,
],
[
9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506,
3140038, -16510092,
],
],
[
[
-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613,
-28774454, 366295,
],
[
19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113,
719605, 11671788,
],
[
8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516,
27000813, -10195553,
],
],
[
[
-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097,
6750977, -14521026,
],
[
11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122,
8169720, 16220347,
],
[
-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664,
-5990708, -14166033,
],
],
[
[
-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284,
2655861, 1738395,
],
[
-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336,
-19087449, -11005278,
],
[
1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408,
10478196, 8544890,
],
],
[
[
32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473,
17789017, -3395995,
],
[
-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233,
30460520, 1052596,
],
[
-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359,
3179268, -9478891,
],
],
[
[
31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777,
-16411740, 19072640, -9511060,
],
[
11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017,
473099, 5040608,
],
[
-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092,
-19558642, -3131606,
],
],
],
[
[
[
7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149,
-27868496, 11538389,
],
[
-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702,
-5676054, 5797016,
],
[
-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574,
-2369172, -5877341,
],
],
[
[
-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199,
15123619, 10811505,
],
[
14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356,
-28886779, -11974553,
],
[
-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855,
4714547, -9600655,
],
],
[
[
15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832,
-11745876, 12340220,
],
[
12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152,
15370987, 9608631,
],
[
-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074,
-28210621, -8814099,
],
],
[
[
26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697,
20571223, 8420556,
],
[
14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406,
-21574435, -12476749,
],
[
236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136,
15069930,
],
],
[
[
1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229,
-30663140, -2331391,
],
[
5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378,
-33069337, 9234253,
],
[
20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587,
18979186, 13396066,
],
],
[
[
24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782,
33514650, 7021958,
],
[
-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677,
-21480480, 12868082,
],
[
-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500,
-12455797, -8089383,
],
],
[
[
-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937,
-15233648, 5540521,
],
[
-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984,
-16128528, -14962807,
],
[
23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185,
-11513277, -15205948,
],
],
[
[
9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127,
-19179614, 5867134,
],
[
-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263,
-29749703, -16108455,
],
[
27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073,
-19526700, 7734629,
],
],
],
[
[
[
-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626,
18549497, 15302069,
],
[
-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461,
-8872242, 8424746,
],
[
24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917,
-11284482, -828919,
],
],
[
[
11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461,
-5066034, 16498837,
],
[
8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238,
6536641, 10543906,
],
[
-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574,
-27235709, 8876771,
],
],
[
[
-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474,
-604426, -9039817,
],
[
10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394,
3084098,
],
[
10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151,
-30233575, 15272409,
],
],
[
[
-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138,
-25014757, 1950504,
],
[
-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532,
15341279, 8373727,
],
[
28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602,
-2878207, 15190420,
],
],
[
[
-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393,
-26033313, -6875003,
],
[
-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594,
-16247779, -12154742, 6048605,
],
[
-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323,
11213262, 9168384,
],
],
[
[
-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150,
20470157, -16398701,
],
[
-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608,
14042978, 5230683,
],
[
29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042,
-5933891, -12449708,
],
],
[
[
-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513,
-28539189, 15326563,
],
[
-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988,
-20514118, 9168260,
],
[
-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605,
33087103, -9011387,
],
],
[
[
-19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329,
-15000531, -5996870, 15664672,
],
[
23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356,
18151676, 13417686,
],
[
-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441,
15271676, -15452665,
],
],
],
[
[
[
11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544,
-6921301, -13440182,
],
[
-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997,
12215110, 12028277,
],
[
14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780,
-16900089, -655628,
],
],
[
[
-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009,
23973261, -12684474,
],
[
-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951,
32013174, -10103539,
],
[
-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752,
4425632, -837822,
],
],
[
[
-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462,
4725005, 14044970,
],
[
19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784,
-19522291, -16109756,
],
[
-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106,
9282262, 10282508,
],
],
[
[
-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215,
5542595, -10702683,
],
[
-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761,
-18093885, 10114655,
],
[
-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146,
25953725, -106158,
],
],
[
[
-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296,
-3315279, 12831125,
],
[
-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196,
7381791, -2421839,
],
[
-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724,
-15362489, 12339664,
],
],
[
[
27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922,
25091167, 14856294,
],
[
-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493,
-22182473, -9012899,
],
[
-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390,
30146206, 9142070,
],
],
[
[
3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384,
-8237858, 4171294,
],
[
-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949,
345228, -5462949,
],
[
-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231,
-16253183, -13582083,
],
],
[
[
31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657,
28012650, -16405420,
],
[
-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057,
-8867157, 3507940,
],
[
29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267,
-9164929, 6580396,
],
],
],
[
[
[
-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846,
-2095802, 9304567,
],
[
20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617,
5289421, -477127,
],
[
-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094,
26939669, -3752294,
],
],
[
[
-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559,
-3698806, 117887,
],
[
22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056,
-23319780, 541964,
],
[
16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829,
-13337066, -13552195,
],
],
[
[
9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351,
690426, 14876244,
],
[
24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348,
-22380984, 6618999,
],
[
-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328,
32239829, -5652762,
],
],
[
[
-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059,
32779359, 5095274,
],
[
-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724,
21639561, -2630236,
],
[
-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535,
17874574, 558605,
],
],
[
[
-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151,
2085892, 5119761,
],
[
-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614,
-31999993, -5759884,
],
[
-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145,
-22351378, 12961482,
],
],
[
[
-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996,
-30194652, -5159638,
],
[
-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275,
7589640, 8945490,
],
[
-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180,
24099109, -14456170,
],
],
[
[
5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025,
-6231896, -10280736,
],
[
10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898,
-3363451, -6441124,
],
[
-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168,
-13866408, 7421392,
],
],
[
[
8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252,
28826358, -4123029,
],
[
6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124,
13746021, -1742048,
],
[
28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524,
4771362, -8419958,
],
],
],
[
[
[
24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695,
3569627, 11342593,
],
[
26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608,
7325975, -14801071,
],
[
-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390,
-17646694, -8186692,
],
],
[
[
11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664,
9280358, -3973687,
],
[
-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901,
-11181622, -15545091, 4387441,
],
[
-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137,
20617071, -7482001,
],
],
[
[
-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822,
24345683, 10325460,
],
[
-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689,
4766743, 3552007,
],
[
-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909,
10988822, -3994762,
],
],
[
[
15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343,
-8295852, 13296005,
],
[
-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054,
-30000824, 12074674,
],
[
4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716,
29832613, -16391035,
],
],
[
[
7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297,
-27122660, 13101590,
],
[
-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593,
-30356070, -4190957,
],
[
-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896,
19568978, 9628812,
],
],
[
[
33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839,
-6291786, 3437740,
],
[
-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104,
7463304, 4176122,
],
[
-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751,
24216882, 5944158,
],
],
[
[
8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796,
11632993, 5847885,
],
[
26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194,
-9727230, 4782140,
],
[
19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911,
6358847, -1873857,
],
],
[
[
801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480,
-13538503, 1387155,
],
[
19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355,
-21866831, 11835260,
],
[
19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869,
-26560550, 5052483,
],
],
],
[
[
[
-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185,
12228557, -7003677,
],
[
32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564,
-6114803, 8653815,
],
[
22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875,
28483275, 2841751,
],
],
[
[
-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658,
19932058, -12739203,
],
[
-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134,
-4777469, -13910208,
],
[
1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705,
-14013818, 3093230,
],
],
[
[
16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225,
-24049421, -6691850,
],
[
-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618,
-21652117, -16739389,
],
[
-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798,
17361620, 11864968,
],
],
[
[
-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601,
-25578460, -16240689,
],
[
14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524,
9145645, -6443880,
],
[
5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128,
-5652273, -3050304,
],
],
[
[
30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496,
-27999779, 1803632,
],
[
-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514,
-21405489, 7047412,
],
[
20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601,
-32343828, -10257566,
],
],
[
[
-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640,
-21679658, 2288038,
],
[
-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692,
-24819617, 12570232,
],
[
-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680,
-11974704, 4724943,
],
],
[
[
17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932,
-29576300, 1903856,
],
[
23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296,
26955097, 14109738,
],
[
15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562,
31960942, 11934971,
],
],
[
[
-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028,
10491392, 1379718,
],
[
-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658,
21432314, 12180697,
],
[
-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540,
-10301319, -13872883,
],
],
],
[
[
[
5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231,
26128231, 6032912,
],
[
-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894,
-25875034, -10437358,
],
[
3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164,
12376617, 3188849,
],
],
[
[
29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113,
-16109234, -9852307,
],
[
-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669,
18640741, -960977,
],
[
-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430,
10530747, 1053335,
],
],
[
[
-29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369,
-2948985, 24018831, 15026644,
],
[
-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497,
-2314791, -15145616,
],
[
-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899,
-23166419, -2531735,
],
],
[
[
-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922,
-5070217, 726099,
],
[
29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461,
30007388, -15823341,
],
[
-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848,
4555336,
],
],
[
[
-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696,
-11985298, 12422646,
],
[
31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706,
29120153, 13924425,
],
[
-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700,
7240931, -237388,
],
],
[
[
-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483,
3293637, -15551743,
],
[
-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547,
12796905, -6335822,
],
[
-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836,
3222231, -11160462,
],
],
[
[
18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234,
-7550776, 2484985,
],
[
9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812,
-19802075, -3034702,
],
[
-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966,
-30097688, -10618797,
],
],
[
[
21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497,
-7360503, -4109293,
],
[
27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276,
-23659143, -8132100,
],
[
19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329,
13243957, 8709688,
],
],
],
[
[
[
12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734,
5150968, 7274186,
],
[
2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058,
31021603, -9793610,
],
[
-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465,
15067285, -14147707,
],
],
[
[
7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586,
-19379462, -12403220,
],
[
915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997,
-7220461, 16527025,
],
[
32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992,
23834301, 6588044,
],
],
[
[
32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107,
-20314580, -1305992,
],
[
-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281,
1976123, -7249027,
],
[
21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252,
12331345, -8237197,
],
],
[
[
8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970,
10008136, -4667901,
],
[
31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089,
8684155, -10532952,
],
[
19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921,
31316348, 14219878,
],
],
[
[
-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409,
29126555, 9207390,
],
[
32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782,
-7957600, -14435730,
],
[
2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130,
28346258, 1994730,
],
],
[
[
-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894,
22628102, 8115180,
],
[
-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160,
-9943017, 930272,
],
[
-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970,
-22765376, -10650715,
],
],
[
[
-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018,
-16554220, -1867018, 8398970,
],
[
-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273,
18009408, -15772772,
],
[
-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419,
19288549, 1325865,
],
],
[
[
15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146,
33166107, -8042750,
],
[
20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715,
2213263, -13878373,
],
[
32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134,
-5766928, 8371348,
],
],
],
[
[
[
9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132,
-26442943, 10486144,
],
[
-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596,
-23921530, -11455195,
],
[
5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541,
19985175, -3436086,
],
],
[
[
-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297,
65030, 8370684,
],
[
-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164,
12743482, -9800518,
],
[
-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569,
18800704, 255233,
],
],
[
[
-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957,
19258688, -14753793,
],
[
-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390,
-1524053, 2055794,
],
[
580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389,
-30021019, 7394435,
],
],
[
[
23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205,
-4821741, 14799921,
],
[
13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856,
-9056018, 7402518,
],
[
2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352,
8205061, 1607563,
],
],
[
[
14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958,
30019587, -9029278,
],
[
-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093,
9944378, 8024,
],
[
4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085,
-8142388, 5640030,
],
],
[
[
10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564,
15219798, -14327783,
],
[
27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195,
-18342183, 9742717,
],
[
6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155,
1994844,
],
],
[
[
14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803,
24319929, -6446333,
],
[
16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049,
-30102368, -4739048,
],
[
22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366,
21880021, -12250760,
],
],
[
[
-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729,
8840445, 4957760,
],
[
-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072,
-14796503, 5005757,
],
[
-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326,
-16395286, -2176112,
],
],
],
[
[
[
-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104,
22208662, 2000468,
],
[
3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527,
-3691214, -7414184,
],
[
10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332,
-3132688, 16400289,
],
],
[
[
15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580,
26894937, 9132066,
],
[
24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452,
-6817084, -2692882,
],
[
13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511,
-4688006, 2364226,
],
],
[
[
16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457,
15445875, -7798101,
],
[
29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540,
-278050, -15759279,
],
[
-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290,
-29828287, -10815811,
],
],
[
[
27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179,
17293797, 960709,
],
[
20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122,
-19384511, 7639714,
],
[
-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750,
29994677, -15808121,
],
],
[
[
9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782,
-31184575, 709464,
],
[
12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874,
16102007, 13205847,
],
[
13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972,
10151379, 10394400,
],
],
[
[
4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039,
-33302334, 8934414,
],
[
-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094,
-11536886, 11721158,
],
[
17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153,
-9205489, -1280045,
],
],
[
[
-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429,
6108462, -6183415,
],
[
-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331,
-26898490, -7867459,
],
[
-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095,
7592688, -14992079,
],
],
[
[
21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833,
-28256052, 4298412,
],
[
-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194,
13717174, 10805743,
],
[
-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609,
-26938930, -5863836,
],
],
],
[
[
[
12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704,
-4381056, 9882022,
],
[
18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879,
-23967430, -3299429,
],
[
-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110,
-2403099, 5276065,
],
],
[
[
30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982,
1449224, 13082861,
],
[
10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736,
-21016438, -8202000,
],
[
-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814,
-10300080, -11060101,
],
],
[
[
32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008,
-22664288, 6904815,
],
[
29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096,
-29003639, -6657642,
],
[
10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370,
-25584551, 5181966,
],
],
[
[
25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922,
-2322852, -12388574,
],
[
-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087,
20603771, -6561742,
],
[
-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390,
4662781, 7820689,
],
],
[
[
12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924,
16136752, 15264020,
],
[
-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822,
19012087, 3772772,
],
[
3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884,
20527771, 12988982,
],
],
[
[
-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943,
3299665, -12424953,
],
[
-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331,
-25583147, 8991218,
],
[
-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950,
-30242287, 1507265,
],
],
[
[
29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391,
14606362, -10647073,
],
[
-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487,
4170404, -2085325,
],
[
-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000,
-14276837, -8400798,
],
],
[
[
-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092,
13240845, 10965870,
],
[
-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411,
29514390, 4302863,
],
[
-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373,
17846988, -13971927,
],
],
],
[
[
[
-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789,
-5222701, 12650267,
],
[
-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293,
-19134326, 10958663,
],
[
22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455,
-25083830, 4271862,
],
],
[
[
-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529,
-32526221, 8469673,
],
[
15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372,
24154791, -9460943,
],
[
15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104,
24913809, 9815020,
],
],
[
[
-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769,
18735128, 9466238,
],
[
11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103,
-22728655, 16199064,
],
[
14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699,
30801119, 2164795,
],
],
[
[
15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269,
-13492807, 1268052,
],
[
-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221,
-17055369, 3565904,
],
[
29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713,
-27162222, -14030531,
],
],
[
[
-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423,
2244111, -14001979,
],
[
-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800,
13491506, 4641841,
],
[
10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242,
14476989, -12767431,
],
],
[
[
10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259,
-27912810, 12651324,
],
[
-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035,
21721536, -3148940,
],
[
10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694,
13216206, 14842320,
],
],
[
[
-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824,
-27434397, 9900184,
],
[
14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406,
-7051866, -8040114,
],
[<|fim▁hole|> ],
[
[
12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483,
15663516, 4035784,
],
[
-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334,
-22258478, 4659091,
],
[
-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997,
-2178256, -13455585,
],
],
],
[
[
[
-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095,
23440562, -290208,
],
[
10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483,
-16571960, -7442864,
],
[
17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594,
-3646624, 3898661,
],
],
[
[
7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530,
21831162, 1245233,
],
[
26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035,
-30402091, -16716212,
],
[
-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357,
-22338025, 13987525,
],
],
[
[
-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639,
-7469781, -2858068,
],
[
9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245,
-14581012, 4091397,
],
[
-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163,
29077877, -14741988,
],
],
[
[
5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881,
-20017847, 2357889,
],
[
32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908,
5727338, 189038,
],
[
14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115,
-25888931, -14884697,
],
],
[
[
20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781,
13913677, -5137875,
],
[
-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180,
12878652, 8511905,
],
[
-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974,
5568676, -3127656,
],
],
[
[
11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373,
-14395196, 8070818,
],
[
27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306,
-11552749, -1028714,
],
[
10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853,
-27493162, 15431203,
],
],
[
[
20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142,
-15056790, -7935931,
],
[
-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766,
-3356550, 9594024,
],
[
-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290,
13352335, -10977084,
],
],
[
[
-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482,
-13215537, -319204,
],
[
20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870,
-22750759, 14523817,
],
[
27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494,
-30172742, -4805667,
],
],
],
[
[
[
11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740,
-27727044, 11358504,
],
[
-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336,
-26123651, 4985768,
],
[
-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114,
-19414307, -15621255,
],
],
[
[
6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005,
-1691065, -9004790,
],
[
1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723,
-16796596, -5031438,
],
[
-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978,
-99853, -10237333,
],
],
[
[
17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976,
-29260363, -5511971,
],
[
31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247,
4882242, -10626905,
],
[
29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828,
-5190932, -4162409,
],
],
[
[
12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697,
330070, -3659409,
],
[
6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892,
-271295, 12071499,
],
[
-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675,
-5159697, 3829363,
],
],
[
[
28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787,
26333140, 14267664,
],
[
-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488,
-21761224, 8930324,
],
[
-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911,
-26491501, -16408940,
],
],
[
[
13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254,
-15943699, 13814990,
],
[
-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833,
-1956526, -1776914,
],
[
-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135,
-18685978, 4578290,
],
],
[
[
24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919,
21964432, 8235257,
],
[
-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206,
13006806, 2355433,
],
[
-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366,
1141648, -12796236,
],
],
[
[
-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972,
32674895, 13715045,
],
[
11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212,
-28740881, -15642093,
],
[
-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794,
-27245943, 4383347,
],
],
],
[
[
[
-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449,
27193557, 6245191,
],
[
-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492,
22510453, 8577507,
],
[
-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092,
-29571492, -3635906,
],
],
[
[
3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320,
5611860, 8164018,
],
[
-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289,
5773085, -8422109,
],
[
-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320,
31632953, 190926,
],
],
[
[
-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564,
-25341555, -3627528,
],
[
8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005,
-1672488, 827625,
],
[
-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036,
-24878478, 1541286,
],
],
[
[
2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481,
20456845, -1885033,
],
[
27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058,
29439641, 15138866,
],
[
21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163,
7779328, 109896,
],
],
[
[
30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118,
23177719, -554075,
],
[
26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492,
4439158, -13279347,
],
[
-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527,
-17717757, -5461437,
],
],
[
[
-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225,
8550082, -15114165,
],
[
-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739,
-23260460, -8428588,
],
[
-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482,
-21902570, 1494193,
],
],
[
[
-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112,
8742704, 12967017,
],
[
-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896,
-29903758, 15553883,
],
[
21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274,
19375923, -12647961,
],
],
[
[
8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716,
2862653, 9455043,
],
[
29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080,
15511449, 4789663,
],
[
-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893,
23513200, 16652362,
],
],
],
[
[
[
-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300,
-18319198, 10212860,
],
[
2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940,
-9988298, -12506466,
],
[
-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440,
-2499677, -16710063,
],
],
[
[
-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300,
2719757, 4940997,
],
[
-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463,
26699843, 5276295,
],
[
-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635,
-15452774, 7159369,
],
],
[
[
9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176,
22477218, -8403385,
],
[
18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995,
-22548173, 9334109,
],
[
2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545,
-22587149, 536906,
],
],
[
[
4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625,
10838060, -15420424,
],
[
-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950,
6378260, 699185,
],
[
7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155,
-5045064, -13373962,
],
],
[
[
-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840,
-3918636, -9669325,
],
[
10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568,
-21786507, 5427593,
],
[
696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720,
19236243, 12477404,
],
],
[
[
-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504,
-23169516, 7733644,
],
[
17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171,
10322027, 15313801,
],
[
26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982,
-24449242, 10890804,
],
],
[
[
-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931,
25180797, -5334884,
],
[
-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883,
316878, 13820577,
],
[
-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054,
30696930, -3712849,
],
],
[
[
32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397,
-32349517, 7392473,
],
[
-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995,
25112947, -2926644,
],
[
-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194,
5537438, -13914319,
],
],
],
[
[
[
-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667,
31234590, 6090599,
],
[
-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753,
-6970405, -9034768,
],
[
-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646,
20650474, 1804084,
],
],
[
[
-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713,
27842616, -202328,
],
[
-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932,
-11375082, 12714369,
],
[
20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546,
-19733229, 12796920,
],
],
[
[
12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495,
-12899438, 3480665, -15182815,
],
[
-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875,
-33374054, 2771025,
],
[
-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226,
-24552282, 15673397,
],
],
[
[
-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254,
3727144, -12934448,
],
[
6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683,
31123697, -10958981,
],
[
30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260,
-16432438, 9648165,
],
],
[
[
32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604,
-26008332, -11377501,
],
[
17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639,
2662509, -16297073,
],
[
-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777,
32247248, -14389861,
],
],
[
[
14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817,
-16027623, -13378845,
],
[
-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137,
17597934, 2346211,
],
[
18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352,
3059833, -11782870,
],
],
[
[
10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586,
-33502212, 3592096,
],
[
33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897,
-982665, -6837803,
],
[
-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704,
26353178, 693168,
],
],
[
[
30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668,
31375464, 14369965,
],
[
-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839,
17901441, 16011505,
],
[
18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240,
-16046376, 8764035, 12309598,
],
],
],
[
[
[
5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319,
17544096, -10593782,
],
[
5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127,
-5565381, 12348900,
],
[
-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295,
-10632534, -585479,
],
],
[
[
-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050,
30944593, 1130208,
],
[
8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540,
23550156, -271232,
],
[
17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146,
-408818, -137719,
],
],
[
[
16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936,
3260525, -7166271,
],
[
-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905,
-12748722, 2701326,
],
[
-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971,
11329923, 1862132,
],
],
[
[
14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231,
-9037963, -940300,
],
[
8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717,
-15438168, 11595570,
],
[
15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794,
-13489462, -4363670,
],
],
[
[
-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635,
977108, 699994,
],
[
-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841,
-30534533, -14337913,
],
[
31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775,
12493932, -5409317,
],
],
[
[
-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121,
29375955, 6024730,
],
[
842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184,
-9940361, 2854096,
],
[
-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770,
12121869, 16648078,
],
],
[
[
-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064,
20237806, 2838411,
],
[
-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457,
1068881, -12499905,
],
[
-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053,
12521378, 4845654,
],
],
[
[
-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400,
-6482306, -12885870,
],
[
-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216,
-3113227, 13974498,
],
[
12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737,
18895762, 12629579,
],
],
],
[
[
[
14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443,
32195181, 3895677,
],
[
10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119,
-8982069, 4429647,
],
[
-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895,
18047436, -15281743,
],
],
[
[
-25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114,
-12850837, -17620701, -9408468,
],
[
21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431,
-29958985, 8773375,
],
[
-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935,
-7874389, -13920155,
],
],
[
[
6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042,
-1721788, -2776725,
],
[
-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698,
28408820, 6816612,
],
[
-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702,
-10339570, 5067943,
],
],
[
[
-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132,
5331210, -10105944,
],
[
30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394,
27679908, -1648928,
],
[
9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565,
22611444, -12715406,
],
],
[
[
22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942,
4854859, 6622139,
],
[
-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227,
26404409, 13001963,
],
[
-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720,
-15405155, 11020693,
],
],
[
[
1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163,
28761762, 1406734,
],
[
-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088,
25577411, -13378680,
],
[
-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936,
-9368926, 4745410,
],
],
[
[
-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852,
10931924, -11931931,
],
[
-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641,
-20470770, 13434654,
],
[
22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326,
28445307, -5364710,
],
],
[
[
29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675,
9074234, 1167180,
],
[
-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498,
3843903, 9367684,
],
[
-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684,
-139197, 4242895,
],
],
],
[
[
[
22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660,
-27417366, 16625501,
],
[
-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725,
-27351616, 14247413,
],
[
6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061,
27108877, -1180880,
],
],
[
[
-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889,
-27148451, 981874,
],
[
22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780,
-10479804, -16197962,
],
[
-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969,
-15933690, 3797899,
],
],
[
[
21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232,
20491983, -8042152,
],
[
9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587,
30997318, -6703063,
],
[
7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576,
17649998, -250080,
],
],
[
[
-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724,
-2233253, 7662146,
],
[
-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199,
-3174674, 3440183,
],
[
-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835,
4862400, 1133,
],
],
[
[
-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861,
-30594991, -7379421,
],
[
-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196,
18278453, 15405622,
],
[
-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523,
-21875062, 13626197,
],
],
[
[
2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792,
13340839, 15928663,
],
[
31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826,
-23452306, 5964753,
],
[
4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144,
2538215, -7570755,
],
],
[
[
-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421,
-629256, -15958862,
],
[
-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288,
11659922, -11115118,
],
[
26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080,
33100372, -1306171,
],
],
[
[
15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675,
-5931810, -14466380,
],
[
16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968,
-10735770, -10039824,
],
[
28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599,
18036436, 5803270,
],
],
],
[
[
[
-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332,
-6159431, -14117438,
],
[
-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292,
-20095739, 11763584,
],
[
-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632,
-19773211, -10713562,
],
],
[
[
30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773,
-17020157, 992471,
],
[
18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033,
-11574335, -10601610,
],
[
19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234,
26224780, 16452269,
],
],
[
[
-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186,
-20533829, 3698650,
],
[
14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444,
27394301, 12015369,
],
[
19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777,
-13259127, -3402461,
],
],
[
[
30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312,
-8550524, -10393462,
],
[
-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654,
-4976164, 12651793,
],
[
-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902,
9768698, -2533218,
],
],
[
[
-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450,
4940095, 10678226,
],
[
18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024,
-24372348, 16582019,
],
[
-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560,
-11003761, 7989037,
],
],
[
[
31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206,
-19686113, -14800171,
],
[
-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713,
28550068, -6857132,
],
[
-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038,
1155602, 5988841,
],
],
[
[
21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481,
24618407, 8283181,
],
[
-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928,
1466169, 10740210,
],
[
-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719,
-32164649, -15327040,
],
],
[
[
3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507,
-3260321, -573935,
],
[
24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372,
-7380369, -6144105,
],
[
-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463,
-14453128, -1625486, -6494814,
],
],
],
[
[
[
793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251,
-9906200, -621852,
],
[
5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826,
-6171428, -15186581,
],
[
-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238,
-1558923, -9863646,
],
],
[
[
10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338,
-30581476, -15757844,
],
[
10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496,
24003793, 14264025,
],
[
27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525,
13958495, -5732453,
],
],
[
[
-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781,
7340521, -15410068,
],
[
4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061,
-15066784, -10375192,
],
[
-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888,
-8843694, 3849921,
],
],
[
[
-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955,
5002294, -15550259,
],
[
-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448,
-25845716, 12741426,
],
[
-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464,
28834118, -7646072,
],
],
[
[
-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841,
20461858, 5491305,
],
[
13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986,
11293807, -28588204, -9421832,
],
[
28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166,
29867745, -8795943,
],
],
[
[
-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392,
22853429, -4012011,
],
[
24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887,
12876623, -2112447,
],
[
17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397,
16031844, 3723494,
],
],
[
[
-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890,
23896954, -4314245,
],
[
-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064,
-9919646, -8826859,
],
[
28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325,
-18051778, -2082915,
],
],
[
[
16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268,
-19715240, 7847707,
],
[
10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018,
-10020567, 3852848,
],
[
-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110,
29330899, -15076224,
],
],
],
[
[
[
-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490,
-27548796, 12314391,
],
[
15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866,
16103996, -3731215,
],
[
-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699,
-29815713, -9841101,
],
],
[
[
23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517,
-25205859, 2739713,
],
[
21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907,
4931255, 11987849,
],
[
-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388,
-30076310, 10117930,
],
],
[
[
-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079,
12890019, 15728940,
],
[
-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139,
12885167, 8311031,
],
[
-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730,
1888765, -5435404,
],
],
[
[
-25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644,
-12707869, -19464434, -3340243,
],
[
-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197,
17151279, -9854116,
],
[
-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279,
-16866484, 16176525,
],
],
[
[
-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426,
-28746253, -10197509,
],
[
-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610,
32808310, 1099883,
],
[
15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350,
2051441, -15225865,
],
],
[
[
-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188,
-22686354, 16633660,
],
[
4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549,
8402478, -9864273,
],
[
-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072,
17983010, 9967138,
],
],
[
[
-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337,
17507396, 3651560,
],
[
-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557,
-18553322, -11357135,
],
[
2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447,
-5605463, -7621941,
],
],
[
[
-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066,
17258084, -7977739,
],
[
18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008,
26908270, 12150756,
],
[
-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701,
-32302074, 16215819,
],
],
],
[
[
[
-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905,
-7503072, -8675347,
],
[
-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080,
21676107, -1943028,
],
[
21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466,
-3556191, -7913075,
],
],
[
[
16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336,
-18907032, -9662799,
],
[
-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659,
25459437, -4564609,
],
[
-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602,
-6432418, -1644817,
],
],
[
[
-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658,
6335692, 7249989,
],
[
-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242,
25993170, -12478523,
],
[
4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955,
31820368, 15075278,
],
],
[
[
31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886,
-17970238, 12833045,
],
[
19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449,
-9413939, 14905377,
],
[
24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129,
27628530, -7555480,
],
],
[
[
17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582,
-14110875, 15297016,
],
[
510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220,
8683221, 2921426,
],
[
18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924,
4674690, 13890525,
],
],
[
[
13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105,
4389687, 288396,
],
[
9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628,
23388070, 16052080,
],
[
12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979,
-14754271, -10812892,
],
],
[
[
15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844,
-28822128, 929275,
],
[
11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533,
-9371869, -21393143, 2465074,
],
[
20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066,
2463391, -4622140,
],
],
[
[
-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107,
4003896, 12673717,
],
[
-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726,
7903886, 2348101,
],
[
24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159,
-28377538, 10048127,
],
],
],
[
[
[
-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090,
-32297756, 15221632,
],
[
-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755,
29769758, 6593415,
],
[
-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678,
30958054, 8292160,
],
],
[
[
31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186,
26143136, -3148876,
],
[
22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433,
-3758243, -2304625,
],
[
-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569,
-16664475, 8194478,
],
],
[
[
27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376,
28572286, 3005164,
],
[
26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479,
-26094821, -13079595,
],
[
-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627,
32208683, -1198248,
],
],
[
[
-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842,
-27672585, -11539858,
],
[
15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429,
15397331, -4130193,
],
[
8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021,
-27505566, 15087184,
],
],
[
[
-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896,
16788528, -5868942,
],
[
-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320,
31322514, -11615635,
],
[
21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414,
13040862, -12112948,
],
],
[
[
11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103,
1613711, 4896935,
],
[
-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045,
-23971776, -11267415,
],
[
-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433,
-23753030, -8436416,
],
],
[
[
-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030,
23097949, -566018,
],
[
4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221,
-18512313, 2424778,
],
[
366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109,
-3642553, 12412659,
],
],
[
[
-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504,
-3141501, 11179385,
],
[
18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897,
-18684645, -11443503,
],
[
476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813,
11052904, 5219329,
],
],
],
[
[
[
20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730,
9014762, -8579056,
],
[
-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280,
8473550, -3256838,
],
[
24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821,
-24568481, 11788948,
],
],
[
[
-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733,
-24568470, -1458691,
],
[
-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194,
-18513325, 8464118,
],
[
-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612,
33313881, -8370517,
],
],
[
[
-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854,
-8940735, -5818269,
],
[
-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188,
28358192, -4253904,
],
[
-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016,
-5351664, 5596589,
],
],
[
[
-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221,
1768301, 15373193,
],
[
-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991,
-24660491, 3442910,
],
[
-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455,
-18585478, 13365930,
],
],
[
[
-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186,
-9689599, -3031667,
],
[
25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784,
15723479, -15163481,
],
[
-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171,
519526, -1235876,
],
],
[
[
22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967,
16648397, 7605640,
],
[
-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555,
-9468848, 4763278,
],
[
-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523,
-11356529, 728112,
],
],
[
[
26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558,
-29365436, -5498272,
],
[
17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945,
10750447, 10014012,
],
[
-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732,
3424691, 7540221,
],
],
[
[
30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219,
-9244265, 15258046,
],
[
13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395,
1062915, -5136345,
],
[
-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497,
32960380, 1459310,
],
],
],
[
[
[
19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885,
18638003, -11174937,
],
[
31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354,
-6643087, -5442636,
],
[
-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543,
-32294889, -6456008,
],
],
[
[
-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692,
-7852844, -8138429,
],
[
-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588,
-9431476, 5203576,
],
[
31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524,
31809243, 7347066,
],
],
[
[
-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255,
15192876, -2087490,
],
[
-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420,
33473243, -13382104,
],
[
33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903,
-6135662, 14480053,
],
],
[
[
31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227,
27595050, 8737275,
],
[
-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604,
26498114, 66511,
],
[
22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747,
-13327787, -7515095,
],
],
[
[
-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437,
-17127465, 15115439,
],
[
23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096,
8236921, 16492939,
],
[
-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562,
6708380, -6222424,
],
],
[
[
2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700,
29955601, -11678310,
],
[
3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595,
-9917575, 6216608,
],
[
-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567,
-26767480, 7525079,
],
],
[
[
-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495,
-19386633, 11994101,
],
[
21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258,
-7477437, 13381418,
],
[
18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247,
28535282, 15779576,
],
],
[
[
30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730,
9955285, -16303356,
],
[
9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399,
20194861, 13380996,
],
[
-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771,
26342023, 10146099,
],
],
],
[
[
[
-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040,
21612326, -545728,
],
[
-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797,
-20856566, 11649658,
],
[
-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064,
33514190, 2333242,
],
],
[
[
-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638,
24350578, -13450001,
],
[
-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836,
8317860, 12352766,
],
[
18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550,
20712163, 6719373,
],
],
[
[
26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210,
26224235, -3297458,
],
[
-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610,
18620611, -16428628,
],
[
-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556,
-30701573, -16479657,
],
],
[
[
-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639,
13735342, 1934062,
],
[
25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346,
-21277997, 5473616,
],
[
31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656,
29111212, -5451014,
],
],
[
[
24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839,
-10295587, 452383,
],
[
-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248,
15766062, 8407814,
],
[
-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953,
-8067909, 2276718,
],
],
[
[
30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219,
22740376, -7303417,
],
[
2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383,
-15637599, 13295222,
],
[
33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972,
-4451357, -14669444,
],
],
[
[
-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880,
7770569, 9620597,
],
[
23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323,
-33502340, -14767970,
],
[
1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118,
30494170, -11440799,
],
],
[
[
-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050,
-1684339, -13333647,
],
[
13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865,
3353509, 4033511,
],
[
-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127,
27485041, 7356032,
],
],
],
[
[
[
9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015,
28431036, -16771834,
],
[
-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565,
15970762, 4099461,
],
[
29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143,
11465739, 8317062,
],
],
[
[
-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455,
20969334, -5157516,
],
[
-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888,
11177095, 14989547,
],
[
-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286,
-28487508, 9930240,
],
],
[
[
-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767,
-13403753, 16291481, -5314038,
],
[
-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617,
4368891, 9788741,
],
[
16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148,
16250552, -11111103,
],
],
[
[
-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807,
-30190403, 4782747,
],
[
-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045,
22546403, 437323,
],
[
31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261,
-30633590, -14097016,
],
],
[
[
-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319,
-19284671, -6114373,
],
[
15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498,
-29380133, 11754228,
],
[
-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556,
22761615, -10134141,
],
],
[
[
16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393,
32851222, 11717399,
],
[
11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633,
-1193175, -4030831,
],
[
-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660,
-19985279, -3948376,
],
],
[
[
-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048,
-30772034, -15486313,
],
[
-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879,
10928917, 3011958,
],
[
-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180,
18008031, 10258577,
],
],
[
[
-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120,
25127874, 6671743,
],
[
29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292,
25838796, 4642684,
],
[
-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640,
18423289, 4177476,
],
],
],
];<|fim▁end|> | 30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635,
9524356, -7018878,
], |
<|file_name|>Aliases.py<|end_file_name|><|fim▁begin|># Generated from 'Aliases.h'
def FOUR_CHAR_CODE(x): return x
true = True
false = False
rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1<|fim▁hole|><|fim▁end|> | asiAliasName = 0
asiParentName = 1
kResolveAliasFileNoUI = 0x00000001 |
<|file_name|>RedundantStringOperationMerger.java<|end_file_name|><|fim▁begin|>// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.siyeh.ig.redundancy;
import com.google.common.collect.ImmutableSet;
import com.intellij.codeInspection.ex.InspectionElementsMergerBase;
import com.intellij.util.ArrayUtilRt;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Set;
public class RedundantStringOperationMerger extends InspectionElementsMergerBase {
private static final String OLD_MERGER_NAME = "RedundantStringOperation";
private static final Set<String> OLD_SOURCE_NAMES = ImmutableSet.of("StringToString", "SubstringZero", "ConstantStringIntern");
@NotNull
@Override
public String getMergedToolName() {
return "StringOperationCanBeSimplified";
}
@Override
protected Element getSourceElement(@NotNull Map<String, Element> inspectionElements, @NotNull String sourceToolName) {<|fim▁hole|> if (inspectionElements.containsKey(sourceToolName)) {
return inspectionElements.get(sourceToolName);
}
if (sourceToolName.equals(OLD_MERGER_NAME)) {//need to merge initial tools to get merged redundant string operations
return new InspectionElementsMergerBase(){
@NotNull
@Override
public String getMergedToolName() {
return OLD_MERGER_NAME;
}
@Override
public String @NotNull [] getSourceToolNames() {
return ArrayUtilRt.toStringArray(OLD_SOURCE_NAMES);
}
@Override
public Element merge(@NotNull Map<String, Element> inspectionElements) {
return super.merge(inspectionElements);
}
@Override
protected boolean writeMergedContent(@NotNull Element toolElement) {
return true;
}
}.merge(inspectionElements);
}
else if (OLD_SOURCE_NAMES.contains(sourceToolName)) {
Element merged = inspectionElements.get(OLD_MERGER_NAME);
if (merged != null) { // RedundantStringOperation already replaced the content
Element clone = merged.clone();
clone.setAttribute("class", sourceToolName);
return clone;
}
}
return null;
}
@Override
public String @NotNull [] getSourceToolNames() {
return new String[] {
"StringToString",
"SubstringZero",
"ConstantStringIntern",
"StringConstructor",
OLD_MERGER_NAME
};
}
@Override
public String @NotNull [] getSuppressIds() {
return new String[] {
"StringToString", "RedundantStringToString",
"SubstringZero", "ConstantStringIntern",
"RedundantStringConstructorCall", "StringConstructor", OLD_MERGER_NAME
};
}
}<|fim▁end|> | |
<|file_name|>edit.py<|end_file_name|><|fim▁begin|># This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from copy import deepcopy
from django import forms
from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.models import modelform_factory<|fim▁hole|>
from shoop.admin.base import MenuEntry
from shoop.admin.toolbar import Toolbar, URLActionButton, get_default_edit_toolbar
from shoop.admin.utils.views import CreateOrUpdateView
from shoop.core.models import PaymentMethod, ShippingMethod
from shoop.core.modules.interface import ModuleNotFound
from shoop.utils.multilanguage_model_form import MultiLanguageModelForm
class MethodEditToolbar(Toolbar):
def __init__(self, view_object):
super(Toolbar, self).__init__()
self.view_object = view_object
get_default_edit_toolbar(toolbar=self, view_object=view_object, save_form_id="method_form")
method = view_object.object
if method.pk:
self.build_detail_button(method)
def build_detail_button(self, method):
disable_reason = None
try:
if not method.module.admin_detail_view_class:
disable_reason = _("The selected module has no details to configure")
except ModuleNotFound:
disable_reason = _("The selected module is not currently available")
self.append(URLActionButton(
url=reverse(
"shoop_admin:%s.edit-detail" % self.view_object.action_url_name_prefix,
kwargs={"pk": method.pk}
),
text=_("Edit Details"),
icon="fa fa-pencil",
extra_css_class="btn-info",
disable_reason=disable_reason
))
class _BaseMethodEditView(CreateOrUpdateView):
model = None # Overridden below
action_url_name_prefix = None
template_name = "shoop/admin/methods/edit.jinja"
form_class = forms.Form
context_object_name = "method"
@property
def title(self):
return _(u"Edit %(model)s") % {"model": self.model._meta.verbose_name}
def get_breadcrumb_parents(self):
return [
MenuEntry(
text=force_text(self.model._meta.verbose_name_plural).title(),
url="shoop_admin:%s.list" % self.action_url_name_prefix
)
]
def get_form(self, form_class=None):
form_class = modelform_factory(
model=self.model,
form=MultiLanguageModelForm,
fields=("name", "status", "tax_class", "module_identifier"),
widgets={"module_identifier": forms.Select},
)
form = form_class(languages=settings.LANGUAGES, **self.get_form_kwargs())
form.fields["module_identifier"].widget.choices = self.model.get_module_choices(
empty_label=(_("Default %s module") % self.model._meta.verbose_name).title()
)
# Add fields from the module, if any...
form.module_option_field_names = []
for field_name, field in self.object.module.option_fields:
form.fields[field_name] = deepcopy(field)
form.module_option_field_names.append(field_name)
if self.object.module_data and field_name in self.object.module_data:
form.initial[field_name] = self.object.module_data[field_name]
return form
def get_success_url(self):
return reverse("shoop_admin:%s.edit" % self.action_url_name_prefix, kwargs={"pk": self.object.pk})
def get_toolbar(self):
return MethodEditToolbar(self)
def save_form(self, form):
self.object = form.save()
if not self.object.module_data:
self.object.module_data = {}
for field_name in form.module_option_field_names:
if field_name in form.cleaned_data:
self.object.module_data[field_name] = form.cleaned_data[field_name]
self.object.save()
class ShippingMethodEditView(_BaseMethodEditView):
model = ShippingMethod
action_url_name_prefix = "method.shipping"
class PaymentMethodEditView(_BaseMethodEditView):
model = PaymentMethod
action_url_name_prefix = "method.payment"<|fim▁end|> | from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _ |
<|file_name|>client.go<|end_file_name|><|fim▁begin|>package muduorpc
import (
"bufio"
"fmt"
"io"
"net/rpc"
"strings"
"code.google.com/p/goprotobuf/proto"
)
type ClientCodec struct {
conn io.ReadWriteCloser
r io.Reader
payload []byte
}
func (c *ClientCodec) WriteRequest(r *rpc.Request, body interface{}) error {
msg := new(RpcMessage)
msg.Type = MessageType_REQUEST.Enum()
msg.Id = &r.Seq
last_dot := strings.LastIndex(r.ServiceMethod, ".")
if last_dot < 0 {
panic(fmt.Sprintf("Invalid ServiceMethod '%s'", r.ServiceMethod))
}
service := r.ServiceMethod[:last_dot]
msg.Service = &service
method := r.ServiceMethod[last_dot+1:]
msg.Method = &method
pb, ok := body.(proto.Message)
if !ok {
return fmt.Errorf("not a protobuf Message")
}
b, err := proto.Marshal(pb)
if err != nil {
return err
}
msg.Request = b
return Send(c.conn, msg)
}
func (c *ClientCodec) ReadResponseHeader(r *rpc.Response) (err error) {
if c.payload != nil {
panic("payload is not nil")
}
var msg *RpcMessage
msg, err = Decode(c.r)
if err != nil {
return
}
if *msg.Type != *MessageType_RESPONSE.Enum() {
err = fmt.Errorf("Wrong message type.")
return
}
r.Seq = *msg.Id
c.payload = msg.Response
return nil
}
// FIXME: merge dup code with ServerCodec.ReadRequestBody()
func (c *ClientCodec) ReadResponseBody(body interface{}) (err error) {
if c.payload == nil {
panic("payload is nil")
}
msg, ok := body.(proto.Message)
if !ok {
return fmt.Errorf("body is not a protobuf Message")
}
err = proto.Unmarshal(c.payload, msg)
if err != nil {
return
}
c.payload = nil<|fim▁hole|>
func (c *ClientCodec) Close() error {
return c.conn.Close()
}
func NewClientCodec(conn io.ReadWriteCloser) *ClientCodec {
codec := new(ClientCodec)
codec.conn = conn
codec.r = bufio.NewReader(conn)
return codec
}<|fim▁end|> | return
} |
<|file_name|>test_submitting_problems.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Integration tests for submitting problem responses and getting grades.
"""
import json
import os
from textwrap import dedent
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from mock import patch
from nose.plugins.attrib import attr
from capa.tests.response_xml_factory import (
OptionResponseXMLFactory, CustomResponseXMLFactory, SchematicResponseXMLFactory,
CodeResponseXMLFactory,
)
from courseware import grades
from courseware.models import StudentModule, StudentModuleHistory
from courseware.tests.helpers import LoginEnrollmentTestCase
from lms.djangoapps.lms_xblock.runtime import quote_slashes
from student.tests.factories import UserFactory
from student.models import anonymous_id_for_user
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from xmodule.partitions.partitions import Group, UserPartition
from openedx.core.djangoapps.credit.api import (
set_credit_requirements, get_credit_requirement_status
)
from openedx.core.djangoapps.credit.models import CreditCourse, CreditProvider
from openedx.core.djangoapps.user_api.tests.factories import UserCourseTagFactory
from openedx.core.djangoapps.grading_policy.utils import MaxScoresCache
class TestSubmittingProblems(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Check that a course gets graded properly.
"""
# arbitrary constant
COURSE_SLUG = "100"
COURSE_NAME = "test_course"
def setUp(self):
super(TestSubmittingProblems, self).setUp(create_user=False)
# Create course
self.course = CourseFactory.create(display_name=self.COURSE_NAME, number=self.COURSE_SLUG)
assert self.course, "Couldn't load course %r" % self.COURSE_NAME
# create a test student
self.student = '[email protected]'
self.password = 'foo'
self.create_account('u1', self.student, self.password)
self.activate_user(self.student)
self.enroll(self.course)
self.student_user = User.objects.get(email=self.student)
self.factory = RequestFactory()
def refresh_course(self):
"""
Re-fetch the course from the database so that the object being dealt with has everything added to it.
"""
self.course = self.store.get_course(self.course.id)
def problem_location(self, problem_url_name):
"""
Returns the url of the problem given the problem's name
"""
return self.course.id.make_usage_key('problem', problem_url_name)
def modx_url(self, problem_location, dispatch):
"""
Return the url needed for the desired action.
problem_location: location of the problem on which we want some action
dispatch: the the action string that gets passed to the view as a kwarg
example: 'check_problem' for having responses processed
"""
return reverse(
'xblock_handler',
kwargs={
'course_id': self.course.id.to_deprecated_string(),
'usage_id': quote_slashes(problem_location.to_deprecated_string()),
'handler': 'xmodule_handler',
'suffix': dispatch,
}
)
def submit_question_answer(self, problem_url_name, responses):
"""
Submit answers to a question.
Responses is a dict mapping problem ids to answers:
{'2_1': 'Correct', '2_2': 'Incorrect'}
"""
problem_location = self.problem_location(problem_url_name)
modx_url = self.modx_url(problem_location, 'problem_check')
answer_key_prefix = 'input_{}_'.format(problem_location.html_id())
# format the response dictionary to be sent in the post request by adding the above prefix to each key
response_dict = {(answer_key_prefix + k): v for k, v in responses.items()}
resp = self.client.post(modx_url, response_dict)
return resp
def look_at_question(self, problem_url_name):
"""
Create state for a problem, but don't answer it
"""
location = self.problem_location(problem_url_name)
modx_url = self.modx_url(location, "problem_get")
resp = self.client.get(modx_url)
return resp
def reset_question_answer(self, problem_url_name):
"""
Reset specified problem for current user.
"""
problem_location = self.problem_location(problem_url_name)
modx_url = self.modx_url(problem_location, 'problem_reset')
resp = self.client.post(modx_url)
return resp
def show_question_answer(self, problem_url_name):
"""
Shows the answer to the current student.
"""
problem_location = self.problem_location(problem_url_name)
modx_url = self.modx_url(problem_location, 'problem_show')
resp = self.client.post(modx_url)
return resp
def add_dropdown_to_section(self, section_location, name, num_inputs=2):
"""
Create and return a dropdown problem.
section_location: location object of section in which to create the problem
(problems must live in a section to be graded properly)
name: string name of the problem
num_input: the number of input fields to create in the problem
"""
prob_xml = OptionResponseXMLFactory().build_xml(
question_text='The correct answer is Correct',
num_inputs=num_inputs,
weight=num_inputs,
options=['Correct', 'Incorrect', u'ⓤⓝⓘⓒⓞⓓⓔ'],
correct_option='Correct'
)
problem = ItemFactory.create(
parent_location=section_location,
category='problem',
data=prob_xml,
metadata={'rerandomize': 'always'},
display_name=name
)
# re-fetch the course from the database so the object is up to date
self.refresh_course()
return problem
def add_graded_section_to_course(self, name, section_format='Homework', late=False, reset=False, showanswer=False):
"""
Creates a graded homework section within a chapter and returns the section.
"""
# if we don't already have a chapter create a new one
if not(hasattr(self, 'chapter')):
self.chapter = ItemFactory.create(
parent_location=self.course.location,
category='chapter'
)
if late:
section = ItemFactory.create(
parent_location=self.chapter.location,
display_name=name,
category='sequential',
metadata={'graded': True, 'format': section_format, 'due': '2013-05-20T23:30'}
)
elif reset:
section = ItemFactory.create(
parent_location=self.chapter.location,
display_name=name,
category='sequential',
rerandomize='always',
metadata={
'graded': True,
'format': section_format,
}
)
elif showanswer:
section = ItemFactory.create(
parent_location=self.chapter.location,
display_name=name,
category='sequential',
showanswer='never',
metadata={
'graded': True,
'format': section_format,
}
)
else:
section = ItemFactory.create(
parent_location=self.chapter.location,
display_name=name,
category='sequential',
metadata={'graded': True, 'format': section_format}
)
# now that we've added the problem and section to the course
# we fetch the course from the database so the object we are
# dealing with has these additions
self.refresh_course()
return section
def add_grading_policy(self, grading_policy):
"""
Add a grading policy to the course.
"""
self.course.grading_policy = grading_policy
self.update_course(self.course, self.student_user.id)
self.refresh_course()
def get_grade_summary(self):
"""
calls grades.grade for current user and course.
the keywords for the returned object are
- grade : A final letter grade.
- percent : The final percent for the class (rounded up).
- section_breakdown : A breakdown of each section that makes
up the grade. (For display)
- grade_breakdown : A breakdown of the major components that
make up the final grade. (For display)
"""
fake_request = self.factory.get(
reverse('progress', kwargs={'course_id': self.course.id.to_deprecated_string()})
)
fake_request.user = self.student_user
return grades.grade(self.student_user, fake_request, self.course)
def get_progress_summary(self):
"""
Return progress summary structure for current user and course.
Returns
- courseware_summary is a summary of all sections with problems in the course.
It is organized as an array of chapters, each containing an array of sections,
each containing an array of scores. This contains information for graded and
ungraded problems, and is good for displaying a course summary with due dates,
etc.
"""
fake_request = self.factory.get(
reverse('progress', kwargs={'course_id': self.course.id.to_deprecated_string()})
)
progress_summary = grades.progress_summary(
self.student_user, fake_request, self.course
)
return progress_summary
def check_grade_percent(self, percent):
"""
Assert that percent grade is as expected.
"""
grade_summary = self.get_grade_summary()
self.assertEqual(grade_summary['percent'], percent)
def earned_hw_scores(self):
"""
Global scores, each Score is a Problem Set.
Returns list of scores: [<points on hw_1>, <points on hw_2>, ..., <points on hw_n>]
"""
return [s.earned for s in self.get_grade_summary()['totaled_scores']['Homework']]
def score_for_hw(self, hw_url_name):
"""
Returns list of scores for a given url.
Returns list of scores for the given homework:
[<points on problem_1>, <points on problem_2>, ..., <points on problem_n>]
"""
# list of grade summaries for each section
sections_list = []
for chapter in self.get_progress_summary():
sections_list.extend(chapter['sections'])
# get the first section that matches the url (there should only be one)
hw_section = next(section for section in sections_list if section.get('url_name') == hw_url_name)
return [s.earned for s in hw_section['scores']]
@attr('shard_1')
class TestCourseGrader(TestSubmittingProblems):
"""
Suite of tests for the course grader.
"""
def basic_setup(self, late=False, reset=False, showanswer=False):
"""
Set up a simple course for testing basic grading functionality.
"""
grading_policy = {
"GRADER": [{
"type": "Homework",
"min_count": 1,
"drop_count": 0,
"short_label": "HW",
"weight": 1.0
}],
"GRADE_CUTOFFS": {
'A': .9,
'B': .33
}
}
self.add_grading_policy(grading_policy)
# set up a simple course with four problems
self.homework = self.add_graded_section_to_course('homework', late=late, reset=reset, showanswer=showanswer)
self.add_dropdown_to_section(self.homework.location, 'p1', 1)
self.add_dropdown_to_section(self.homework.location, 'p2', 1)
self.add_dropdown_to_section(self.homework.location, 'p3', 1)
self.refresh_course()
def weighted_setup(self):
"""
Set up a simple course for testing weighted grading functionality.
"""
grading_policy = {
"GRADER": [
{
"type": "Homework",
"min_count": 1,
"drop_count": 0,
"short_label": "HW",
"weight": 0.25
}, {
"type": "Final",
"name": "Final Section",
"short_label": "Final",
"weight": 0.75
}
]
}
self.add_grading_policy(grading_policy)
# set up a structure of 1 homework and 1 final
self.homework = self.add_graded_section_to_course('homework')
self.problem = self.add_dropdown_to_section(self.homework.location, 'H1P1')
self.final = self.add_graded_section_to_course('Final Section', 'Final')
self.final_question = self.add_dropdown_to_section(self.final.location, 'FinalQuestion')
def dropping_setup(self):
"""
Set up a simple course for testing the dropping grading functionality.
"""
grading_policy = {
"GRADER": [
{
"type": "Homework",
"min_count": 3,
"drop_count": 1,
"short_label": "HW",
"weight": 1
}
]
}
self.add_grading_policy(grading_policy)
# Set up a course structure that just consists of 3 homeworks.
# Since the grading policy drops 1 entire homework, each problem is worth 25%
# names for the problem in the homeworks
self.hw1_names = ['h1p1', 'h1p2']
self.hw2_names = ['h2p1', 'h2p2']
self.hw3_names = ['h3p1', 'h3p2']
self.homework1 = self.add_graded_section_to_course('homework1')
self.add_dropdown_to_section(self.homework1.location, self.hw1_names[0], 1)
self.add_dropdown_to_section(self.homework1.location, self.hw1_names[1], 1)
self.homework2 = self.add_graded_section_to_course('homework2')
self.add_dropdown_to_section(self.homework2.location, self.hw2_names[0], 1)
self.add_dropdown_to_section(self.homework2.location, self.hw2_names[1], 1)
self.homework3 = self.add_graded_section_to_course('homework3')
self.add_dropdown_to_section(self.homework3.location, self.hw3_names[0], 1)
self.add_dropdown_to_section(self.homework3.location, self.hw3_names[1], 1)
def test_submission_late(self):
"""Test problem for due date in the past"""
self.basic_setup(late=True)
resp = self.submit_question_answer('p1', {'2_1': 'Correct'})
self.assertEqual(resp.status_code, 200)
err_msg = (
"The state of this problem has changed since you loaded this page. "
"Please refresh your page."
)
self.assertEqual(json.loads(resp.content).get("success"), err_msg)
def test_submission_reset(self):
"""Test problem ProcessingErrors due to resets"""
self.basic_setup(reset=True)
resp = self.submit_question_answer('p1', {'2_1': 'Correct'})
# submit a second time to draw NotFoundError
resp = self.submit_question_answer('p1', {'2_1': 'Correct'})
self.assertEqual(resp.status_code, 200)
err_msg = (
"The state of this problem has changed since you loaded this page. "
"Please refresh your page."
)
self.assertEqual(json.loads(resp.content).get("success"), err_msg)
def test_submission_show_answer(self):
"""Test problem for ProcessingErrors due to showing answer"""
self.basic_setup(showanswer=True)
resp = self.show_question_answer('p1')
self.assertEqual(resp.status_code, 200)
err_msg = (
"The state of this problem has changed since you loaded this page. "
"Please refresh your page."
)
self.assertEqual(json.loads(resp.content).get("success"), err_msg)
def test_show_answer_doesnt_write_to_csm(self):
self.basic_setup()
self.submit_question_answer('p1', {'2_1': u'Correct'})
# Now fetch the state entry for that problem.
student_module = StudentModule.objects.get(
course_id=self.course.id,
student=self.student_user
)
# count how many state history entries there are
baseline = StudentModuleHistory.objects.filter(
student_module=student_module
)
baseline_count = baseline.count()
self.assertEqual(baseline_count, 3)
# now click "show answer"
self.show_question_answer('p1')
# check that we don't have more state history entries
csmh = StudentModuleHistory.objects.filter(
student_module=student_module
)
current_count = csmh.count()
self.assertEqual(current_count, 3)
def test_grade_with_max_score_cache(self):
"""
Tests that the max score cache is populated after a grading run
and that the results of grading runs before and after the cache
warms are the same.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.look_at_question('p2')
self.assertTrue(
StudentModule.objects.filter(
module_state_key=self.problem_location('p2')
).exists()
)
location_to_cache = unicode(self.problem_location('p2'))
max_scores_cache = MaxScoresCache.create_for_course(self.course)
# problem isn't in the cache
max_scores_cache.fetch_from_remote([location_to_cache])
self.assertIsNone(max_scores_cache.get(location_to_cache))
self.check_grade_percent(0.33)
# problem is in the cache
max_scores_cache.fetch_from_remote([location_to_cache])
self.assertIsNotNone(max_scores_cache.get(location_to_cache))
self.check_grade_percent(0.33)
def test_none_grade(self):
"""
Check grade is 0 to begin with.
"""
self.basic_setup()
self.check_grade_percent(0)
self.assertEqual(self.get_grade_summary()['grade'], None)
def test_b_grade_exact(self):
"""
Check that at exactly the cutoff, the grade is B.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.check_grade_percent(0.33)
self.assertEqual(self.get_grade_summary()['grade'], 'B')
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_MAX_SCORE_CACHE": False})
def test_grade_no_max_score_cache(self):
"""
Tests grading when the max score cache is disabled
"""
self.test_b_grade_exact()
def test_b_grade_above(self):
"""
Check grade between cutoffs.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.submit_question_answer('p2', {'2_1': 'Correct'})
self.check_grade_percent(0.67)
self.assertEqual(self.get_grade_summary()['grade'], 'B')
def test_a_grade(self):
"""
Check that 100 percent completion gets an A
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.submit_question_answer('p2', {'2_1': 'Correct'})
self.submit_question_answer('p3', {'2_1': 'Correct'})
self.check_grade_percent(1.0)
self.assertEqual(self.get_grade_summary()['grade'], 'A')
def test_wrong_answers(self):
"""
Check that answering incorrectly is graded properly.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.submit_question_answer('p2', {'2_1': 'Correct'})
self.submit_question_answer('p3', {'2_1': 'Incorrect'})
self.check_grade_percent(0.67)
self.assertEqual(self.get_grade_summary()['grade'], 'B')
def test_submissions_api_overrides_scores(self):
"""
Check that answering incorrectly is graded properly.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.submit_question_answer('p2', {'2_1': 'Correct'})
self.submit_question_answer('p3', {'2_1': 'Incorrect'})
self.check_grade_percent(0.67)
self.assertEqual(self.get_grade_summary()['grade'], 'B')
# But now we mock out a get_scores call, and watch as it overrides the
# score read from StudentModule and our student gets an A instead.
with patch('submissions.api.get_scores') as mock_get_scores:
mock_get_scores.return_value = {
self.problem_location('p3').to_deprecated_string(): (1, 1)
}
self.check_grade_percent(1.0)
self.assertEqual(self.get_grade_summary()['grade'], 'A')
def test_submissions_api_anonymous_student_id(self):
"""
Check that the submissions API is sent an anonymous student ID.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})<|fim▁hole|>
with patch('submissions.api.get_scores') as mock_get_scores:
mock_get_scores.return_value = {
self.problem_location('p3').to_deprecated_string(): (1, 1)
}
self.get_grade_summary()
# Verify that the submissions API was sent an anonymized student ID
mock_get_scores.assert_called_with(
self.course.id.to_deprecated_string(),
anonymous_id_for_user(self.student_user, self.course.id)
)
def test_weighted_homework(self):
"""
Test that the homework section has proper weight.
"""
self.weighted_setup()
# Get both parts correct
self.submit_question_answer('H1P1', {'2_1': 'Correct', '2_2': 'Correct'})
self.check_grade_percent(0.25)
self.assertEqual(self.earned_hw_scores(), [2.0]) # Order matters
self.assertEqual(self.score_for_hw('homework'), [2.0])
def test_weighted_exam(self):
"""
Test that the exam section has the proper weight.
"""
self.weighted_setup()
self.submit_question_answer('FinalQuestion', {'2_1': 'Correct', '2_2': 'Correct'})
self.check_grade_percent(0.75)
def test_weighted_total(self):
"""
Test that the weighted total adds to 100.
"""
self.weighted_setup()
self.submit_question_answer('H1P1', {'2_1': 'Correct', '2_2': 'Correct'})
self.submit_question_answer('FinalQuestion', {'2_1': 'Correct', '2_2': 'Correct'})
self.check_grade_percent(1.0)
def dropping_homework_stage1(self):
"""
Get half the first homework correct and all of the second
"""
self.submit_question_answer(self.hw1_names[0], {'2_1': 'Correct'})
self.submit_question_answer(self.hw1_names[1], {'2_1': 'Incorrect'})
for name in self.hw2_names:
self.submit_question_answer(name, {'2_1': 'Correct'})
def test_dropping_grades_normally(self):
"""
Test that the dropping policy does not change things before it should.
"""
self.dropping_setup()
self.dropping_homework_stage1()
self.assertEqual(self.score_for_hw('homework1'), [1.0, 0.0])
self.assertEqual(self.score_for_hw('homework2'), [1.0, 1.0])
self.assertEqual(self.earned_hw_scores(), [1.0, 2.0, 0]) # Order matters
self.check_grade_percent(0.75)
def test_dropping_nochange(self):
"""
Tests that grade does not change when making the global homework grade minimum not unique.
"""
self.dropping_setup()
self.dropping_homework_stage1()
self.submit_question_answer(self.hw3_names[0], {'2_1': 'Correct'})
self.assertEqual(self.score_for_hw('homework1'), [1.0, 0.0])
self.assertEqual(self.score_for_hw('homework2'), [1.0, 1.0])
self.assertEqual(self.score_for_hw('homework3'), [1.0, 0.0])
self.assertEqual(self.earned_hw_scores(), [1.0, 2.0, 1.0]) # Order matters
self.check_grade_percent(0.75)
def test_dropping_all_correct(self):
"""
Test that the lowest is dropped for a perfect score.
"""
self.dropping_setup()
self.dropping_homework_stage1()
for name in self.hw3_names:
self.submit_question_answer(name, {'2_1': 'Correct'})
self.check_grade_percent(1.0)
self.assertEqual(self.earned_hw_scores(), [1.0, 2.0, 2.0]) # Order matters
self.assertEqual(self.score_for_hw('homework3'), [1.0, 1.0])
def test_min_grade_credit_requirements_status(self):
"""
Test for credit course. If user passes minimum grade requirement then
status will be updated as satisfied in requirement status table.
"""
self.basic_setup()
self.submit_question_answer('p1', {'2_1': 'Correct'})
self.submit_question_answer('p2', {'2_1': 'Correct'})
# Enable the course for credit
credit_course = CreditCourse.objects.create(
course_key=self.course.id,
enabled=True,
)
# Configure a credit provider for the course
CreditProvider.objects.create(
provider_id="ASU",
enable_integration=True,
provider_url="https://credit.example.com/request",
)
requirements = [{
"namespace": "grade",
"name": "grade",
"display_name": "Grade",
"criteria": {"min_grade": 0.52},
}]
# Add a single credit requirement (final grade)
set_credit_requirements(self.course.id, requirements)
self.get_grade_summary()
req_status = get_credit_requirement_status(self.course.id, self.student_user.username, 'grade', 'grade')
self.assertEqual(req_status[0]["status"], 'satisfied')
@attr('shard_1')
class ProblemWithUploadedFilesTest(TestSubmittingProblems):
"""Tests of problems with uploaded files."""
def setUp(self):
super(ProblemWithUploadedFilesTest, self).setUp()
self.section = self.add_graded_section_to_course('section')
def problem_setup(self, name, files):
"""
Create a CodeResponse problem with files to upload.
"""
xmldata = CodeResponseXMLFactory().build_xml(
allowed_files=files, required_files=files,
)
ItemFactory.create(
parent_location=self.section.location,
category='problem',
display_name=name,
data=xmldata
)
# re-fetch the course from the database so the object is up to date
self.refresh_course()
def test_three_files(self):
# Open the test files, and arrange to close them later.
filenames = "prog1.py prog2.py prog3.py"
fileobjs = [
open(os.path.join(settings.COMMON_TEST_DATA_ROOT, "capa", filename))
for filename in filenames.split()
]
for fileobj in fileobjs:
self.addCleanup(fileobj.close)
self.problem_setup("the_problem", filenames)
with patch('courseware.module_render.XQUEUE_INTERFACE.session') as mock_session:
resp = self.submit_question_answer("the_problem", {'2_1': fileobjs})
self.assertEqual(resp.status_code, 200)
json_resp = json.loads(resp.content)
self.assertEqual(json_resp['success'], "incorrect")
# See how post got called.
name, args, kwargs = mock_session.mock_calls[0]
self.assertEqual(name, "post")
self.assertEqual(len(args), 1)
self.assertTrue(args[0].endswith("/submit/"))
self.assertItemsEqual(kwargs.keys(), ["files", "data"])
self.assertItemsEqual(kwargs['files'].keys(), filenames.split())
@attr('shard_1')
class TestPythonGradedResponse(TestSubmittingProblems):
"""
Check that we can submit a schematic and custom response, and it answers properly.
"""
SCHEMATIC_SCRIPT = dedent("""
# for a schematic response, submission[i] is the json representation
# of the diagram and analysis results for the i-th schematic tag
def get_tran(json,signal):
for element in json:
if element[0] == 'transient':
return element[1].get(signal,[])
return []
def get_value(at,output):
for (t,v) in output:
if at == t: return v
return None
output = get_tran(submission[0],'Z')
okay = True
# output should be 1, 1, 1, 1, 1, 0, 0, 0
if get_value(0.0000004, output) < 2.7: okay = False;
if get_value(0.0000009, output) < 2.7: okay = False;
if get_value(0.0000014, output) < 2.7: okay = False;
if get_value(0.0000019, output) < 2.7: okay = False;
if get_value(0.0000024, output) < 2.7: okay = False;
if get_value(0.0000029, output) > 0.25: okay = False;
if get_value(0.0000034, output) > 0.25: okay = False;
if get_value(0.0000039, output) > 0.25: okay = False;
correct = ['correct' if okay else 'incorrect']""").strip()
SCHEMATIC_CORRECT = json.dumps(
[['transient', {'Z': [
[0.0000004, 2.8],
[0.0000009, 2.8],
[0.0000014, 2.8],
[0.0000019, 2.8],
[0.0000024, 2.8],
[0.0000029, 0.2],
[0.0000034, 0.2],
[0.0000039, 0.2]
]}]]
)
SCHEMATIC_INCORRECT = json.dumps(
[['transient', {'Z': [
[0.0000004, 2.8],
[0.0000009, 0.0], # wrong.
[0.0000014, 2.8],
[0.0000019, 2.8],
[0.0000024, 2.8],
[0.0000029, 0.2],
[0.0000034, 0.2],
[0.0000039, 0.2]
]}]]
)
CUSTOM_RESPONSE_SCRIPT = dedent("""
def test_csv(expect, ans):
# Take out all spaces in expected answer
expect = [i.strip(' ') for i in str(expect).split(',')]
# Take out all spaces in student solution
ans = [i.strip(' ') for i in str(ans).split(',')]
def strip_q(x):
# Strip quotes around strings if students have entered them
stripped_ans = []
for item in x:
if item[0] == "'" and item[-1]=="'":
item = item.strip("'")
elif item[0] == '"' and item[-1] == '"':
item = item.strip('"')
stripped_ans.append(item)
return stripped_ans
return strip_q(expect) == strip_q(ans)""").strip()
CUSTOM_RESPONSE_CORRECT = "0, 1, 2, 3, 4, 5, 'Outside of loop', 6"
CUSTOM_RESPONSE_INCORRECT = "Reading my code I see. I hope you like it :)"
COMPUTED_ANSWER_SCRIPT = dedent("""
if submission[0] == "a shout in the street":
correct = ['correct']
else:
correct = ['incorrect']""").strip()
COMPUTED_ANSWER_CORRECT = "a shout in the street"
COMPUTED_ANSWER_INCORRECT = "because we never let them in"
def setUp(self):
super(TestPythonGradedResponse, self).setUp()
self.section = self.add_graded_section_to_course('section')
self.correct_responses = {}
self.incorrect_responses = {}
def schematic_setup(self, name):
"""
set up an example Circuit_Schematic_Builder problem
"""
script = self.SCHEMATIC_SCRIPT
xmldata = SchematicResponseXMLFactory().build_xml(answer=script)
ItemFactory.create(
parent_location=self.section.location,
category='problem',
boilerplate='circuitschematic.yaml',
display_name=name,
data=xmldata
)
# define the correct and incorrect responses to this problem
self.correct_responses[name] = self.SCHEMATIC_CORRECT
self.incorrect_responses[name] = self.SCHEMATIC_INCORRECT
# re-fetch the course from the database so the object is up to date
self.refresh_course()
def custom_response_setup(self, name):
"""
set up an example custom response problem using a check function
"""
test_csv = self.CUSTOM_RESPONSE_SCRIPT
expect = self.CUSTOM_RESPONSE_CORRECT
cfn_problem_xml = CustomResponseXMLFactory().build_xml(script=test_csv, cfn='test_csv', expect=expect)
ItemFactory.create(
parent_location=self.section.location,
category='problem',
boilerplate='customgrader.yaml',
data=cfn_problem_xml,
display_name=name
)
# define the correct and incorrect responses to this problem
self.correct_responses[name] = expect
self.incorrect_responses[name] = self.CUSTOM_RESPONSE_INCORRECT
# re-fetch the course from the database so the object is up to date
self.refresh_course()
def computed_answer_setup(self, name):
"""
set up an example problem using an answer script'''
"""
script = self.COMPUTED_ANSWER_SCRIPT
computed_xml = CustomResponseXMLFactory().build_xml(answer=script)
ItemFactory.create(
parent_location=self.section.location,
category='problem',
boilerplate='customgrader.yaml',
data=computed_xml,
display_name=name
)
# define the correct and incorrect responses to this problem
self.correct_responses[name] = self.COMPUTED_ANSWER_CORRECT
self.incorrect_responses[name] = self.COMPUTED_ANSWER_INCORRECT
# re-fetch the course from the database so the object is up to date
self.refresh_course()
def _check_correct(self, name):
"""
check that problem named "name" gets evaluated correctly correctly
"""
resp = self.submit_question_answer(name, {'2_1': self.correct_responses[name]})
respdata = json.loads(resp.content)
self.assertEqual(respdata['success'], 'correct')
def _check_incorrect(self, name):
"""
check that problem named "name" gets evaluated incorrectly correctly
"""
resp = self.submit_question_answer(name, {'2_1': self.incorrect_responses[name]})
respdata = json.loads(resp.content)
self.assertEqual(respdata['success'], 'incorrect')
def _check_ireset(self, name):
"""
Check that the problem can be reset
"""
# first, get the question wrong
resp = self.submit_question_answer(name, {'2_1': self.incorrect_responses[name]})
# reset the question
self.reset_question_answer(name)
# then get it right
resp = self.submit_question_answer(name, {'2_1': self.correct_responses[name]})
respdata = json.loads(resp.content)
self.assertEqual(respdata['success'], 'correct')
def test_schematic_correct(self):
name = "schematic_problem"
self.schematic_setup(name)
self._check_correct(name)
def test_schematic_incorrect(self):
name = "schematic_problem"
self.schematic_setup(name)
self._check_incorrect(name)
def test_schematic_reset(self):
name = "schematic_problem"
self.schematic_setup(name)
self._check_ireset(name)
def test_check_function_correct(self):
name = 'cfn_problem'
self.custom_response_setup(name)
self._check_correct(name)
def test_check_function_incorrect(self):
name = 'cfn_problem'
self.custom_response_setup(name)
self._check_incorrect(name)
def test_check_function_reset(self):
name = 'cfn_problem'
self.custom_response_setup(name)
self._check_ireset(name)
def test_computed_correct(self):
name = 'computed_answer'
self.computed_answer_setup(name)
self._check_correct(name)
def test_computed_incorrect(self):
name = 'computed_answer'
self.computed_answer_setup(name)
self._check_incorrect(name)
def test_computed_reset(self):
name = 'computed_answer'
self.computed_answer_setup(name)
self._check_ireset(name)
@attr('shard_1')
class TestAnswerDistributions(TestSubmittingProblems):
"""Check that we can pull answer distributions for problems."""
def setUp(self):
"""Set up a simple course with four problems."""
super(TestAnswerDistributions, self).setUp()
self.homework = self.add_graded_section_to_course('homework')
self.p1_html_id = self.add_dropdown_to_section(self.homework.location, 'p1', 1).location.html_id()
self.p2_html_id = self.add_dropdown_to_section(self.homework.location, 'p2', 1).location.html_id()
self.p3_html_id = self.add_dropdown_to_section(self.homework.location, 'p3', 1).location.html_id()
self.refresh_course()
def test_empty(self):
# Just make sure we can process this without errors.
empty_distribution = grades.answer_distributions(self.course.id)
self.assertFalse(empty_distribution) # should be empty
def test_one_student(self):
# Basic test to make sure we have simple behavior right for a student
# Throw in a non-ASCII answer
self.submit_question_answer('p1', {'2_1': u'ⓤⓝⓘⓒⓞⓓⓔ'})
self.submit_question_answer('p2', {'2_1': 'Correct'})
distributions = grades.answer_distributions(self.course.id)
self.assertEqual(
distributions,
{
('p1', 'p1', '{}_2_1'.format(self.p1_html_id)): {
u'ⓤⓝⓘⓒⓞⓓⓔ': 1
},
('p2', 'p2', '{}_2_1'.format(self.p2_html_id)): {
'Correct': 1
}
}
)
def test_multiple_students(self):
# Our test class is based around making requests for a particular user,
# so we're going to cheat by creating another user and copying and
# modifying StudentModule entries to make them from other users. It's
# a little hacky, but it seemed the simpler way to do this.
self.submit_question_answer('p1', {'2_1': u'Correct'})
self.submit_question_answer('p2', {'2_1': u'Incorrect'})
self.submit_question_answer('p3', {'2_1': u'Correct'})
# Make the above submissions owned by user2
user2 = UserFactory.create()
problems = StudentModule.objects.filter(
course_id=self.course.id,
student=self.student_user
)
for problem in problems:
problem.student_id = user2.id
problem.save()
# Now make more submissions by our original user
self.submit_question_answer('p1', {'2_1': u'Correct'})
self.submit_question_answer('p2', {'2_1': u'Correct'})
self.assertEqual(
grades.answer_distributions(self.course.id),
{
('p1', 'p1', '{}_2_1'.format(self.p1_html_id)): {
'Correct': 2
},
('p2', 'p2', '{}_2_1'.format(self.p2_html_id)): {
'Correct': 1,
'Incorrect': 1
},
('p3', 'p3', '{}_2_1'.format(self.p3_html_id)): {
'Correct': 1
}
}
)
def test_other_data_types(self):
# We'll submit one problem, and then muck with the student_answers
# dict inside its state to try different data types (str, int, float,
# none)
self.submit_question_answer('p1', {'2_1': u'Correct'})
# Now fetch the state entry for that problem.
student_module = StudentModule.objects.get(
course_id=self.course.id,
student=self.student_user
)
for val in ('Correct', True, False, 0, 0.0, 1, 1.0, None):
state = json.loads(student_module.state)
state["student_answers"]['{}_2_1'.format(self.p1_html_id)] = val
student_module.state = json.dumps(state)
student_module.save()
self.assertEqual(
grades.answer_distributions(self.course.id),
{
('p1', 'p1', '{}_2_1'.format(self.p1_html_id)): {
str(val): 1
},
}
)
def test_missing_content(self):
# If there's a StudentModule entry for content that no longer exists,
# we just quietly ignore it (because we can't display a meaningful url
# or name for it).
self.submit_question_answer('p1', {'2_1': 'Incorrect'})
# Now fetch the state entry for that problem and alter it so it points
# to a non-existent problem.
student_module = StudentModule.objects.get(
course_id=self.course.id,
student=self.student_user
)
student_module.module_state_key = student_module.module_state_key.replace(
name=student_module.module_state_key.name + "_fake"
)
student_module.save()
# It should be empty (ignored)
empty_distribution = grades.answer_distributions(self.course.id)
self.assertFalse(empty_distribution) # should be empty
def test_broken_state(self):
# Missing or broken state for a problem should be skipped without
# causing the whole answer_distribution call to explode.
# Submit p1
self.submit_question_answer('p1', {'2_1': u'Correct'})
# Now fetch the StudentModule entry for p1 so we can corrupt its state
prb1 = StudentModule.objects.get(
course_id=self.course.id,
student=self.student_user
)
# Submit p2
self.submit_question_answer('p2', {'2_1': u'Incorrect'})
for new_p1_state in ('{"student_answers": {}}', "invalid json!", None):
prb1.state = new_p1_state
prb1.save()
# p1 won't show up, but p2 should still work
self.assertEqual(
grades.answer_distributions(self.course.id),
{
('p2', 'p2', '{}_2_1'.format(self.p2_html_id)): {
'Incorrect': 1
},
}
)
@attr('shard_1')
class TestConditionalContent(TestSubmittingProblems):
"""
Check that conditional content works correctly with grading.
"""
def setUp(self):
"""
Set up a simple course with a grading policy, a UserPartition, and 2 sections, both graded as "homework".
One section is pre-populated with a problem (with 2 inputs), visible to all students.
The second section is empty. Test cases should add conditional content to it.
"""
super(TestConditionalContent, self).setUp()
self.user_partition_group_0 = 0
self.user_partition_group_1 = 1
self.partition = UserPartition(
0,
'first_partition',
'First Partition',
[
Group(self.user_partition_group_0, 'alpha'),
Group(self.user_partition_group_1, 'beta')
]
)
self.course = CourseFactory.create(
display_name=self.COURSE_NAME,
number=self.COURSE_SLUG,
user_partitions=[self.partition]
)
grading_policy = {
"GRADER": [{
"type": "Homework",
"min_count": 2,
"drop_count": 0,
"short_label": "HW",
"weight": 1.0
}]
}
self.add_grading_policy(grading_policy)
self.homework_all = self.add_graded_section_to_course('homework1')
self.p1_all_html_id = self.add_dropdown_to_section(self.homework_all.location, 'H1P1', 2).location.html_id()
self.homework_conditional = self.add_graded_section_to_course('homework2')
def split_setup(self, user_partition_group):
"""
Setup for tests using split_test module. Creates a split_test instance as a child of self.homework_conditional
with 2 verticals in it, and assigns self.student_user to the specified user_partition_group.
The verticals are returned.
"""
vertical_0_url = self.course.id.make_usage_key("vertical", "split_test_vertical_0")
vertical_1_url = self.course.id.make_usage_key("vertical", "split_test_vertical_1")
group_id_to_child = {}
for index, url in enumerate([vertical_0_url, vertical_1_url]):
group_id_to_child[str(index)] = url
split_test = ItemFactory.create(
parent_location=self.homework_conditional.location,
category="split_test",
display_name="Split test",
user_partition_id='0',
group_id_to_child=group_id_to_child,
)
vertical_0 = ItemFactory.create(
parent_location=split_test.location,
category="vertical",
display_name="Condition 0 vertical",
location=vertical_0_url,
)
vertical_1 = ItemFactory.create(
parent_location=split_test.location,
category="vertical",
display_name="Condition 1 vertical",
location=vertical_1_url,
)
# Now add the student to the specified group.
UserCourseTagFactory(
user=self.student_user,
course_id=self.course.id,
key='xblock.partition_service.partition_{0}'.format(self.partition.id), # pylint: disable=no-member
value=str(user_partition_group)
)
return vertical_0, vertical_1
def split_different_problems_setup(self, user_partition_group):
"""
Setup for the case where the split test instance contains problems for each group
(so both groups do have graded content, though it is different).
Group 0 has 2 problems, worth 1 and 3 points respectively.
Group 1 has 1 problem, worth 1 point.
This method also assigns self.student_user to the specified user_partition_group and
then submits answers for the problems in section 1, which are visible to all students.
The submitted answers give the student 1 point out of a possible 2 points in the section.
"""
vertical_0, vertical_1 = self.split_setup(user_partition_group)
# Group 0 will have 2 problems in the section, worth a total of 4 points.
self.add_dropdown_to_section(vertical_0.location, 'H2P1_GROUP0', 1).location.html_id()
self.add_dropdown_to_section(vertical_0.location, 'H2P2_GROUP0', 3).location.html_id()
# Group 1 will have 1 problem in the section, worth a total of 1 point.
self.add_dropdown_to_section(vertical_1.location, 'H2P1_GROUP1', 1).location.html_id()
# Submit answers for problem in Section 1, which is visible to all students.
self.submit_question_answer('H1P1', {'2_1': 'Correct', '2_2': 'Incorrect'})
def test_split_different_problems_group_0(self):
"""
Tests that users who see different problems in a split_test module instance are graded correctly.
This is the test case for a user in user partition group 0.
"""
self.split_different_problems_setup(self.user_partition_group_0)
self.submit_question_answer('H2P1_GROUP0', {'2_1': 'Correct'})
self.submit_question_answer('H2P2_GROUP0', {'2_1': 'Correct', '2_2': 'Incorrect', '2_3': 'Correct'})
self.assertEqual(self.score_for_hw('homework1'), [1.0])
self.assertEqual(self.score_for_hw('homework2'), [1.0, 2.0])
self.assertEqual(self.earned_hw_scores(), [1.0, 3.0])
# Grade percent is .63. Here is the calculation
homework_1_score = 1.0 / 2
homework_2_score = (1.0 + 2.0) / 4
self.check_grade_percent(round((homework_1_score + homework_2_score) / 2, 2))
def test_split_different_problems_group_1(self):
"""
Tests that users who see different problems in a split_test module instance are graded correctly.
This is the test case for a user in user partition group 1.
"""
self.split_different_problems_setup(self.user_partition_group_1)
self.submit_question_answer('H2P1_GROUP1', {'2_1': 'Correct'})
self.assertEqual(self.score_for_hw('homework1'), [1.0])
self.assertEqual(self.score_for_hw('homework2'), [1.0])
self.assertEqual(self.earned_hw_scores(), [1.0, 1.0])
# Grade percent is .75. Here is the calculation
homework_1_score = 1.0 / 2
homework_2_score = 1.0 / 1
self.check_grade_percent(round((homework_1_score + homework_2_score) / 2, 2))
def split_one_group_no_problems_setup(self, user_partition_group):
"""
Setup for the case where the split test instance contains problems on for one group.
Group 0 has no problems.
Group 1 has 1 problem, worth 1 point.
This method also assigns self.student_user to the specified user_partition_group and
then submits answers for the problems in section 1, which are visible to all students.
The submitted answers give the student 2 points out of a possible 2 points in the section.
"""
[_, vertical_1] = self.split_setup(user_partition_group)
# Group 1 will have 1 problem in the section, worth a total of 1 point.
self.add_dropdown_to_section(vertical_1.location, 'H2P1_GROUP1', 1).location.html_id()
self.submit_question_answer('H1P1', {'2_1': 'Correct'})
def test_split_one_group_no_problems_group_0(self):
"""
Tests what happens when a given group has no problems in it (students receive 0 for that section).
"""
self.split_one_group_no_problems_setup(self.user_partition_group_0)
self.assertEqual(self.score_for_hw('homework1'), [1.0])
self.assertEqual(self.score_for_hw('homework2'), [])
self.assertEqual(self.earned_hw_scores(), [1.0, 0.0])
# Grade percent is .25. Here is the calculation.
homework_1_score = 1.0 / 2
homework_2_score = 0.0
self.check_grade_percent(round((homework_1_score + homework_2_score) / 2, 2))
def test_split_one_group_no_problems_group_1(self):
"""
Verifies students in the group that DOES have a problem receive a score for their problem.
"""
self.split_one_group_no_problems_setup(self.user_partition_group_1)
self.submit_question_answer('H2P1_GROUP1', {'2_1': 'Correct'})
self.assertEqual(self.score_for_hw('homework1'), [1.0])
self.assertEqual(self.score_for_hw('homework2'), [1.0])
self.assertEqual(self.earned_hw_scores(), [1.0, 1.0])
# Grade percent is .75. Here is the calculation.
homework_1_score = 1.0 / 2
homework_2_score = 1.0 / 1
self.check_grade_percent(round((homework_1_score + homework_2_score) / 2, 2))<|fim▁end|> | self.submit_question_answer('p2', {'2_1': 'Correct'})
self.submit_question_answer('p3', {'2_1': 'Incorrect'}) |
<|file_name|>fakeipmitool.py<|end_file_name|><|fim▁begin|>import os
import time
import yaml
import random
import argparse
from rackattack.physical import pikapatch
from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)}
rangesProbabilities = intervalRanges.keys()
rangesProbabilities.sort()
def informFakeConsumersManagerOfReboot(hostname):
rebootsPipe = os.environ["FAKE_REBOOTS_PIPE_PATH"]
fd = os.open(rebootsPipe, os.O_WRONLY)
os.write(fd, "%(hostname)s," % dict(hostname=hostname))
os.close(fd)
def power(mode):
time.sleep(0.02)
if mode == "on":
informFakeConsumersManagerOfReboot(args.H)
print "Chassis Power Control: Up/On"
elif mode == "off":
print "Chassis Power Control: Down/Off"
else:
raise NotImplementedError
def sol(subaction):
if subaction != "activate":
return
possibleOutputLines = ("Yo yo i'm a cool server",
"This server has got swag.",<|fim▁hole|> "Wow this totally looks like a serial log of a linux server",
"asdasd")
while True:
withinBound = random.random()
chosenRangeProbability = \
[rangeProb for rangeProb in rangesProbabilities if rangeProb <= withinBound][-1]
chosenRange = intervalRanges[chosenRangeProbability]
interval = chosenRange[0] + random.random() * (chosenRange[1] - chosenRange[0])
time.sleep(interval)
print random.choice(possibleOutputLines)
def main(args):
useFakeRackConf()
useFakeIPMITool()
if args.I != "lanplus":
assert args.I is None
action = dict(power=power, sol=sol).get(args.action)
action(args.subaction)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-I", default=None, type=str)
parser.add_argument("-H", default=None, type=str)
parser.add_argument("-U", default=None, type=str)
parser.add_argument("-P", default=None, type=str)
parser.add_argument("-R", default=1, type=int)
parser.add_argument("action", default=None, type=str)
parser.add_argument("subaction", default=None, type=str)
args = parser.parse_args()
main(args)<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>r"""
==================================
Constants (:mod:`scipy.constants`)
==================================
.. currentmodule:: scipy.constants
Physical and mathematical constants and units.
Mathematical constants
======================
================ =================================================================
``pi`` Pi
``golden`` Golden ratio
``golden_ratio`` Golden ratio
================ =================================================================
Physical constants
==================
=========================== =================================================================
``c`` speed of light in vacuum
``speed_of_light`` speed of light in vacuum
``mu_0`` the magnetic constant :math:`\mu_0`
``epsilon_0`` the electric constant (vacuum permittivity), :math:`\epsilon_0`
``h`` the Planck constant :math:`h`
``Planck`` the Planck constant :math:`h`
``hbar`` :math:`\hbar = h/(2\pi)`
``G`` Newtonian constant of gravitation
``gravitational_constant`` Newtonian constant of gravitation
``g`` standard acceleration of gravity
``e`` elementary charge
``elementary_charge`` elementary charge
``R`` molar gas constant
``gas_constant`` molar gas constant
``alpha`` fine-structure constant
``fine_structure`` fine-structure constant
``N_A`` Avogadro constant
``Avogadro`` Avogadro constant
``k`` Boltzmann constant
``Boltzmann`` Boltzmann constant
``sigma`` Stefan-Boltzmann constant :math:`\sigma`
``Stefan_Boltzmann`` Stefan-Boltzmann constant :math:`\sigma`
``Wien`` Wien displacement law constant
``Rydberg`` Rydberg constant
``m_e`` electron mass
``electron_mass`` electron mass
``m_p`` proton mass
``proton_mass`` proton mass
``m_n`` neutron mass
``neutron_mass`` neutron mass
=========================== =================================================================
Constants database
------------------
In addition to the above variables, :mod:`scipy.constants` also contains the
2018 CODATA recommended values [CODATA2018]_ database containing more physical
constants.
.. autosummary::
:toctree: generated/
value -- Value in physical_constants indexed by key
unit -- Unit in physical_constants indexed by key
precision -- Relative precision in physical_constants indexed by key
find -- Return list of physical_constant keys with a given string
ConstantWarning -- Constant sought not in newest CODATA data set
.. data:: physical_constants
Dictionary of physical constants, of the format
``physical_constants[name] = (value, unit, uncertainty)``.
Available constants:
====================================================================== ====
%(constant_names)s
====================================================================== ====
Units
=====
SI prefixes
-----------
============ =================================================================
``yotta`` :math:`10^{24}`
``zetta`` :math:`10^{21}`
``exa`` :math:`10^{18}`
``peta`` :math:`10^{15}`
``tera`` :math:`10^{12}`
``giga`` :math:`10^{9}`
``mega`` :math:`10^{6}`
``kilo`` :math:`10^{3}`
``hecto`` :math:`10^{2}`
``deka`` :math:`10^{1}`
``deci`` :math:`10^{-1}`
``centi`` :math:`10^{-2}`
``milli`` :math:`10^{-3}`
``micro`` :math:`10^{-6}`
``nano`` :math:`10^{-9}`
``pico`` :math:`10^{-12}`
``femto`` :math:`10^{-15}`
``atto`` :math:`10^{-18}`
``zepto`` :math:`10^{-21}`
============ =================================================================
Binary prefixes
---------------
============ =================================================================
``kibi`` :math:`2^{10}`
``mebi`` :math:`2^{20}`
``gibi`` :math:`2^{30}`
``tebi`` :math:`2^{40}`
``pebi`` :math:`2^{50}`
``exbi`` :math:`2^{60}`
``zebi`` :math:`2^{70}`
``yobi`` :math:`2^{80}`
============ =================================================================
Mass
----
================= ============================================================
``gram`` :math:`10^{-3}` kg
``metric_ton`` :math:`10^{3}` kg
``grain`` one grain in kg
``lb`` one pound (avoirdupous) in kg
``pound`` one pound (avoirdupous) in kg
``blob`` one inch version of a slug in kg (added in 1.0.0)
``slinch`` one inch version of a slug in kg (added in 1.0.0)
``slug`` one slug in kg (added in 1.0.0)
``oz`` one ounce in kg
``ounce`` one ounce in kg
``stone`` one stone in kg
``grain`` one grain in kg
``long_ton`` one long ton in kg
``short_ton`` one short ton in kg
``troy_ounce`` one Troy ounce in kg
``troy_pound`` one Troy pound in kg
``carat`` one carat in kg
``m_u`` atomic mass constant (in kg)
``u`` atomic mass constant (in kg)
``atomic_mass`` atomic mass constant (in kg)
================= ============================================================
Angle
-----
================= ============================================================
``degree`` degree in radians
``arcmin`` arc minute in radians
``arcminute`` arc minute in radians
``arcsec`` arc second in radians
``arcsecond`` arc second in radians
================= ============================================================
Time
----
================= ============================================================
``minute`` one minute in seconds
``hour`` one hour in seconds
``day`` one day in seconds
``week`` one week in seconds
``year`` one year (365 days) in seconds
``Julian_year`` one Julian year (365.25 days) in seconds
================= ============================================================
Length
------
===================== ============================================================
``inch`` one inch in meters
``foot`` one foot in meters
``yard`` one yard in meters
``mile`` one mile in meters
``mil`` one mil in meters
``pt`` one point in meters
``point`` one point in meters
``survey_foot`` one survey foot in meters
``survey_mile`` one survey mile in meters
``nautical_mile`` one nautical mile in meters
``fermi`` one Fermi in meters
``angstrom`` one Angstrom in meters
``micron`` one micron in meters
``au`` one astronomical unit in meters
``astronomical_unit`` one astronomical unit in meters
``light_year`` one light year in meters
``parsec`` one parsec in meters
===================== ============================================================
<|fim▁hole|>Pressure
--------
================= ============================================================
``atm`` standard atmosphere in pascals
``atmosphere`` standard atmosphere in pascals
``bar`` one bar in pascals
``torr`` one torr (mmHg) in pascals
``mmHg`` one torr (mmHg) in pascals
``psi`` one psi in pascals
================= ============================================================
Area
----
================= ============================================================
``hectare`` one hectare in square meters
``acre`` one acre in square meters
================= ============================================================
Volume
------
=================== ========================================================
``liter`` one liter in cubic meters
``litre`` one liter in cubic meters
``gallon`` one gallon (US) in cubic meters
``gallon_US`` one gallon (US) in cubic meters
``gallon_imp`` one gallon (UK) in cubic meters
``fluid_ounce`` one fluid ounce (US) in cubic meters
``fluid_ounce_US`` one fluid ounce (US) in cubic meters
``fluid_ounce_imp`` one fluid ounce (UK) in cubic meters
``bbl`` one barrel in cubic meters
``barrel`` one barrel in cubic meters
=================== ========================================================
Speed
-----
================== ==========================================================
``kmh`` kilometers per hour in meters per second
``mph`` miles per hour in meters per second
``mach`` one Mach (approx., at 15 C, 1 atm) in meters per second
``speed_of_sound`` one Mach (approx., at 15 C, 1 atm) in meters per second
``knot`` one knot in meters per second
================== ==========================================================
Temperature
-----------
===================== =======================================================
``zero_Celsius`` zero of Celsius scale in Kelvin
``degree_Fahrenheit`` one Fahrenheit (only differences) in Kelvins
===================== =======================================================
.. autosummary::
:toctree: generated/
convert_temperature
Energy
------
==================== =======================================================
``eV`` one electron volt in Joules
``electron_volt`` one electron volt in Joules
``calorie`` one calorie (thermochemical) in Joules
``calorie_th`` one calorie (thermochemical) in Joules
``calorie_IT`` one calorie (International Steam Table calorie, 1956) in Joules
``erg`` one erg in Joules
``Btu`` one British thermal unit (International Steam Table) in Joules
``Btu_IT`` one British thermal unit (International Steam Table) in Joules
``Btu_th`` one British thermal unit (thermochemical) in Joules
``ton_TNT`` one ton of TNT in Joules
==================== =======================================================
Power
-----
==================== =======================================================
``hp`` one horsepower in watts
``horsepower`` one horsepower in watts
==================== =======================================================
Force
-----
==================== =======================================================
``dyn`` one dyne in newtons
``dyne`` one dyne in newtons
``lbf`` one pound force in newtons
``pound_force`` one pound force in newtons
``kgf`` one kilogram force in newtons
``kilogram_force`` one kilogram force in newtons
==================== =======================================================
Optics
------
.. autosummary::
:toctree: generated/
lambda2nu
nu2lambda
References
==========
.. [CODATA2018] CODATA Recommended Values of the Fundamental
Physical Constants 2018.
https://physics.nist.gov/cuu/Constants/
"""
# Modules contributed by BasSw ([email protected])
from .codata import *
from .constants import *
from .codata import _obsolete_constants
_constant_names = [(_k.lower(), _k, _v)
for _k, _v in physical_constants.items()
if _k not in _obsolete_constants]
_constant_names = "\n".join(["``%s``%s %s %s" % (_x[1], " "*(66-len(_x[1])),
_x[2][0], _x[2][1])
for _x in sorted(_constant_names)])
if __doc__:
__doc__ = __doc__ % dict(constant_names=_constant_names)
del _constant_names
__all__ = [s for s in dir() if not s.startswith('_')]
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester<|fim▁end|> | |
<|file_name|>unsafe_rc.rs<|end_file_name|><|fim▁begin|>use std::cell::UnsafeCell;
use std::rc::{Rc, Weak};
use std::ops::{Deref, DerefMut};
use std::hash::{Hash, Hasher};
pub struct UnsafeRc<T> {
value: Rc<UnsafeCell<T>>
}
impl<T> Hash for UnsafeRc<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.ptr().hash(state)
}
}
impl<T> PartialEq for UnsafeRc<T> {
fn eq(&self, other: &UnsafeRc<T>) -> bool {
self.ptr() == other.ptr()
}
}
impl<T> Eq for UnsafeRc<T> {}
impl<T> Clone for UnsafeRc<T> {
fn clone(&self) -> UnsafeRc<T> {
UnsafeRc::from_rc(self.value.clone())
}
}
impl<T> Deref for UnsafeRc<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe {
self.value.get().as_ref().unwrap()
}
}
}
impl<T> DerefMut for UnsafeRc<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe {
self.value.get().as_mut::<'a>().unwrap()
}
}
}
impl<T> UnsafeRc<T> {
pub fn new(v: T) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: Rc::new(UnsafeCell::new(v))
}
}
pub fn from_rc(v: Rc<UnsafeCell<T>>) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: v
}
}
pub fn downgrade(&self) -> UnsafeWeak<T> {
UnsafeWeak::from_weak(self.value.downgrade())
}
pub fn ptr(&self) -> *const T {
self.value.get()
}
}
pub struct UnsafeWeak<T> {
value: Weak<UnsafeCell<T>>
}
impl<T> UnsafeWeak<T> {
pub fn from_weak(r: Weak<UnsafeCell<T>>) -> UnsafeWeak<T> {
UnsafeWeak {
value: r
}
}
pub fn upgrade(&self) -> Option<UnsafeRc<T>> {
self.value.upgrade().map(UnsafeRc::from_rc)
}
}
impl<T> Hash for UnsafeWeak<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.upgrade().hash(state)
}
}
impl<T> PartialEq for UnsafeWeak<T> {
fn eq(&self, other: &UnsafeWeak<T>) -> bool {
self.upgrade() == other.upgrade()
}<|fim▁hole|>}
impl<T> Eq for UnsafeWeak<T> {}<|fim▁end|> |
Subsets and Splits