repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
Aryan98/lcprediction
|
test_luna_props_scan_dsb.py
|
import sys
import lasagne as nn
import numpy as np
import theano
import os
import pathfinder
import utils
from configuration import config, set_configuration
from utils_plots import plot_slice_3d_3
import theano.tensor as T
import utils_lung
import blobs_detection
import logger
from collections import defaultdict
theano.config.warn_float64 = 'raise'
if len(sys.argv) < 2:
sys.exit("Usage: test_luna_props_scan.py <configuration_name>")
config_name = sys.argv[1]
set_configuration('configs_luna_props_scan', config_name)
# predictions path
predictions_dir = utils.get_dir_path('model-predictions', pathfinder.METADATA_PATH)
outputs_path = predictions_dir + '/%s' % config_name
utils.auto_make_dir(outputs_path)
# logs
logs_dir = utils.get_dir_path('logs', pathfinder.METADATA_PATH)
sys.stdout = logger.Logger(logs_dir + '/%s.log' % config_name)
sys.stderr = sys.stdout
# builds model and sets its parameters
model = config().build_model()
x_shared = nn.utils.shared_empty(dim=len(model.l_in.shape))
givens_valid = {}
givens_valid[model.l_in.input_var] = x_shared
get_predictions_patch = theano.function([],
nn.layers.get_output(model.l_out, deterministic=True),
givens=givens_valid,
on_unused_input='ignore')
data_iterator = config().data_iterator
#existing_preds = [f.rsplit('.') for f in os.listdir(outputs_path)]
#print existing_preds
print
print 'Data'
print 'n samples: %d' % data_iterator.nsamples
prev_pid = None
candidates = []
patients_count = 0
max_malignancy = 0.
for n, (x, candidate_zyxd, id) in enumerate(data_iterator.generate()):
pid = id[0]
if pid != prev_pid and prev_pid is not None:
print patients_count, prev_pid, len(candidates)
candidates = np.asarray(candidates)
utils.save_pkl(candidates, outputs_path + '/%s.pkl' % prev_pid)
patients_count += 1
candidates = []
#print 'x.shape', x.shape
x_shared.set_value(x)
predictions = get_predictions_patch()
#print 'predictions.shape', predictions.shape
#print 'candidate_zyxd', candidate_zyxd.shape
candidate_zyxd_pred = np.append(candidate_zyxd, [predictions])
#print 'candidate_zyxd_pred', candidate_zyxd_pred
candidates.append(candidate_zyxd_pred)
prev_pid = pid
# save the last one
print patients_count, prev_pid, len(candidates)
candidates = np.asarray(candidates)
utils.save_pkl(candidates, outputs_path + '/%s.pkl' % prev_pid)
|
greensnow25/javaaz
|
chapter4/3.LSP/src/main/java/com/greensnow25/foods/Fruit.java
|
<reponame>greensnow25/javaaz
package com.greensnow25.foods;
/**
* public class Fruit.
*
* @author greensnow25.
* @version 1.
* @since 27.03.2017.
*/
public class Fruit extends Food {
/**
* class constructor.
*
* @param name name.
* @param expaireDate date.
* @param createDate date.
* @param prise prise.
* @param discount discount.
*/
public Fruit(String name, String createDate,String expaireDate, String prise, String discount) {
super(name, createDate,expaireDate, prise, discount);
}
}
|
zoewangg/aws-sdk-java
|
aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/internal/netty/handler/PutMediaHandlerInitializer.java
|
<reponame>zoewangg/aws-sdk-java
/*
* Copyright 2012-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisvideo.internal.netty.handler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Initializer for PutMedia pipeline.
*/
public class PutMediaHandlerInitializer extends ChannelInitializer<Channel> {
private static final Log log = LogFactory.getLog(PutMediaHandlerInitializer.class);
private final SslContext sslContext;
/**
* Additional pipeline handlers to process PutMedia response and ack events. See {@link DeliverAckHandler}.
*/
private final List<ChannelHandler> handlers;
private final String host;
private final int port;
public PutMediaHandlerInitializer(SslContext sslContext, List<ChannelHandler> handlers, String host, int port) {
this.sslContext = sslContext;
this.handlers = new ArrayList<ChannelHandler>(handlers);
this.host = host;
this.port = port;
}
@Override
public void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
if (log.isDebugEnabled()) {
pipeline.addLast(new LoggingHandler());
}
if (sslContext != null) {
SslHandler sslHandler = sslContext.newHandler(channel.alloc(), host, port);
configureSslEngine(sslHandler.engine());
pipeline.addLast("ssl", sslHandler);
}
pipeline.addLast("http-codec", new HttpClientCodec());
for (ChannelHandler handler : handlers) {
pipeline.addLast(handler);
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
}
/**
* Enable HostName verification.
*
* See https://netty.io/4.0/api/io/netty/handler/ssl/SslContext.html#newHandler-io.netty.buffer.ByteBufAllocator-java.lang
* .String-int-
*
* @param sslEngine the sslEngine to configure
*/
private void configureSslEngine(SSLEngine sslEngine) {
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
}
|
lihongli528628/yishu
|
medtree/medtree/Groups/Common/CycleScrollView.h
|
//
// CycleScrollView.h
// PagedScrollView
//
// Created by 陈政 on 14-1-23.
// Copyright (c) 2014年 Apple Inc. All rights reserved.
// 循环滚动
#import <UIKit/UIKit.h>
@protocol CycleScrollViewDelegate <NSObject>
- (void)setSelectIndex:(NSInteger)idx;
- (void)setTapIndex:(NSInteger)idx;
@end
@interface CycleScrollView : UIView
{
UIScrollView *scroll;
NSMutableArray *viewArray;
}
/**
* 初始化
*
* @param frame frame
* @param animationDuration 自动滚动的间隔时长。如果<=0,不自动滚动。
*
* @return instance
*/
- (id)initWithFrame:(CGRect)frame animationDuration:(NSTimeInterval)animationDuration;
@property (nonatomic, assign) id<CycleScrollViewDelegate> parent;
- (void)removeTimer;
- (void)addTimer;
- (void)clearScrollDelegate;
- (void)addScrollDelegate;
- (void)setViewArray:(NSArray *)array;
/** 显示水平滚动条 */
@property (nonatomic, assign) BOOL showsHorizontalScrollIndicator;
/**
数据源:获取总的page个数
**/
@property (nonatomic , copy) NSInteger (^totalPagesCount)(void);
/**
数据源:获取第pageIndex个位置的contentView
**/
@property (nonatomic , copy) UIView *(^fetchContentViewAtIndex)(NSInteger pageIndex);
/**
当点击的时候,执行的block
**/
@property (nonatomic , copy) void (^TapActionBlock)(NSInteger pageIndex);
/**
数据源:获取的page
**/
@property (nonatomic , copy) void (^PageAtIndexBlock)(NSInteger pageAtIndex);
@end
|
jerrykrinock/IupCocoaTouch
|
src/gtk/iupgtk_label.c
|
<reponame>jerrykrinock/IupCocoaTouch
/** \file
* \brief Label Control
*
* See Copyright Notice in "iup.h"
*/
#include <gtk/gtk.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <stdarg.h>
#include "iup.h"
#include "iupcbs.h"
#include "iup_object.h"
#include "iup_layout.h"
#include "iup_attrib.h"
#include "iup_str.h"
#include "iup_image.h"
#include "iup_label.h"
#include "iup_drv.h"
#include "iup_image.h"
#include "iup_focus.h"
#include "iupgtk_drv.h"
static int gtkLabelSetBgColorAttrib(Ihandle* ih, const char* value)
{
GtkWidget* eventbox = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT");
unsigned char r, g, b;
/* ignore given value, must use only from parent for the scrollbars */
char* parent_value = iupBaseNativeParentGetBgColor(ih);
if (iupStrToRGB(parent_value, &r, &g, &b))
iupgtkSetBgColor(eventbox, r, g, b);
(void)value;
return iupdrvBaseSetBgColorAttrib(ih, parent_value);
}
static int gtkLabelSetTitleAttrib(Ihandle* ih, const char* value)
{
if (ih->data->type == IUP_LABEL_TEXT)
{
GtkLabel* label = (GtkLabel*)ih->handle;
if (iupgtkSetMnemonicTitle(ih, label, value))
{
Ihandle* next = iupFocusNextInteractive(ih);
if (next)
{
if (next->handle)
gtk_label_set_mnemonic_widget(label, next->handle);
else
iupAttribSet(next, "_IUPGTK_LABELMNEMONIC", (char*)label); /* used by iupgtkUpdateMnemonic */
}
}
return 1;
}
return 0;
}
static int gtkLabelSetWordWrapAttrib(Ihandle* ih, const char* value)
{
if (ih->data->type == IUP_LABEL_TEXT)
{
GtkLabel* label = (GtkLabel*)ih->handle;
if (iupStrBoolean(value))
gtk_label_set_line_wrap(label, TRUE);
else
gtk_label_set_line_wrap(label, FALSE);
return 1;
}
return 0;
}
static int gtkLabelSetEllipsisAttrib(Ihandle* ih, const char* value)
{
if (ih->data->type == IUP_LABEL_TEXT)
{
#if GTK_CHECK_VERSION(2, 6, 0)
GtkLabel* label = (GtkLabel*)ih->handle;
if (iupStrBoolean(value))
gtk_label_set_ellipsize(label, PANGO_ELLIPSIZE_END);
else
gtk_label_set_ellipsize(label, PANGO_ELLIPSIZE_NONE);
#endif
return 1;
}
return 0;
}
static int gtkLabelSetAlignmentAttrib(Ihandle* ih, const char* value)
{
if (ih->data->type != IUP_LABEL_SEP_HORIZ && ih->data->type != IUP_LABEL_SEP_VERT)
{
GtkMisc* misc = (GtkMisc*)ih->handle;
PangoAlignment alignment;
float xalign, yalign;
char value1[30], value2[30];
iupStrToStrStr(value, value1, value2, ':');
if (iupStrEqualNoCase(value1, "ARIGHT"))
{
xalign = 1.0f;
alignment = PANGO_ALIGN_RIGHT;
}
else if (iupStrEqualNoCase(value1, "ACENTER"))
{
xalign = 0.5f;
alignment = PANGO_ALIGN_CENTER;
}
else /* "ALEFT" */
{
xalign = 0;
alignment = PANGO_ALIGN_LEFT;
}
if (iupStrEqualNoCase(value2, "ABOTTOM"))
yalign = 1.0f;
else if (iupStrEqualNoCase(value2, "ATOP"))
yalign = 0;
else /* ACENTER (default) */
yalign = 0.5f;
gtk_misc_set_alignment(misc, xalign, yalign);
if (ih->data->type == IUP_LABEL_TEXT)
pango_layout_set_alignment(gtk_label_get_layout((GtkLabel*)ih->handle), alignment);
return 1;
}
else
return 0;
}
static int gtkLabelSetPaddingAttrib(Ihandle* ih, const char* value)
{
iupStrToIntInt(value, &ih->data->horiz_padding, &ih->data->vert_padding, 'x');
if (ih->handle && ih->data->type != IUP_LABEL_SEP_HORIZ && ih->data->type != IUP_LABEL_SEP_VERT)
{
GtkMisc* misc = (GtkMisc*)ih->handle;
gtk_misc_set_padding(misc, ih->data->horiz_padding, ih->data->vert_padding);
return 0;
}
else
return 1; /* store until not mapped, when mapped will be set again */
}
static void gtkLabelSetPixbuf(Ihandle* ih, const char* name, int make_inactive)
{
GtkImage* image_label = (GtkImage*)ih->handle;
if (name)
{
GdkPixbuf* pixbuf = iupImageGetImage(name, ih, make_inactive);
GdkPixbuf* old_pixbuf = gtk_image_get_pixbuf(image_label);
if (pixbuf != old_pixbuf)
gtk_image_set_from_pixbuf(image_label, pixbuf);
return;
}
/* if not defined */
#if GTK_CHECK_VERSION(2, 8, 0)
gtk_image_clear(image_label);
#endif
}
static int gtkLabelSetImageAttrib(Ihandle* ih, const char* value)
{
if (ih->data->type == IUP_LABEL_IMAGE)
{
if (iupdrvIsActive(ih))
gtkLabelSetPixbuf(ih, value, 0);
else
{
if (!iupAttribGet(ih, "IMINACTIVE"))
{
/* if not active and IMINACTIVE is not defined
then automaticaly create one based on IMAGE */
gtkLabelSetPixbuf(ih, value, 1); /* make_inactive */
}
}
return 1;
}
else
return 0;
}
static int gtkLabelSetImInactiveAttrib(Ihandle* ih, const char* value)
{
if (ih->data->type == IUP_LABEL_IMAGE)
{
if (!iupdrvIsActive(ih))
{
if (value)
gtkLabelSetPixbuf(ih, value, 0);
else
{
/* if not defined then automaticaly create one based on IMAGE */
char* name = iupAttribGet(ih, "IMAGE");
gtkLabelSetPixbuf(ih, name, 1); /* make_inactive */
}
}
return 1;
}
else
return 0;
}
static int gtkLabelSetActiveAttrib(Ihandle* ih, const char* value)
{
/* update the inactive image if necessary */
if (ih->data->type == IUP_LABEL_IMAGE)
{
if (!iupStrBoolean(value))
{
char* name = iupAttribGet(ih, "IMINACTIVE");
if (name)
gtkLabelSetPixbuf(ih, name, 0);
else
{
/* if not defined then automaticaly create one based on IMAGE */
name = iupAttribGet(ih, "IMAGE");
gtkLabelSetPixbuf(ih, name, 1); /* make_inactive */
}
}
else
{
/* must restore the normal image */
char* name = iupAttribGet(ih, "IMAGE");
gtkLabelSetPixbuf(ih, name, 0);
}
}
return iupBaseSetActiveAttrib(ih, value);
}
static int gtkLabelMapMethod(Ihandle* ih)
{
char* value;
GtkWidget *label;
value = iupAttribGet(ih, "SEPARATOR");
if (value)
{
if (iupStrEqualNoCase(value, "HORIZONTAL"))
{
ih->data->type = IUP_LABEL_SEP_HORIZ;
#if GTK_CHECK_VERSION(3, 0, 0)
label = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
#else
label = gtk_hseparator_new();
#endif
}
else /* "VERTICAL" */
{
ih->data->type = IUP_LABEL_SEP_VERT;
#if GTK_CHECK_VERSION(3, 0, 0)
label = gtk_separator_new(GTK_ORIENTATION_VERTICAL);
#else
label = gtk_vseparator_new();
#endif
}
}
else
{
value = iupAttribGet(ih, "IMAGE");
if (value)
{
ih->data->type = IUP_LABEL_IMAGE;
label = gtk_image_new();
}
else
{
ih->data->type = IUP_LABEL_TEXT;
label = gtk_label_new(NULL);
}
}
if (!label)
return IUP_ERROR;
ih->handle = label;
/* interactive callbacks will not work without the eventbox */
{
GtkWidget *box = gtk_event_box_new();
gtk_container_add((GtkContainer*)box, ih->handle);
iupAttribSet(ih, "_IUP_EXTRAPARENT", (char*)box);
gtk_widget_add_events(box,
GDK_POINTER_MOTION_MASK| GDK_POINTER_MOTION_HINT_MASK|
GDK_BUTTON_PRESS_MASK|GDK_BUTTON_RELEASE_MASK|GDK_BUTTON_MOTION_MASK|
GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK);
g_signal_connect(G_OBJECT(box), "button-press-event", G_CALLBACK(iupgtkButtonEvent), ih);
g_signal_connect(G_OBJECT(box), "button-release-event",G_CALLBACK(iupgtkButtonEvent), ih);
g_signal_connect(G_OBJECT(box), "enter-notify-event", G_CALLBACK(iupgtkEnterLeaveEvent), ih);
g_signal_connect(G_OBJECT(box), "leave-notify-event", G_CALLBACK(iupgtkEnterLeaveEvent), ih);
}
/* add to the parent, all GTK controls must call this. */
iupgtkAddToParent(ih);
gtk_widget_realize(label);
/* configure for DRAG&DROP of files */
if (IupGetCallback(ih, "DROPFILES_CB"))
iupAttribSet(ih, "DROPFILESTARGET", "YES");
return IUP_NOERROR;
}
void iupdrvLabelInitClass(Iclass* ic)
{
/* Driver Dependent Class functions */
ic->Map = gtkLabelMapMethod;
/* Driver Dependent Attribute functions */
/* Overwrite Visual */
iupClassRegisterAttribute(ic, "ACTIVE", iupBaseGetActiveAttrib, gtkLabelSetActiveAttrib, IUPAF_SAMEASSYSTEM, "YES", IUPAF_DEFAULT);
/* Visual */
iupClassRegisterAttribute(ic, "BGCOLOR", iupBaseNativeParentGetBgColorAttrib, gtkLabelSetBgColorAttrib, IUPAF_SAMEASSYSTEM, "DLGBGCOLOR", IUPAF_DEFAULT);
/* Special */
iupClassRegisterAttribute(ic, "FGCOLOR", NULL, iupdrvBaseSetFgColorAttrib, IUPAF_SAMEASSYSTEM, "DLGFGCOLOR", IUPAF_DEFAULT);
iupClassRegisterAttribute(ic, "TITLE", NULL, gtkLabelSetTitleAttrib, NULL, NULL, IUPAF_NO_DEFAULTVALUE|IUPAF_NO_INHERIT);
/* IupLabel only */
iupClassRegisterAttribute(ic, "ALIGNMENT", NULL, gtkLabelSetAlignmentAttrib, "ALEFT:ACENTER", NULL, IUPAF_NO_INHERIT); /* force new default value */
iupClassRegisterAttribute(ic, "IMAGE", NULL, gtkLabelSetImageAttrib, NULL, NULL, IUPAF_IHANDLENAME|IUPAF_NO_DEFAULTVALUE|IUPAF_NO_INHERIT);
iupClassRegisterAttribute(ic, "PADDING", iupLabelGetPaddingAttrib, gtkLabelSetPaddingAttrib, IUPAF_SAMEASSYSTEM, "0x0", IUPAF_NOT_MAPPED);
/* IupLabel GTK and Motif only */
iupClassRegisterAttribute(ic, "IMINACTIVE", NULL, gtkLabelSetImInactiveAttrib, NULL, NULL, IUPAF_IHANDLENAME|IUPAF_NO_DEFAULTVALUE|IUPAF_NO_INHERIT);
/* IupLabel Windows and GTK only */
iupClassRegisterAttribute(ic, "WORDWRAP", NULL, gtkLabelSetWordWrapAttrib, NULL, NULL, IUPAF_DEFAULT);
iupClassRegisterAttribute(ic, "ELLIPSIS", NULL, gtkLabelSetEllipsisAttrib, NULL, NULL, IUPAF_DEFAULT);
/* IupLabel GTK only */
iupClassRegisterAttribute(ic, "MARKUP", NULL, NULL, NULL, NULL, IUPAF_DEFAULT);
}
|
joklawitter/BookDrawingAlgorithms
|
src/algorithms/heuristics/vertexorder/SmallestDegreeDFSAlgorithm.java
|
<filename>src/algorithms/heuristics/vertexorder/SmallestDegreeDFSAlgorithm.java
package algorithms.heuristics.vertexorder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
import model.Embedding;
import model.Graph;
import model.Vertex;
import algorithms.base.PartialVertexOrderAlgorithm;
/**
* Implementation of the DFS vertex ordering algorithm. The graph is traversed in depth first order
* and vertices are ordered accordingly. The root vertex is chosen by degree (smallest) as is the order
* in which the neighbours of the current vertex are visited.
*
* @author <NAME>, (based on Michael Wegner's RDFS)
*/
public class SmallestDegreeDFSAlgorithm implements PartialVertexOrderAlgorithm {
@Override
public void computeVertexOrder(Embedding embedding) {
computePartialVertexOrder(embedding, 0, embedding.getGraph().getN());
}
@Override
public void computePartialVertexOrder(Embedding embedding, int keepUpToPosition) {
computePartialVertexOrder(embedding, keepUpToPosition+1, embedding.getGraph().getN());
}
@Override
public void computePartialVertexOrder(Embedding embedding, int begin, int end) {
Graph g = embedding.getGraph();
int[] vertexOnSpine = embedding.getVertexOnSpineArray();
int[] spine = embedding.getSpine();
if ((begin + 1 == end) || (begin == end)) {
return; // only one element to order => nothing to do
} else if (begin < end) {
// we only change the order of vertices spine[begin]..spine[end-1]
for (int i = begin; i < end; ++i) {
vertexOnSpine[spine[i]] = -1;
}
} else {
// we only change the order of vertices spine[begin]..spine[n-1]
for (int i = begin; i < g.getN(); ++i) {
vertexOnSpine[spine[i]] = -1;
}
// and spine[0]..spine[end-1]
for (int i = 0; i < end; ++i) {
vertexOnSpine[spine[i]] = -1;
}
}
int rootPosition = findPositionOfVertexWithSmallestDegree(embedding, begin, end);
int rootIndex = spine[rootPosition];
Stack<Integer> stack = new Stack<Integer>();
boolean[] visited = new boolean[embedding.getN()];
int idx = begin;
// continue if not reached end / still after begin without flip
while ((idx < end) || (end < begin && begin <= idx)) {
// graph may not be connected -> find not visited vertex
while (vertexOnSpine[rootIndex] != -1) {
rootPosition = (rootPosition + 1) % embedding.getN();
rootIndex = spine[rootPosition];
}
// order connected component
stack.push(rootIndex);
while (!stack.empty()) {
int v = stack.pop();
if (!visited[v]) {
visited[v] = true;
// only set new index if vertex belongs to the set of vertices to order
if (vertexOnSpine[v] == -1) {
vertexOnSpine[v] = idx++;
if (begin > end) {
idx = idx % g.getN();
}
}
ArrayList<Vertex> neighbors = new ArrayList<Vertex>();
for (Vertex u : g.getVertexByIndex(v).getNeighbors()) {
if (!visited[u.getIndex()]) {
neighbors.add(u);
}
}
// sorts by degree descending, thus y and x are swapped
Collections.sort(neighbors, (Vertex x, Vertex y) -> Integer.compare(y.getDegree(), x.getDegree()));
for (Vertex u : neighbors) {
stack.push(u.getIndex());
}
}
}
}
embedding.setVertexOnSpine(vertexOnSpine);
}
private int findPositionOfVertexWithSmallestDegree(Embedding embedding, int begin, int end) {
Graph g = embedding.getGraph();
int[] spine = embedding.getSpine();
int smallestPosition = begin;
int smallestDegree = Integer.MAX_VALUE;
if (begin < end) {
for (int i = begin; i < end; i++) {
int currentDegree = g.getDegreeOf(spine[i]);
if (currentDegree < smallestDegree) {
smallestDegree = currentDegree;
smallestPosition = i;
}
}
} else {
for (int i = begin; i < embedding.getN(); i++) {
int currentDegree = g.getDegreeOf(spine[i]);
if (currentDegree < smallestDegree) {
smallestDegree = currentDegree;
smallestPosition = i;
}
}
for (int i = 0; i < end; i++) {
int currentDegree = g.getDegreeOf(spine[i]);
if (currentDegree < smallestDegree) {
smallestDegree = currentDegree;
smallestPosition = i;
}
}
}
return smallestPosition;
}
}
|
loggar/js
|
js-es/url/url.4.properties.js
|
// construct a url
const url = new URL("http://sample.domain.com");
url.pathname = "/blog/javascript-url-object";
url.hash = "#url-properties";
// update `protocol` property
url.protocol = "https:";
console.log(url.toString()); // https://sample.domain.com/blog/javascript-url-object#url-propertie
|
myardhs/react-ionicons
|
src/Briefcase.js
|
import React from 'react'
import PropTypes from 'prop-types'
import SvgContainer from './SvgContainer'
const Briefcase = props => {
return (
<SvgContainer
height={props.height}
width={props.width}
color={props.color}
onClick={props.onClick}
rotate={props.rotate ? 1 : 0}
shake={props.shake ? 1 : 0}
beat={props.beat ? 1 : 0}
className={props.className}
>
<svg style={props.style} className={props.cssClasses} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">{props.title ? <title>{props.title}</title> : ''}<path d="M336 80H176a16 16 0 00-16 16v16h192V96a16 16 0 00-16-16z" fill="none"/><path d="M496 176a64.07 64.07 0 00-64-64h-48V96a48.05 48.05 0 00-48-48H176a48.05 48.05 0 00-48 48v16H80a64.07 64.07 0 00-64 64v48h480zm-144-64H160V96a16 16 0 0116-16h160a16 16 0 0116 16zM336 264a24 24 0 01-24 24H200a24 24 0 01-24-24v-4a4 4 0 00-4-4H16v144a64 64 0 0064 64h352a64 64 0 0064-64V256H340a4 4 0 00-4 4z"/></svg>
</SvgContainer>
)
}
Briefcase.defaultProps = {
// style
style: {},
color: '#000000',
height: '22px',
width: '22px',
cssClasses: '',
title: '',
// animation
shake: false,
beat: false,
rotate: false,
}
Briefcase.propTypes = {
// style
style: PropTypes.object,
color: PropTypes.string,
height: PropTypes.string,
width: PropTypes.string,
cssClasses: PropTypes.string,
title: PropTypes.string,
// animation
shake: PropTypes.bool,
beat: PropTypes.bool,
rotate: PropTypes.bool,
// functions
onClick: PropTypes.func
}
export default Briefcase
|
nawawi/zephir
|
ext/stub/geometry.zep.h
|
extern zend_class_entry *stub_geometry_ce;
ZEPHIR_INIT_CLASS(Stub_Geometry);
PHP_METHOD(Stub_Geometry, run);
PHP_METHOD(Stub_Geometry, runOptimize);
PHP_METHOD(Stub_Geometry, distanceStatic);
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stub_geometry_run, 0, 2, IS_VOID, 0)
ZEND_ARG_ARRAY_INFO(0, list, 0)
ZEND_ARG_TYPE_INFO(0, count, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stub_geometry_runoptimize, 0, 2, IS_VOID, 0)
ZEND_ARG_ARRAY_INFO(0, list, 0)
ZEND_ARG_TYPE_INFO(0, count, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stub_geometry_distancestatic, 0, 4, IS_DOUBLE, 0)
ZEND_ARG_TYPE_INFO(0, x1, IS_DOUBLE, 0)
ZEND_ARG_TYPE_INFO(0, y1, IS_DOUBLE, 0)
ZEND_ARG_TYPE_INFO(0, x2, IS_DOUBLE, 0)
ZEND_ARG_TYPE_INFO(0, y2, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(stub_geometry_method_entry) {
PHP_ME(Stub_Geometry, run, arginfo_stub_geometry_run, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Stub_Geometry, runOptimize, arginfo_stub_geometry_runoptimize, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Stub_Geometry, distanceStatic, arginfo_stub_geometry_distancestatic, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_FE_END
};
|
manageacloud/thevpncompany
|
src/main/java/com/manageacloud/vpn/interceptor/VPNToolInterceptor.java
|
/*
* Copyright (c) 2020 TheVPNCompany.com.au
*/
package com.manageacloud.vpn.interceptor;
import com.manageacloud.vpn.utils.CoreUtils;
import com.manageacloud.vpn.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class VPNToolInterceptor extends HandlerInterceptorAdapter {
private static Logger log = LoggerFactory.getLogger(VPNToolInterceptor.class);
@Override
public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// set the cookie string
CoreUtils.setCookieIfEmpty();
return true;
}
@Override
public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if ( modelAndView != null ) {
WebUtils.addDefaultVars(request, modelAndView);
}
}
}
|
christof337/ACSEL
|
matrice_grad_CADNA/lib/SAM_unstab.cpp
|
<filename>matrice_grad_CADNA/lib/SAM_unstab.cpp
/*-----------------------------------------------------------------------
Copyright 2013 <NAME>, <NAME>, <NAME>, <NAME>
This file is part of SAM.
SAM is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
SAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with SAM. If not, see
<http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------*/
///////////////////////////////////////////////////
//
// SAM SOFTWARE
//
///////////////////////////////////////////////////
// Last Modifications
//
//
///////////////////////////////////////////////////
#include "SAM.h"
#include "SAM_private.h"
extern int nbre_trace_SAM;
extern int nbre_stability_count;
int _SAM_max_instability;
int _SAM_instability_detected;
extern FILE *unit_stability;
//
//
//=====================================================
// "INSTABILITY" function
//=====================================================
//
//
//****f* SAM_unstab/instability
// NAME
// instability
//
// SYNOPSIS
// void instability(unsigned long *unstab)
// FUNCTION
// It is an internal subroutine of the SAM library. It manages
// the different kinds of instabilities detected by SAM.
// INPUTS
// An unsigned long integer which indicates the kind of instability
// that has been detected.
// RESULT
//
// SEE ALSO
//*****
// You can use this space for remarks that should not be included
// in the documentation.
// EXAMPLE
//
//
// NOTES
// This function is called exclusively when an instability has been
// detected. Therefore, under a symbolic debugger like gdb, one has
// only to put a breakoint at this function to stop the run each
// time an instability occurs.
//
// BUGS
//
//
//
//
// /
void instability(unsigned long *unstab)
{
(*unstab)++;
_SAM_instability_detected++;
if (_SAM_max_instability<0) return;
if (_SAM_instability_detected==_SAM_max_instability) {
_SAM_div_tag=0;
_SAM_mul_tag=0;
_SAM_math_tag=0;
_SAM_intrinsic_tag=0;
_SAM_cancel_tag=0;
_SAM_branching_tag=0;
_SAM_div_change=1;
_SAM_mul_change=1;
_SAM_power_change=1;
_SAM_branching_change=1;
_SAM_cancel_change=1;
_SAM_intrinsic_change=1;
_SAM_math_change=1;
_SAM_max_instability=-2;
}
}
|
ekzemplaro/data_base_language
|
ftp/ruby/create/ftp_create.rb
|
#! /usr/bin/ruby
# -*- encoding: utf-8 -*-
#
# ftp_create.rb
#
# Feb/25/2013
#
require 'rubygems'
require 'json'
#
load '/var/www/data_base/common/ruby_common/text_manipulate.rb'
load '/var/www/data_base/common/ruby_common/net_manipulate.rb'
#
#
# ---------------------------------------------------------------------
def prepare_data_proc ()
dict_aa={}
dict_aa=dict_append_proc(dict_aa,"t0361","盛岡",31587,"2006-11-12")
dict_aa=dict_append_proc(dict_aa,"t0362","久慈",23864,"2006-8-21")
dict_aa=dict_append_proc(dict_aa,"t0363","二戸",45917,"2006-4-8")
dict_aa=dict_append_proc(dict_aa,"t0364","宮古",78623,"2006-2-22")
dict_aa=dict_append_proc(dict_aa,"t0365","遠野",41589,"2006-5-11")
dict_aa=dict_append_proc(dict_aa,"t0366","八幡平",25915,"2006-9-17")
dict_aa=dict_append_proc(dict_aa,"t0367","大船渡",36972,"2006-8-18")
dict_aa=dict_append_proc(dict_aa,"t0368","一関",73921,"2006-8-15")
dict_aa=dict_append_proc(dict_aa,"t0369","花巻",86123,"2006-10-21")
end
# ---------------------------------------------------------------------
puts "*** 開始 ***"
#
dict_aa=prepare_data_proc()
#
json_str = JSON.pretty_generate(dict_aa)
#
host='host_dbase'
user='scott'
pass='<PASSWORD>'
target_file='city/iwate.json'
ftp_put_proc(host,user,pass,target_file,json_str)
#
puts "*** 終了 ***"
#
# --------------------------------------------------------------------------
|
huashijiacuo/codeclone
|
gumtreetest/core/src/test/java/com/github/gumtreediff/test/TestGumtreeMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2016 <NAME> <<EMAIL>>
* Copyright 2011-2016 <NAME> <<EMAIL>>
*/
package com.github.gumtreediff.test;
import com.github.gumtreediff.matchers.CompositeMatchers;
import com.github.gumtreediff.matchers.MappingStore;
import com.github.gumtreediff.matchers.Matcher;
import com.github.gumtreediff.matchers.heuristic.gt.AbstractBottomUpMatcher;
import com.github.gumtreediff.matchers.heuristic.gt.GreedySubtreeMatcher;
import com.github.gumtreediff.utils.Pair;
import com.github.gumtreediff.tree.TreeContext;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestGumtreeMatcher {
@Test
public void testMinHeightThreshold() {
Pair<TreeContext, TreeContext> trees = TreeLoader.getGumtreePair();
GreedySubtreeMatcher.MIN_HEIGHT = 0;
AbstractBottomUpMatcher.SIZE_THRESHOLD = 0;
Matcher m = new CompositeMatchers.ClassicGumtree(
trees.getFirst().getRoot(), trees.getSecond().getRoot(), new MappingStore());
m.match();
assertEquals(5, m.getMappingsAsSet().size());
GreedySubtreeMatcher.MIN_HEIGHT = 1;
AbstractBottomUpMatcher.SIZE_THRESHOLD = 0;
m = new CompositeMatchers.ClassicGumtree(
trees.getFirst().getRoot(), trees.getSecond().getRoot(), new MappingStore());
m.match();
assertEquals(4, m.getMappingsAsSet().size());
}
@Test
public void testSizeThreshold() {
Pair<TreeContext, TreeContext> trees = TreeLoader.getGumtreePair();
GreedySubtreeMatcher.MIN_HEIGHT = 0;
AbstractBottomUpMatcher.SIZE_THRESHOLD = 0;
Matcher m = new CompositeMatchers.ClassicGumtree(
trees.getFirst().getRoot(), trees.getSecond().getRoot(), new MappingStore());
m.match();
assertEquals(5, m.getMappingsAsSet().size());
GreedySubtreeMatcher.MIN_HEIGHT = 0;
AbstractBottomUpMatcher.SIZE_THRESHOLD = 5;
m = new CompositeMatchers.ClassicGumtree(
trees.getFirst().getRoot(), trees.getSecond().getRoot(), new MappingStore());
m.match();
assertEquals(6, m.getMappingsAsSet().size());
}
}
|
shaowei-su/shaowei-su.github.io
|
newEff/259.3sum-smaller.java
|
/*
* [259] 3Sum Smaller
*
* https://leetcode.com/problems/3sum-smaller/description/
*
* algorithms
* Medium (43.00%)
* Total Accepted: 41.4K
* Total Submissions: 96.3K
* Testcase Example: '[-2,0,1,3]\n2'
*
* Given an array of n integers nums and a target, find the number of index
* triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i]
* + nums[j] + nums[k] < target.
*
* Example:
*
*
* Input: nums = [-2,0,1,3], and target = 2
* Output: 2
* Explanation: Because there are two triplets which sums are less than
* 2:
* [-2,0,1]
* [-2,0,3]
*
*
* Follow up: Could you solve it in O(n2) runtime?
*
*/
class Solution {
public int threeSumSmaller(int[] nums, int target) {
if (nums == null || nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int res = 0;
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;
int remain = target - nums[i];
while (left < right) {
if (nums[left] + nums[right] < remain) {
res += right - left;
left++;
} else {
right--;
}
}
}
return res;
}
}
|
Infinidat/pyvisdk
|
pyvisdk/esxcli/handlers/ha_cli_handler_hardware_cpu.py
|
from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class HardwareCpu(Base):
'''
CPU information.
'''
moid = 'ha-cli-handler-hardware-cpu'
def list(self):
'''
List all of the CPUs on this host.
:returns: vim.EsxCLI.hardware.cpu.list.Cpu[]
'''
return execute_soap(self._client, self._host, self.moid, 'vim.EsxCLI.hardware.cpu.List',
)
|
hbrunie/cctbx_project
|
cctbx/maptbx/refine_sharpening.py
|
<filename>cctbx/maptbx/refine_sharpening.py
from __future__ import absolute_import, division, print_function
import sys,os
from libtbx.utils import Sorry
from cctbx.array_family import flex
from copy import deepcopy
from cctbx.array_family import flex
import scitbx.lbfgs
import math
from cctbx.maptbx.segment_and_split_map import map_and_b_object
from six.moves import range
from six.moves import zip
def write_mtz(ma=None,phases=None,file_name=None):
mtz_dataset=ma.as_mtz_dataset(column_root_label="FWT")
mtz_dataset.add_miller_array(miller_array=phases,column_types="P", column_root_label="PHWT")
mtz_dataset.mtz_object().write(file_name=file_name)
# XXX copied these from cctbx.miller; made small change to catch weird case
# where normalizations are negative. Just multiply these *-1 and it seems to
# close to what we want. Figure this out later...
# XXX Also set means=1 not mean square = 1
def amplitude_quasi_normalisations(ma, d_star_power=1, set_to_minimum=None,
pseudo_likelihood=False): # Used for pseudo-likelihood calculation
epsilons = ma.epsilons().data().as_double()
mean_f_sq_over_epsilon = flex.double()
for i_bin in ma.binner().range_used():
sel = ma.binner().selection(i_bin)
if pseudo_likelihood:
sel_f_sq = flex.pow2(ma.data().select(sel)) # original method used
else: # usual
sel_f_sq = ma.data().select(sel)
if (sel_f_sq.size() > 0):
sel_epsilons = epsilons.select(sel)
sel_f_sq_over_epsilon = sel_f_sq / sel_epsilons
mean_f_sq_over_epsilon.append(flex.mean(sel_f_sq_over_epsilon))
else:
mean_f_sq_over_epsilon.append(0)
mean_f_sq_over_epsilon_interp = ma.binner().interpolate(
mean_f_sq_over_epsilon, d_star_power)
if set_to_minimum and not mean_f_sq_over_epsilon_interp.all_gt(0):
# HACK NO REASON THIS SHOULD WORK BUT IT GETS BY THE FAILURE
sel = (mean_f_sq_over_epsilon_interp <= set_to_minimum)
mean_f_sq_over_epsilon_interp.set_selected(sel,-mean_f_sq_over_epsilon_interp)
sel = (mean_f_sq_over_epsilon_interp <= set_to_minimum)
mean_f_sq_over_epsilon_interp.set_selected(sel,set_to_minimum)
assert mean_f_sq_over_epsilon_interp.all_gt(0)
from cctbx.miller import array
return array(ma, flex.sqrt(mean_f_sq_over_epsilon_interp))
# XXX was below before 2017-10-25
# return array(ma, mean_f_sq_over_epsilon_interp)
def quasi_normalize_structure_factors(ma, d_star_power=1, set_to_minimum=None,
pseudo_likelihood=False):
normalisations = amplitude_quasi_normalisations(ma, d_star_power,
set_to_minimum=set_to_minimum,pseudo_likelihood=pseudo_likelihood)
if pseudo_likelihood:
print("Norms:")
for n,d in zip(normalisations[:100],ma.data()[:100]): print(n,d)
q = ma.data() / normalisations.data()
from cctbx.miller import array
return array(ma, q)
def get_array(file_name=None,labels=None):
print("Reading from %s" %(file_name))
from iotbx import reflection_file_reader
reflection_file = reflection_file_reader.any_reflection_file(
file_name=file_name)
array_to_use=None
if labels:
for array in reflection_file.as_miller_arrays():
if ",".join(array.info().labels)==labels:
array_to_use=array
break
else:
for array in reflection_file.as_miller_arrays():
if array.is_complex_array() or array.is_xray_amplitude_array() or\
array.is_xray_intensity_array():
array_to_use=array
break
if not array_to_use:
text=""
for array in reflection_file.as_miller_arrays():
text+=" %s " %(",".join(array.info().labels))
raise Sorry("Cannot identify array to use...possibilities: %s" %(text))
print("Using the array %s" %(",".join(array_to_use.info().labels)))
return array_to_use
def get_amplitudes(args):
if not args or 'help' in args or '--help' in args:
print("\nsharpen.py")
print("Read in map coefficients or amplitudes and sharpen")
return
new_args=[]
file_name=None
for arg in args:
if os.path.isfile(arg) and arg.endswith(".mtz"):
file_name=arg
else:
new_args.append(arg)
args=new_args
labels=None
array_list=[]
array_list.append(get_array(file_name=file_name,labels=labels))
array=array_list[-1]
phases=None
assert array.is_complex_array()
return array
def get_effective_b_values(d_min_ratio=None,resolution_dependent_b=None,
resolution=None):
# Return effective b values at sthol2_1 2 and 3
# see adjust_amplitudes_linear below
d_min=resolution*d_min_ratio
sthol2_2=0.25/resolution**2
sthol2_1=sthol2_2*0.5
sthol2_3=0.25/d_min**2
b1=resolution_dependent_b[0]
b2=resolution_dependent_b[1]
b3=resolution_dependent_b[2]
b3_use=b3+b2
res_1=(0.25/sthol2_1)**0.5
res_2=(0.25/sthol2_2)**0.5
res_3=(0.25/sthol2_3)**0.5
# Scale factor is exp(b3_use) at res_3 for example
# f=exp(-b sthol2)
# b= - ln(f)/sthol2
b1=-b1/sthol2_1
b2=-b2/sthol2_2
b3_use=-b3_use/sthol2_3
return [res_1,res_2,res_3],[b1,b2,b3_use]
def adjust_amplitudes_linear(f_array,b1,b2,b3,resolution=None,
d_min_ratio=None):
# do something to the amplitudes.
# b1=delta_b at midway between d=inf and d=resolution,b2 at resolution,
# b3 at d_min (added to b2)
# pseudo-B at position of b1= -b1/sthol2_2= -b1*4*resolution**2
# or...b1=-pseudo_b1/(4*resolution**2)
# typical values of say b1=1 at 3 A -> pseudo_b1=-4*9=-36
data_array=f_array.data()
sthol2_array=f_array.sin_theta_over_lambda_sq()
scale_array=flex.double()
import math
#d_min=f_array.d_min()
#if resolution is None: resolution=d_min
d_min=d_min_ratio*resolution
sthol2_2=0.25/resolution**2
sthol2_1=sthol2_2*0.5
sthol2_3=0.25/d_min**2
b0=0.0
d_spacings=f_array.d_spacings()
b3_use=b3+b2
for x,(ind,sthol2),(ind1,d) in zip(data_array,sthol2_array,d_spacings):
if sthol2 > sthol2_2:
value=b2+(sthol2-sthol2_2)*(b3_use-b2)/(sthol2_3-sthol2_2)
elif sthol2 > sthol2_1:
value=b1+(sthol2-sthol2_1)*(b2-b1)/(sthol2_2-sthol2_1)
else:
value=b0+(sthol2-0.)*(b1-b0)/(sthol2_1-0.)
scale_array.append(math.exp(value))
data_array=data_array*scale_array
return f_array.customized_copy(data=data_array)
def get_scale_factors(f_array,target_scale_factors=None):
scale_array=flex.double(f_array.data().size()*(-1.,))
assert len(target_scale_factors)==len(list(f_array.binner().range_used()))
for i_bin in f_array.binner().range_used():
sel = f_array.binner().selection(i_bin)
scale_array.set_selected(sel,target_scale_factors[i_bin-1])
assert scale_array.count(-1.)==0
return scale_array
def get_model_map_coeffs_normalized(pdb_inp=None,
si=None,
f_array=None,
overall_b=None,
resolution=None,
out=sys.stdout):
if not pdb_inp: return None
# define Wilson B for the model
if overall_b is None:
if si.resolution:
overall_b=si.get_target_b_iso()*si.target_b_iso_model_scale
else:
overall_b=0
print("Setting Wilson B = %5.1f A" %(overall_b), file=out)
# create model map using same coeffs
from cctbx.maptbx.segment_and_split_map import get_f_phases_from_model
model_map_coeffs=get_f_phases_from_model(
pdb_inp=pdb_inp,
f_array=f_array,
overall_b=overall_b,
k_sol=si.k_sol,
b_sol=si.b_sol,
out=out)
from cctbx.maptbx.segment_and_split_map import map_coeffs_as_fp_phi,get_b_iso
model_f_array,model_phases=map_coeffs_as_fp_phi(model_map_coeffs)
(d_max,d_min)=f_array.d_max_min()
model_f_array.setup_binner(n_bins=si.n_bins,d_max=d_max,d_min=d_min)
# Set overall_b....
final_b_iso=get_b_iso(model_f_array,d_min=resolution)
print("Effective b_iso of "+\
"adjusted model map: %6.1f A**2" %(final_b_iso), file=out)
model_map_coeffs_normalized=model_f_array.phase_transfer(
phase_source=model_phases,deg=True)
return model_map_coeffs_normalized
def get_b_eff(si=None,out=sys.stdout):
if si.rmsd is None:
b_eff=None
else:
b_eff=8*3.14159*si.rmsd**2
print("Setting b_eff for fall-off at %5.1f A**2 based on model error of %5.1f A" \
%( b_eff,si.rmsd), file=out)
return b_eff
def cc_fit(sthol_list=None,scale=None,value_zero=None,baseline=None,
scale_using_last=None):
# for scale_using_last, fix final value at zero
fit=flex.double()
s_zero=sthol_list[0]
for s in sthol_list:
fit.append(value_zero*math.exp(-scale*(s-s_zero)))
if scale_using_last:
fit=fit-fit[-1]
return fit
def get_baseline(scale=None,scale_using_last=None,max_cc_for_rescale=None):
if not scale_using_last:
return 0
else:
baseline=min(0.99,max(0.,scale[-scale_using_last:].min_max_mean().mean))
if baseline > max_cc_for_rescale:
return None
else:
return baseline
def fit_cc(cc_list=None,sthol_list=None,
scale_min=None,scale_max=None,n_tries=None,scale_using_last=None):
# find value of scale in range scale_min,scale_max that minimizes rms diff
# between cc_list and cc_list[0]*exp(-scale*(sthol-sthol_list[0]))
# for scale_using_last, require it to go to zero at end
best_scale=None
best_rms=None
for i in range(n_tries):
scale=scale_min+(scale_max-scale_min)*i/n_tries
fit=cc_fit(sthol_list=sthol_list,scale=scale,value_zero=cc_list[0],
scale_using_last=scale_using_last)
fit=fit-cc_list
rms=fit.norm()
if best_rms is None or rms<best_rms:
best_rms=rms
best_scale=scale
return cc_fit(sthol_list=sthol_list,scale=best_scale,value_zero=cc_list[0],
scale_using_last=scale_using_last)
def get_fitted_cc(cc_list=None,sthol_list=None, cc_cut=None,
scale_using_last=None):
# only do this if there is some value of s where cc is at least 2*cc_cut or
# (1-c_cut/2), whichever is smaller
min_cc=min(2*cc_cut,1-0.5*cc_cut)
if cc_list.min_max_mean().max < min_cc:
return cc_list
# find first point after point where cc>=min_cc that cc<=cc_cut
# then back off by 1 point
found_high=False
s_cut=None
i_cut=0
for s,cc in zip(sthol_list,cc_list):
if cc > min_cc:
found_high=True
if found_high and cc < cc_cut:
s_cut=s
break
i_cut+=1
if s_cut is None or i_cut==0:
return cc_list
#Fit remainder
sthol_remainder_list=sthol_list[i_cut:]
cc_remainder_list=cc_list[i_cut:]
n=cc_remainder_list.size()
scale_min=10 # soft
scale_max=500 # hard
n_tries=200
fitted_cc_remainder_list=fit_cc(
cc_list=cc_remainder_list,sthol_list=sthol_remainder_list,
scale_min=scale_min,scale_max=scale_max,n_tries=n_tries,
scale_using_last=scale_using_last)
new_cc_list=cc_list[:i_cut]
new_cc_list.extend(fitted_cc_remainder_list)
return new_cc_list
def estimate_cc_star(cc_list=None,sthol_list=None, cc_cut=None,
scale_using_last=None):
# cc ~ sqrt(2*half_dataset_cc/(1+half_dataset_cc))
# however for small cc the errors are very big and we think cc decreases
# rapidly towards zero once cc is small
# So find value of sthol_zero that gives cc about cc_cut...for
# sthol >sthol_zero use fit of cc_zero * exp(-falloff*(sthol-sthol_zero))
# for scale_using_last set: subtract off final values so it goes to zero.
fitted_cc=get_fitted_cc(
cc_list=cc_list,sthol_list=sthol_list,cc_cut=cc_cut,
scale_using_last=scale_using_last)
cc_star_list=flex.double()
for cc in fitted_cc:
cc=max(cc,0.)
cc_star=(2.*cc/(1.+cc))**0.5
cc_star_list.append(cc_star)
return cc_star_list
def rescale_cc_list(cc_list=None,scale_using_last=None,
max_cc_for_rescale=None):
baseline=get_baseline(scale=cc_list,
scale_using_last=scale_using_last,
max_cc_for_rescale=max_cc_for_rescale)
if baseline is None:
return cc_list,baseline
# replace cc with (cc-baseline)/(1-baseline)
scaled_cc_list=flex.double()
for cc in cc_list:
scaled_cc_list.append((cc-baseline)/(1-baseline))
return scaled_cc_list,baseline
def calculate_fsc(si=None,
f_array=None, # just used for binner
map_coeffs=None,
model_map_coeffs=None,
first_half_map_coeffs=None,
second_half_map_coeffs=None,
resolution=None,
fraction_complete=None,
min_fraction_complete=None,
is_model_based=None,
cc_cut=None,
scale_using_last=None,
max_cc_for_rescale=None,
pseudo_likelihood=False,
skip_scale_factor=False,
verbose=None,
out=sys.stdout):
# calculate anticipated fall-off of model data with resolution
if si.rmsd is None and is_model_based:
si.rmsd=resolution*si.rmsd_resolution_factor
print("Setting rmsd to %5.1f A based on resolution of %5.1f A" %(
si.rmsd,resolution), file=out)
# get f and model_f vs resolution and FSC vs resolution and apply
# scale to f_array and return sharpened map
dsd = f_array.d_spacings().data()
from cctbx.maptbx.segment_and_split_map import map_coeffs_to_fp
if is_model_based:
mc1=map_coeffs
mc2=model_map_coeffs
fo_map=map_coeffs # scale map_coeffs to model_map_coeffs*FSC
fc_map=model_map_coeffs
b_eff=get_b_eff(si=si,out=out)
else: # half_dataset
mc1=first_half_map_coeffs
mc2=second_half_map_coeffs
fo_map=map_coeffs # scale map_coeffs to cc*
fc_map=model_map_coeffs
b_eff=None
ratio_list=flex.double()
target_sthol2=flex.double()
cc_list=flex.double()
sthol_list=flex.double()
d_min_list=flex.double()
rms_fo_list=flex.double()
rms_fc_list=flex.double()
max_possible_cc=None
for i_bin in f_array.binner().range_used():
sel = f_array.binner().selection(i_bin)
d = dsd.select(sel)
if d.size()<1:
raise Sorry("Please reduce number of bins (no data in bin "+
"%s) from current value of %s" %(i_bin,f_array.binner().n_bins_used()))
d_min = flex.min(d)
d_max = flex.max(d)
d_avg = flex.mean(d)
n = d.size()
m1 = mc1.select(sel)
m2 = mc2.select(sel)
cc = m1.map_correlation(other = m2)
if fo_map:
fo = fo_map.select(sel)
f_array_fo=map_coeffs_to_fp(fo)
rms_fo=f_array_fo.data().norm()
else:
rms_fo=1.
if fc_map:
fc = fc_map.select(sel)
f_array_fc=map_coeffs_to_fp(fc)
rms_fc=f_array_fc.data().norm()
else:
rms_fc=1.
sthol2=0.25/d_avg**2
ratio_list.append(max(1.e-10,rms_fc)/max(1.e-10,rms_fo))
target_sthol2.append(sthol2)
if cc is None: cc=0.
cc_list.append(cc)
sthol_list.append(1/d_avg)
d_min_list.append(d_min)
rms_fo_list.append(rms_fo)
rms_fc_list.append(rms_fc)
if b_eff is not None:
max_cc_estimate=cc* math.exp(min(20.,sthol2*b_eff))
else:
max_cc_estimate=cc
max_cc_estimate=max(0.,min(1.,max_cc_estimate))
if max_possible_cc is None or (
max_cc_estimate > 0 and max_cc_estimate > max_possible_cc):
max_possible_cc=max_cc_estimate
if verbose:
print("d_min: %5.1f FC: %7.1f FOBS: %7.1f CC: %5.2f" %(
d_avg,rms_fc,rms_fo,cc), file=out)
if scale_using_last: # rescale to give final value average==0
cc_list,baseline=rescale_cc_list(
cc_list=cc_list,scale_using_last=scale_using_last,
max_cc_for_rescale=max_cc_for_rescale)
if baseline is None: # don't use it
scale_using_last=None
original_cc_list=deepcopy(cc_list)
if not is_model_based: # calculate cc* for half-dataset cc
cc_list=estimate_cc_star(cc_list=cc_list,sthol_list=sthol_list,
cc_cut=cc_cut,scale_using_last=scale_using_last)
if not max_possible_cc:
max_possible_cc=0.01
if si.target_scale_factors: # not using these
max_possible_cc=1.
fraction_complete=1.
elif (not is_model_based):
max_possible_cc=1.
fraction_complete=1.
else:
# Define overall CC based on model completeness (CC=sqrt(fraction_complete))
if fraction_complete is None:
fraction_complete=max_possible_cc**2
print("Estimated fraction complete is %5.2f based on low_res CC of %5.2f" %(
fraction_complete,max_possible_cc), file=out)
else:
print("Using fraction complete value of %5.2f " %(fraction_complete), file=out)
max_possible_cc=fraction_complete**0.5
target_scale_factors=flex.double()
for i_bin in f_array.binner().range_used():
index=i_bin-1
ratio=ratio_list[index]
cc=cc_list[index]
sthol2=target_sthol2[index]
d_min=d_min_list[index]
corrected_cc=max(0.00001,min(1.,cc/max_possible_cc))
if (not is_model_based): # cc is already cc*
scale_on_fo=ratio * corrected_cc
elif b_eff is not None:
if pseudo_likelihood:
scale_on_fo=(cc/max(0.001,1-cc**2))
else: # usual
scale_on_fo=ratio * min(1.,
max(0.00001,corrected_cc) * math.exp(min(20.,sthol2*b_eff)) )
else:
scale_on_fo=ratio * min(1.,max(0.00001,corrected_cc))
target_scale_factors.append(scale_on_fo)
if not pseudo_likelihood and not skip_scale_factor: # normalize
scale_factor=1./target_scale_factors.min_max_mean().max
target_scale_factors=\
target_scale_factors*scale_factor
print("Scale factor A: %.5f" %(scale_factor), file=out)
if fraction_complete < min_fraction_complete:
print("\nFraction complete (%5.2f) is less than minimum (%5.2f)..." %(
fraction_complete,min_fraction_complete) + "\nSkipping scaling", file=out)
target_scale_factors=flex.double(target_scale_factors.size()*(1.0,))
print ("\nAverage CC: %.3f" %(cc_list.min_max_mean().mean),file=out)
print("\nScale factors vs resolution:", file=out)
print("Note 1: CC* estimated from sqrt(2*CC/(1+CC))", file=out)
print("Note 2: CC estimated by fitting (smoothing) for values < %s" %(cc_cut), file=out)
print("Note 3: Scale = A CC* rmsFc/rmsFo (A is normalization)", file=out)
print(" d_min rmsFo rmsFc CC CC* Scale", file=out)
for sthol2,scale,rms_fo,cc,rms_fc,orig_cc in zip(
target_sthol2,target_scale_factors,rms_fo_list,cc_list,rms_fc_list,
original_cc_list):
print("%7.1f %9.1f %9.1f %7.3f %7.3f %5.2f" %(
0.5/sthol2**0.5,rms_fo,rms_fc,orig_cc,cc,scale), file=out)
si.target_scale_factors=target_scale_factors
si.target_sthol2=target_sthol2
si.d_min_list=d_min_list
si.cc_list=cc_list
return si
def analyze_aniso(f_array=None,map_coeffs=None,b_iso=None,resolution=None,
get_remove_aniso_object=True,
remove_aniso=None, aniso_obj=None, out=sys.stdout):
# optionally remove anisotropy and set all directions to mean value
# return array and analyze_aniso_object
# resolution can be None, b_iso can be None
# if remove_aniso is None, just analyze and return original array
if map_coeffs: # convert to f and apply
from cctbx.maptbx.segment_and_split_map import map_coeffs_as_fp_phi
f_local,phases_local=map_coeffs_as_fp_phi(map_coeffs)
f_local,f_local_aa=analyze_aniso(f_array=f_local,
aniso_obj=aniso_obj,
get_remove_aniso_object=get_remove_aniso_object,
remove_aniso=remove_aniso, resolution=resolution,out=out)
return f_local.phase_transfer(phase_source=phases_local,deg=True),f_local_aa
elif not get_remove_aniso_object:
return f_array,aniso_obj # don't do anything
else: # have f_array and resolution
if not aniso_obj:
aniso_obj=analyze_aniso_object()
aniso_obj.set_up_aniso_correction(f_array=f_array,d_min=resolution)
if remove_aniso and aniso_obj and aniso_obj.b_cart:
f_array=aniso_obj.apply_aniso_correction(f_array=f_array)
print("Removing anisotropy with b_cart=(%7.2f,%7.2f,%7.2f)\n" %(
aniso_obj.b_cart[:3]), file=out)
return f_array,aniso_obj
def scale_amplitudes(model_map_coeffs=None,
map_coeffs=None,
first_half_map_coeffs=None,
second_half_map_coeffs=None,
si=None,resolution=None,overall_b=None,
fraction_complete=None,
min_fraction_complete=0.05,
map_calculation=True,
verbose=False,
out=sys.stdout):
# Figure out resolution_dependent sharpening to optimally
# match map and model. Then apply it as usual.
# if second_half_map_coeffs instead of model, use second_half_map_coeffs same as
# normalized model map_coeffs, except that the target fall-off should be
# skipped (could use fall-off based on a dummy model...)
if model_map_coeffs and (
not first_half_map_coeffs or not second_half_map_coeffs):
is_model_based=True
else:
assert si.target_scale_factors or (
first_half_map_coeffs and second_half_map_coeffs)
is_model_based=False
if si.verbose and not verbose:
verbose=True
# if si.target_scale_factors is set, just use those scale factors
from cctbx.maptbx.segment_and_split_map import map_coeffs_as_fp_phi,get_b_iso
f_array,phases=map_coeffs_as_fp_phi(map_coeffs)
(d_max,d_min)=f_array.d_max_min()
if not f_array.binner():
f_array.setup_binner(n_bins=si.n_bins,d_max=d_max,d_min=d_min)
f_array.binner().require_all_bins_have_data(min_counts=1,
error_string="Please use a lower value of n_bins")
if resolution is None:
resolution=si.resolution
if resolution is None:
raise Sorry("Need resolution for model sharpening")
obs_b_iso=get_b_iso(f_array,d_min=resolution)
print("\nEffective b_iso of observed data: %6.1f A**2" %(obs_b_iso), file=out)
if not si.target_scale_factors: # get scale factors if don't already have them
si=calculate_fsc(si=si,
f_array=f_array, # just used for binner
map_coeffs=map_coeffs,
model_map_coeffs=model_map_coeffs,
first_half_map_coeffs=first_half_map_coeffs,
second_half_map_coeffs=second_half_map_coeffs,
resolution=resolution,
fraction_complete=fraction_complete,
min_fraction_complete=min_fraction_complete,
is_model_based=is_model_based,
cc_cut=si.cc_cut,
scale_using_last=si.scale_using_last,
max_cc_for_rescale=si.max_cc_for_rescale,
pseudo_likelihood=si.pseudo_likelihood,
verbose=verbose,
out=out)
# now si.target_scale_factors array are the scale factors
# Now create resolution-dependent coefficients from the scale factors
if not si.target_scale_factors: # nothing to do
print("\nNo scaling applied", file=out)
map_data=calculate_map(map_coeffs=map_coeffs,n_real=si.n_real)
return map_and_b_object(map_data=map_data)
elif not map_calculation:
return map_and_b_object()
else: # apply scaling
if si.pseudo_likelihood:
print("Normalizing structure factors", file=out)
f_array=quasi_normalize_structure_factors(f_array,set_to_minimum=0.01,
pseudo_likelihood=si.pseudo_likelihood)
f_array.setup_binner(n_bins=si.n_bins,d_max=d_max,d_min=d_min)
map_and_b=apply_target_scale_factors(
f_array=f_array,phases=phases,resolution=resolution,
target_scale_factors=si.target_scale_factors,
n_real=si.n_real,
out=out)
return map_and_b
def apply_target_scale_factors(f_array=None,phases=None,
resolution=None,target_scale_factors=None,
n_real=None,
return_map_coeffs=None,out=sys.stdout):
from cctbx.maptbx.segment_and_split_map import get_b_iso
f_array_b_iso=get_b_iso(f_array,d_min=resolution)
scale_array=get_scale_factors(f_array,
target_scale_factors=target_scale_factors)
scaled_f_array=f_array.customized_copy(data=f_array.data()*scale_array)
scaled_f_array_b_iso=get_b_iso(scaled_f_array,d_min=resolution)
print("\nInitial b_iso for "+\
"map: %5.1f A**2 After applying scaling: %5.1f A**2" %(
f_array_b_iso,scaled_f_array_b_iso), file=out)
new_map_coeffs=scaled_f_array.phase_transfer(phase_source=phases,deg=True)
if return_map_coeffs:
return new_map_coeffs
map_data=calculate_map(map_coeffs=new_map_coeffs,n_real=n_real)
return map_and_b_object(map_data=map_data,starting_b_iso=f_array_b_iso,
final_b_iso=scaled_f_array_b_iso)
def calculate_map(map_coeffs=None,crystal_symmetry=None,n_real=None):
if crystal_symmetry is None: crystal_symmetry=map_coeffs.crystal_symmetry()
from cctbx.maptbx.segment_and_split_map import get_map_from_map_coeffs
map_data=get_map_from_map_coeffs(
map_coeffs=map_coeffs,crystal_symmetry=crystal_symmetry, n_real=n_real)
return map_data
def get_sharpened_map(ma=None,phases=None,b=None,resolution=None,
n_real=None,d_min_ratio=None):
assert n_real is not None
sharpened_ma=adjust_amplitudes_linear(ma,b[0],b[1],b[2],resolution=resolution,
d_min_ratio=d_min_ratio)
new_map_coeffs=sharpened_ma.phase_transfer(phase_source=phases,deg=True)
map_data=calculate_map(map_coeffs=new_map_coeffs,n_real=n_real)
return map_data
def calculate_match(target_sthol2=None,target_scale_factors=None,b=None,resolution=None,d_min_ratio=None,rmsd=None,fraction_complete=None):
if fraction_complete is None:
pass # XXX not implemented for fraction_complete
if rmsd is None:
rmsd=resolution/3.
print("Setting rmsd to %5.1f A based on resolution of %5.1f A" %(
rmsd,resolution), file=out)
if rmsd is None:
b_eff=None
else:
b_eff=8*3.14159*rmsd**2
d_min=d_min_ratio*resolution
sthol2_2=0.25/resolution**2
sthol2_1=sthol2_2*0.5
sthol2_3=0.25/d_min**2
b0=0.0
b1=b[0]
b2=b[1]
b3=b[2]
b3_use=b3+b2
resid=0.
import math
value_list=flex.double()
scale_factor_list=flex.double()
for sthol2,scale_factor in zip(target_sthol2,target_scale_factors):
if sthol2 > sthol2_2:
value=b2+(sthol2-sthol2_2)*(b3_use-b2)/(sthol2_3-sthol2_2)
elif sthol2 > sthol2_1:
value=b1+(sthol2-sthol2_1)*(b2-b1)/(sthol2_2-sthol2_1)
else:
value=b0+(sthol2-0.)*(b1-b0)/(sthol2_1-0.)
value=math.exp(value)
if b_eff is not None:
value=value*math.exp(-sthol2*b_eff)
value_list.append(value)
scale_factor_list.append(scale_factor)
mean_value=value_list.min_max_mean().mean
mean_scale_factor=scale_factor_list.min_max_mean().mean
ratio=mean_scale_factor/mean_value
value_list=value_list*ratio
delta_list=value_list-scale_factor_list
delta_sq_list=delta_list*delta_list
resid=delta_sq_list.min_max_mean().mean
return resid
def calculate_adjusted_sa(ma,phases,b,
resolution=None,
d_min_ratio=None,
solvent_fraction=None,
region_weight=None,
max_regions_to_test=None,
sa_percent=None,
fraction_occupied=None,
wrapping=None,
n_real=None):
map_data=get_sharpened_map(ma,phases,b,resolution,n_real=n_real,
d_min_ratio=d_min_ratio)
from cctbx.maptbx.segment_and_split_map import score_map
from libtbx.utils import null_out
si=score_map(
map_data=map_data,
solvent_fraction=solvent_fraction,
fraction_occupied=fraction_occupied,
wrapping=wrapping,
sa_percent=sa_percent,
region_weight=region_weight,
max_regions_to_test=max_regions_to_test,
out=null_out())
return si.adjusted_sa
def get_kurtosis(data=None):
mean=data.min_max_mean().mean
sd=data.standard_deviation_of_the_sample()
x=data-mean
return (x**4).min_max_mean().mean/sd**4
class analyze_aniso_object:
def __init__(self):
self.b_iso=None # target b_iso, default is mean of existing
self.b_cart=None
self.b_cart_aniso_removed=None
def set_up_aniso_correction(self,f_array=None,b_iso=None,d_min=None):
assert f_array is not None
if not d_min:
(d_max,d_min)=f_array.d_max_min()
from cctbx.maptbx.segment_and_split_map import get_b_iso
b_mean,aniso_scale_and_b=get_b_iso(f_array,d_min=d_min,
return_aniso_scale_and_b=True)
if not aniso_scale_and_b or not aniso_scale_and_b.b_cart:
return # failed
if b_iso is None:
b_iso=b_mean # use mean
self.b_iso=b_iso
self.b_cart=aniso_scale_and_b.b_cart # current
self.b_cart_aniso_removed = [ -b_iso, -b_iso, -b_iso, 0, 0, 0] # change
# ready to apply
def apply_aniso_correction(self,f_array=None):
if self.b_cart is None or self.b_cart_aniso_removed is None:
return f_array # nothing to do
from mmtbx.scaling import absolute_scaling
from cctbx import adptbx
u_star= adptbx.u_cart_as_u_star(
f_array.unit_cell(), adptbx.b_as_u( self.b_cart) )
u_star_aniso_removed = adptbx.u_cart_as_u_star(
f_array.unit_cell(), adptbx.b_as_u( self.b_cart_aniso_removed ) )
no_aniso_array = absolute_scaling.anisotropic_correction(
f_array,0.0, u_star ,must_be_greater_than=-0.0001)
no_aniso_array = absolute_scaling.anisotropic_correction(
no_aniso_array,0.0,u_star_aniso_removed,must_be_greater_than=-0.0001)
no_aniso_array=no_aniso_array.set_observation_type( f_array)
return no_aniso_array
class refinery:
def __init__(self,ma,phases,b,resolution,
residual_target=None,
solvent_fraction=None,
region_weight=None,
max_regions_to_test=None,
sa_percent=None,
fraction_occupied=None,
wrapping=None,
eps=0.01,
tol=0.01,
max_iterations=20,
n_real=None,
target_sthol2=None,
target_scale_factors=None,
d_min_ratio=None,
rmsd=None,
fraction_complete=None,
dummy_run=False):
self.ma=ma
self.n_real=n_real
self.phases=phases
self.resolution=resolution
self.d_min_ratio=d_min_ratio
self.rmsd=rmsd
self.fraction_complete=fraction_complete
self.target_sthol2=target_sthol2
self.target_scale_factors=target_scale_factors
self.tol=tol
self.eps=eps
self.max_iterations=max_iterations
self.solvent_fraction=solvent_fraction
self.region_weight=region_weight
self.max_regions_to_test=max_regions_to_test
self.residual_target=residual_target
self.sa_percent=sa_percent
self.fraction_occupied=fraction_occupied
self.wrapping=wrapping
self.x = flex.double(b)
def run(self):
scitbx.lbfgs.run(target_evaluator=self,
termination_params=scitbx.lbfgs.termination_parameters(
traditional_convergence_test_eps=self.tol,
max_iterations=self.max_iterations,
))
def show_result(self,out=sys.stdout):
b=self.get_b()
value = -1.*self.residual(b)
print("Result: b1 %7.2f b2 %7.2f b3 %7.2f resolution %7.2f %s: %7.3f" %(
b[0],b[1],b[2],self.resolution,self.residual_target,value), file=out)
if self.ma:
self.sharpened_ma=adjust_amplitudes_linear(
self.ma,b[0],b[1],b[2],resolution=self.resolution,
d_min_ratio=self.d_min_ratio)
else:
self.sharpened_ma=None
return value
def compute_functional_and_gradients(self):
b = self.get_b()
f = self.residual(b)
g = self.gradients(b)
return f, g
def residual(self,b,restraint_weight=100.):
if self.residual_target=='kurtosis':
resid=-1.*calculate_kurtosis(self.ma,self.phases,b,self.resolution,
n_real=self.n_real,d_min_ratio=self.d_min_ratio)
elif self.residual_target=='adjusted_sa':
resid=-1.*calculate_adjusted_sa(self.ma,self.phases,b,
resolution=self.resolution,
d_min_ratio=self.d_min_ratio,
solvent_fraction=self.solvent_fraction,
region_weight=self.region_weight,
max_regions_to_test=self.max_regions_to_test,
sa_percent=self.sa_percent,
fraction_occupied=self.fraction_occupied,
wrapping=self.wrapping,n_real=self.n_real)
elif self.residual_target=='model':
resid=calculate_match(target_sthol2=self.target_sthol2,
target_scale_factors=self.target_scale_factors,
b=b,
resolution=self.resolution,
d_min_ratio=self.d_min_ratio,
emsd=self.rmsd,
fraction_complete=self.complete)
else:
raise Sorry("residual_target must be kurtosis or adjusted_sa or match_target")
# put in restraint so b[1] is not bigger than b[0]
if b[1]>b[0]: resid+=(b[1]-b[0])*restraint_weight
# put in restraint so b[2] <=0
if b[2]>0: resid+=b[2]*restraint_weight
return resid
def gradients(self,b):
result = flex.double()
for i in range(len(list(b))):
rs = []
for signed_eps in [self.eps, -self.eps]:
params_eps = deepcopy(b)
params_eps[i] += signed_eps
rs.append(self.residual(params_eps))
result.append((rs[0]-rs[1])/(2*self.eps))
return result
def get_b(self):
return list(self.x)
def callback_after_step(self, minimizer):
pass # can do anything here
def calculate_kurtosis(ma,phases,b,resolution,n_real=None,
d_min_ratio=None):
map_data=get_sharpened_map(ma,phases,b,resolution,n_real=n_real,
d_min_ratio=d_min_ratio)
return get_kurtosis(map_data.as_1d())
def run(map_coeffs=None,
b=[0,0,0],
sharpening_info_obj=None,
resolution=None,
residual_target=None,
solvent_fraction=None,
region_weight=None,
max_regions_to_test=None,
sa_percent=None,
fraction_occupied=None,
n_bins=None,
eps=None,
wrapping=False,
n_real=False,
target_sthol2=None,
target_scale_factors=None,
d_min_ratio=None,
rmsd=None,
fraction_complete=None,
normalize_amplitudes_in_resdep=None,
out=sys.stdout):
if sharpening_info_obj:
solvent_fraction=sharpening_info_obj.solvent_fraction
wrapping=sharpening_info_obj.wrapping
n_real=sharpening_info_obj.n_real
fraction_occupied=sharpening_info_obj.fraction_occupied
sa_percent=sharpening_info_obj.sa_percent
region_weight=sharpening_info_obj.region_weight
max_regions_to_test=sharpening_info_obj.max_regions_to_test
residual_target=sharpening_info_obj.residual_target
resolution=sharpening_info_obj.resolution
d_min_ratio=sharpening_info_obj.d_min_ratio
rmsd=sharpening_info_obj.rmsd
fraction_complete=sharpening_info_obj.fraction_complete
eps=sharpening_info_obj.eps
n_bins=sharpening_info_obj.n_bins
normalize_amplitudes_in_resdep= \
sharpening_info_obj.normalize_amplitudes_in_resdep
else:
from cctbx.maptbx.segment_and_split_map import sharpening_info
sharpening_info_obj=sharpening_info()
if map_coeffs:
phases=map_coeffs.phases(deg=True)
ma=map_coeffs.as_amplitude_array()
else:
phases=None
ma=None
# set some defaults
if residual_target is None: residual_target='kurtosis'
assert (solvent_fraction is not None ) or residual_target=='kurtosis'
assert resolution is not None
if residual_target=='adjusted_sa' and solvent_fraction is None:
raise Sorry("Solvent fraction is required for residual_target=adjusted_sa")
if eps is None and residual_target=='kurtosis':
eps=0.01
elif eps is None:
eps=0.5
if fraction_complete is None:
pass # XXX not implemented
if rmsd is None:
rmsd=resolution/3.
print("Setting rmsd to %5.1f A based on resolution of %5.1f A" %(
rmsd,resolution), file=out)
if fraction_occupied is None: fraction_occupied=0.20
if region_weight is None: region_weight=20.
if sa_percent is None: sa_percent=30.
if n_bins is None: n_bins=20
if max_regions_to_test is None: max_regions_to_test=30
# Get initial value
best_b=b
print("Getting starting value ...",residual_target, file=out)
refined = refinery(ma,phases,b,resolution,
residual_target=residual_target,
solvent_fraction=solvent_fraction,
region_weight=region_weight,
sa_percent=sa_percent,
max_regions_to_test=max_regions_to_test,
fraction_occupied=fraction_occupied,
wrapping=wrapping,
n_real=n_real,
target_sthol2=target_sthol2,
target_scale_factors=target_scale_factors,
d_min_ratio=d_min_ratio,
rmsd=rmsd,
fraction_complete=fraction_complete,
eps=eps)
starting_result=refined.show_result(out=out)
print("Starting value: %7.2f" %(starting_result), file=out)
if ma:
(d_max,d_min)=ma.d_max_min()
ma.setup_binner(n_bins=n_bins,d_max=d_max,d_min=d_min)
if normalize_amplitudes_in_resdep:
print("Normalizing structure factors...", file=out)
ma=quasi_normalize_structure_factors(ma,set_to_minimum=0.01)
else:
assert resolution is not None
refined = refinery(ma,phases,b,resolution,
residual_target=residual_target,
solvent_fraction=solvent_fraction,
region_weight=region_weight,
max_regions_to_test=max_regions_to_test,
sa_percent=sa_percent,
fraction_occupied=fraction_occupied,
wrapping=wrapping,
n_real=n_real,
target_sthol2=target_sthol2,
target_scale_factors=target_scale_factors,
d_min_ratio=d_min_ratio,
rmsd=rmsd,
fraction_complete=fraction_complete,
eps=eps)
starting_normalized_result=refined.show_result(out=out)
print("Starting value after normalization: %7.2f" %(
starting_normalized_result), file=out)
best_sharpened_ma=ma
best_result=starting_normalized_result
best_b=refined.get_b()
refined.run()
final_result=refined.show_result(out=out)
print("Final value: %7.2f" %(
final_result), file=out)
if final_result>best_result:
best_sharpened_ma=refined.sharpened_ma
best_result=final_result
best_b=refined.get_b()
print("Best overall result: %7.2f: " %(best_result), file=out)
sharpening_info_obj.resolution_dependent_b=best_b
return best_sharpened_ma,phases
if (__name__ == "__main__"):
args=sys.argv[1:]
residual_target='kurtosis'
if 'adjusted_sa' in args:
residual_target='adjusted_sa'
resolution=2.9 # need to set this as nominal resolution
# get data
map_coeffs=get_amplitudes(args)
new_map_coeffs=run(map_coeffs=map_coeffs,
resolution=resolution,
residual_target=residual_target)
mtz_dataset=new_map_coeffs.as_mtz_dataset(column_root_label="FWT")
mtz_dataset.mtz_object().write(file_name='sharpened.mtz')
|
omerlevran46/sdk
|
runtime/vm/compiler/frontend/flow_graph_builder.h
|
<filename>runtime/vm/compiler/frontend/flow_graph_builder.h
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#ifndef RUNTIME_VM_COMPILER_FRONTEND_FLOW_GRAPH_BUILDER_H_
#define RUNTIME_VM_COMPILER_FRONTEND_FLOW_GRAPH_BUILDER_H_
#if defined(DART_PRECOMPILED_RUNTIME)
#error "AOT runtime should not use compiler sources (including header files)"
#endif // defined(DART_PRECOMPILED_RUNTIME)
#include "platform/assert.h"
#include "platform/globals.h"
#include "vm/allocation.h"
#include "vm/compiler/backend/flow_graph.h"
#include "vm/compiler/backend/il.h"
#include "vm/growable_array.h"
#include "vm/raw_object.h"
namespace dart {
// A class to collect the exits from an inlined function during graph
// construction so they can be plugged into the caller's flow graph.
class InlineExitCollector : public ZoneAllocated {
public:
InlineExitCollector(FlowGraph* caller_graph, Definition* call)
: caller_graph_(caller_graph), call_(call), exits_(4) {}
void AddExit(ReturnInstr* exit);
void Union(const InlineExitCollector* other);
// Before replacing a call with a graph, the outer environment needs to be
// attached to each instruction in the callee graph and the caller graph
// needs to have its block and instruction ID state updated.
// Additionally we need to remove all unreachable exits from the list of
// collected exits.
void PrepareGraphs(FlowGraph* callee_graph);
// Inline a graph at a call site.
//
// Assumes the callee is in SSA with a correct dominator tree and use
// lists.
//
// After inlining the caller graph will have correctly adjusted the use
// lists. The block orders will need to be recomputed.
void ReplaceCall(BlockEntryInstr* callee_entry);
private:
struct Data {
BlockEntryInstr* exit_block;
ReturnInstr* exit_return;
};
BlockEntryInstr* ExitBlockAt(intptr_t i) const {
ASSERT(exits_[i].exit_block != NULL);
return exits_[i].exit_block;
}
Instruction* LastInstructionAt(intptr_t i) const {
return ReturnAt(i)->previous();
}
Value* ValueAt(intptr_t i) const { return ReturnAt(i)->value(); }
ReturnInstr* ReturnAt(intptr_t i) const { return exits_[i].exit_return; }
static int LowestBlockIdFirst(const Data* a, const Data* b);
void SortExits();
void RemoveUnreachableExits(FlowGraph* callee_graph);
Definition* JoinReturns(BlockEntryInstr** exit_block,
Instruction** last_instruction,
intptr_t try_index);
Zone* zone() const { return caller_graph_->zone(); }
FlowGraph* caller_graph_;
Definition* call_;
GrowableArray<Data> exits_;
};
bool SimpleInstanceOfType(const AbstractType& type);
uword FindDoubleConstant(double value);
} // namespace dart
#endif // RUNTIME_VM_COMPILER_FRONTEND_FLOW_GRAPH_BUILDER_H_
|
eugeneilyin/mdi-norm
|
lib/SharpArrowRight.js
|
"use strict";
exports.__esModule = true;
var _FilledArrowRight = require("./FilledArrowRight");
exports.SharpArrowRight = _FilledArrowRight.FilledArrowRight;
|
gradient-ml/Ghost
|
node_modules/intl-messageformat/lib/en.js
|
<gh_stars>100-1000
// GENERATED FILE
"use strict";
exports["default"] = {"locale":"en","pluralRuleFunction":function (n,ord){var s=String(n).split("."),v0=!s[1],t0=Number(s[0])==n,n10=t0&&s[0].slice(-1),n100=t0&&s[0].slice(-2);if(ord)return n10==1&&n100!=11?"one":n10==2&&n100!=12?"two":n10==3&&n100!=13?"few":"other";return n==1&&v0?"one":"other"}};
//# sourceMappingURL=en.js.map
|
postnummeruppror/insamlingsappen-server
|
src/test/java/nu/postnummeruppror/insamlingsappen/PostortsPolygonServiceSkyddsrum.java
|
package nu.postnummeruppror.insamlingsappen;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.PrecisionModel;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import se.kodapan.osm.jts.voronoi.AdjacentClassVoronoiClusterer;
import se.kodapan.osm.jts.voronoi.GeoJSONVoronoiFactory;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
/**
* @author kalle
* @since 2014-09-20 22:32
*/
public class PostortsPolygonServiceSkyddsrum {
public static void main(String[] args) throws Exception {
new PostortsPolygonServiceSkyddsrum().factory();
}
public void factory() throws Exception {
JSONArray skyddsrumJSON = new JSONArray(new JSONTokener(new InputStreamReader(getClass().getResourceAsStream("/skyddsrum-ej-cc0.json"), "UTF8")));
AdjacentClassVoronoiClusterer<String> voronoiClusterer = new AdjacentClassVoronoiClusterer<>(new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), 4326));
voronoiClusterer.setNumberOfThreads(4);
for (int i = 0; i < skyddsrumJSON.length(); i++) {
JSONObject skyddsrum = skyddsrumJSON.getJSONObject(i);
if (skyddsrum.has("kommunnamn")) {
String postalTown = skyddsrum.getString("kommunnamn").trim().toUpperCase();
if (!postalTown.isEmpty()) {
voronoiClusterer.addCoordinate(postalTown, skyddsrum.getDouble("longitud"), skyddsrum.getDouble("latitud"));
}
}
}
Map<String, List<Polygon>> voronoiClusters = voronoiClusterer.build();
Writer writer = new OutputStreamWriter(new FileOutputStream("src/test/resources/postalTowns-skyddsrum.geo.json"), "UTF8");
GeoJSONVoronoiFactory<String> geojsonFactory = new GeoJSONVoronoiFactory<String>() {
};
geojsonFactory.factory(voronoiClusters);
geojsonFactory.getRoot().writeJSON(writer);
writer.close();
}
}
|
sailikhithk/tech-interview-prep
|
problems/subdomain-visit-count.py
|
#https://leetcode.com/problems/subdomain-visit-count/
class Solution(object):
def subdomainVisits(self, cpdomains):
data = collections.Counter()
return_data = []
for domain in cpdomains:
count, domain = domain.split()
count = int(count)
data[domain]+=count
sub_domain1 = domain.split('.', 1)[-1]
data[sub_domain1]+=count
if '.' in sub_domain1:
sub_domain2 = sub_domain1.split('.', 1)[-1]
data[sub_domain2]+=count
for domain, count in data.items():
return_data.append(str(count)+' '+domain)
return return_data
|
mnaboka/cosmos
|
cosmos-server/src/main/scala/com/mesosphere/cosmos/http/MediaTypeParser.scala
|
<reponame>mnaboka/cosmos
package com.mesosphere.cosmos.http
import java.util
import com.google.common.collect.Multimaps
import com.google.common.net.{MediaType => GMediaType}
import com.twitter.util.Try
import scala.collection.JavaConversions._
case class MediaTypeParseError(msg: String, cause: Throwable) extends RuntimeException(msg, cause)
object MediaTypeParser {
def parse(s: String): Try[MediaType] = {
Try {
GMediaType.parse(s)
}
.map { mediaType =>
val parameters = mediaType.parameters()
val params = Multimaps
.asMap(parameters)
.toMap
.map { case (key: String, v: util.List[String]) =>
key.toLowerCase -> v.toList.head
}
MediaType(
`type` = mediaType.`type`().toLowerCase,
subType = MediaTypeSubType.parse(mediaType.subtype()),
parameters = params
)
}
.handle {
case iae: IllegalArgumentException =>
throw new MediaTypeParseError(s"Unable to parse MediaType for input: '$s'", iae)
case ise: IllegalStateException =>
throw new MediaTypeParseError(s"Unable to parse MediaType for input: '$s'", ise)
}
}
}
|
GabrieleRolleri/competitive_programming
|
training-olinfo/annoluce/main.cpp
|
#include <bits/stdc++.h>
using namespace std;
bool funzione(int a, long double b);
int main(){
ifstream in;
in.open("input.txt");
ofstream out;
out.open("output.txt");
int nStelle;
in>>nStelle;
vector<long double> D(nStelle);
long double temp1, temp2, temp3;
for(auto it=D.begin(); it!=D.end(); it++){
in>>temp1>>temp2>>temp3;
*it=sqrt(temp1*temp1+temp2*temp2+temp3*temp3);
}
sort(D.begin(), D.end());
int nQuery;
in>>nQuery;
int temp;
for(int i=0; i<nQuery; i++){
in>>temp;
out<<upper_bound(D.begin(), D.end(), temp, funzione)-D.begin()<<endl;
}
return 0;
}
bool funzione(int a, long double b){
if(a<b)
return true;
else
return false;
}
|
Reloadly/reloadly-sdk-java
|
java-sdk-airtime/src/test/java/software/reloadly/sdk/airtime/operation/integration/AccountOperationsTest.java
|
<reponame>Reloadly/reloadly-sdk-java<gh_stars>10-100
package software.reloadly.sdk.airtime.operation.integration;
import software.reloadly.sdk.airtime.client.AirtimeAPI;
import software.reloadly.sdk.airtime.dto.response.AccountBalanceInfo;
import software.reloadly.sdk.airtime.interfaces.IntegrationTest;
import software.reloadly.sdk.core.enums.Environment;
import software.reloadly.sdk.core.internal.dto.request.interfaces.Request;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class AccountOperationsTest extends BaseIntegrationTest {
@IntegrationTest
public void testGetAccountBalance() throws Exception {
AirtimeAPI airtimeAPI = AirtimeAPI.builder().environment(Environment.LIVE).accessToken(accessToken).build();
Request<AccountBalanceInfo> request = airtimeAPI.accounts().getBalance();
assertThat(request, is(notNullValue()));
AccountBalanceInfo accountBalance = request.execute();
assertIsValidAccountBalance(accountBalance);
}
private void assertIsValidAccountBalance(AccountBalanceInfo accountBalance) {
List<String> countryFields = Arrays.asList("amount", "currencyCode", "currencyName", "updatedAt");
countryFields.forEach(field -> assertThat(accountBalance, hasProperty(field)));
assertThat(accountBalance.getAmount(), is(notNullValue()));
assertThat(accountBalance.getCurrencyCode(), is(notNullValue()));
assertThat(accountBalance.getCurrencyName(), is(notNullValue()));
assertThat(accountBalance.getUpdatedAt(), is(notNullValue()));
}
}
|
WANGXINJ/SOCharts
|
src/main/java/com/storedobject/chart/property/TextBorder.java
|
<filename>src/main/java/com/storedobject/chart/property/TextBorder.java
/*
* Copyright 2019-2020 <NAME>
* 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.storedobject.chart.property;
import static com.storedobject.chart.util.ComponentPropertyUtil.camelName;
import static com.storedobject.chart.util.ComponentPropertyUtil.nonNegativeInt;
/**
* Represents text-border. Text can be drawn with borders and the width and
* color of the border can be set.
*
* @author Syam
*/
public class TextBorder extends PropertyComponentValue {
private String prefix;
private Color color;
private Integer width;
private Shadow shadow;
/**
* Constructor.
*/
public TextBorder() {
}
@Override
protected void buildProperties() {
super.buildProperties();
property(p("borderColor"), color);
property(p("borderWidth"), width, nonNegativeInt());
property(shadow());
}
/**
* Get the color of the border.
*
* @return Color of the border.
*/
public final Color getColor() {
return color;
}
/**
* Set the color of the border.
*
* @param color Color to set.
*/
public TextBorder setColor(Color color) {
this.color = color;
return this;
}
/**
* Get the width of the border (in pixels).
*
* @return Width of the border.
*/
public final Integer getWidth() {
return width;
}
/**
* <p>
* Set the width of the border (in pixels).
* </p>
* <p>
* Note: Corner radius is not applicable for text borders.
* </p>
*
* @param width Width of the border.
*/
public TextBorder setWidth(Integer width) {
this.width = width;
return this;
}
/**
* Get the shadow.
*
* @param create Whether to create if not exists or not.
* @return Shadow.
*/
public final Shadow getShadow(boolean create) {
if (shadow == null && create) {
shadow = new Shadow();
}
return shadow;
}
/**
* Set the shadow.
*
* @param shadow Shadow.
*/
public TextBorder setShadow(Shadow shadow) {
this.shadow = shadow;
return this;
}
public TextBorder setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
private Shadow shadow() {
return shadow != null ? shadow.setPrefix(prefix) : null;
}
protected String p(String any) {
return camelName(prefix, any);
}
}
|
Andreev-Sergey/diadocsdk-cpp
|
src/protos/Timestamp.pb.h
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Timestamp.proto
#ifndef PROTOBUF_Timestamp_2eproto__INCLUDED
#define PROTOBUF_Timestamp_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace Diadoc {
namespace Api {
namespace Proto {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_Timestamp_2eproto();
void protobuf_AssignDesc_Timestamp_2eproto();
void protobuf_ShutdownFile_Timestamp_2eproto();
class Timestamp;
// ===================================================================
class Timestamp : public ::google::protobuf::Message {
public:
Timestamp();
virtual ~Timestamp();
Timestamp(const Timestamp& from);
inline Timestamp& operator=(const Timestamp& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Timestamp& default_instance();
void Swap(Timestamp* other);
// implements Message ----------------------------------------------
Timestamp* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Timestamp& from);
void MergeFrom(const Timestamp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required sfixed64 Ticks = 1;
inline bool has_ticks() const;
inline void clear_ticks();
static const int kTicksFieldNumber = 1;
inline ::google::protobuf::int64 ticks() const;
inline void set_ticks(::google::protobuf::int64 value);
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.Timestamp)
private:
inline void set_has_ticks();
inline void clear_has_ticks();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::int64 ticks_;
friend void protobuf_AddDesc_Timestamp_2eproto();
friend void protobuf_AssignDesc_Timestamp_2eproto();
friend void protobuf_ShutdownFile_Timestamp_2eproto();
void InitAsDefaultInstance();
static Timestamp* default_instance_;
};
// ===================================================================
// ===================================================================
// Timestamp
// required sfixed64 Ticks = 1;
inline bool Timestamp::has_ticks() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Timestamp::set_has_ticks() {
_has_bits_[0] |= 0x00000001u;
}
inline void Timestamp::clear_has_ticks() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Timestamp::clear_ticks() {
ticks_ = GOOGLE_LONGLONG(0);
clear_has_ticks();
}
inline ::google::protobuf::int64 Timestamp::ticks() const {
// @@protoc_insertion_point(field_get:Diadoc.Api.Proto.Timestamp.Ticks)
return ticks_;
}
inline void Timestamp::set_ticks(::google::protobuf::int64 value) {
set_has_ticks();
ticks_ = value;
// @@protoc_insertion_point(field_set:Diadoc.Api.Proto.Timestamp.Ticks)
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Proto
} // namespace Api
} // namespace Diadoc
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_Timestamp_2eproto__INCLUDED
|
alancnet/artifactory
|
storage/db/src/test/java/org/artifactory/storage/db/fs/itest/dao/NodesDaoRepoStorageSummaryTest.java
|
/*
* Artifactory is a binaries repository manager.
* Copyright (C) 2013 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.storage.db.fs.itest.dao;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.artifactory.storage.db.fs.dao.NodesDao;
import org.artifactory.storage.db.itest.DbBaseTest;
import org.artifactory.storage.fs.repo.RepoStorageSummary;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.util.Set;
import static org.fest.assertions.Assertions.assertThat;
/**
* Tests the repo summary methods of the {@link org.artifactory.storage.db.fs.dao.NodesDao}.
*
* @author <NAME>
*/
@Test
public class NodesDaoRepoStorageSummaryTest extends DbBaseTest {
@Autowired
private NodesDao nodesDao;
@BeforeClass
public void setup() {
importSql("/sql/nodes-summary.sql");
}
public void testSummary() throws SQLException {
Set<RepoStorageSummary> summaries = nodesDao.getRepositoriesStorageSummary();
assertThat(summaries).isNotEmpty().hasSize(3).containsOnly(
new RepoStorageSummary("repo1", 6, 4, 10),
new RepoStorageSummary("repo2", 4, 4, 100),
new RepoStorageSummary("repo3", 0, 0, 0) // empty repository
);
// per field and reflection equality checks
RepoStorageSummary repo1Summary = getSummaryFor("repo1", summaries);
assertThat(repo1Summary).isNotNull();
assertThat(repo1Summary.getRepoKey()).isEqualTo("repo1");
assertThat(repo1Summary.getFoldersCount()).isEqualTo(6);
assertThat(repo1Summary.getFilesCount()).isEqualTo(4);
assertThat(repo1Summary.getUsedSpace()).isEqualTo(10);
RepoStorageSummary repo2Summary = getSummaryFor("repo2", summaries);
assertThat(repo2Summary).isNotNull();
assertThat(EqualsBuilder.reflectionEquals(new RepoStorageSummary("repo2", 4, 4, 100), repo2Summary)).isTrue();
// repo with no children
RepoStorageSummary repo3Summary = getSummaryFor("repo3", summaries);
assertThat(repo3Summary).isNotNull();
assertThat(EqualsBuilder.reflectionEquals(new RepoStorageSummary("repo3", 0, 0, 0), repo3Summary)).isTrue();
}
private RepoStorageSummary getSummaryFor(String repoKey, Set<RepoStorageSummary> summaries) {
for (RepoStorageSummary summary : summaries) {
if (summary.getRepoKey().equals(repoKey)) {
return summary;
}
}
return null;
}
}
|
morrislab/plos-medicine-joint-patterns
|
scripts/data/validation/concatenate.py
|
<gh_stars>0
"""
Concatenates joint involvement data.
"""
from click import *
from logging import *
import pandas as pd
def load_data(path: str, visit: int) -> pd.DataFrame:
"""
Loads data for the given visit.
Args:
path: the path to the data
visit: the visit number
"""
info(f"Loading {path}")
X = pd.read_csv(path)
X["visit_id"] = visit
debug(f"Result: {X.shape}")
return X
@command()
@option(
"--input",
required=True,
multiple=True,
help="the CSV files to read input data from",
)
@option(
"--visit",
type=IntRange(1),
required=True,
multiple=True,
help="the visit numbers corresponding to the inputs",
)
@option("--output", required=True, help="the Feather file to write output to")
def main(input, visit, output):
if len(input) != len(visit):
raise Exception("number of --inputs must match number of --visits")
basicConfig(level=DEBUG)
# Load the data.
info("Loading and concatenating data...")
X = pd.concat(load_data(path, v) for path, v in zip(input, visit))
debug(f"Result: {X.shape}")
# Write output.
info("Writing output")
X.reset_index(drop=True).to_feather(output)
if __name__ == "__main__":
main()
|
helmutkemper/iotmaker.santa_isabel_theater.platform.webbrowser
|
canvas/strokeStyle.go
|
<filename>canvas/strokeStyle.go
package canvas
import "image/color"
// SetStrokeStyle
// en: Sets the color, gradient, or pattern used for strokes
// value: a valid JavaScript value or a color.RGBA{} struct
// Default value: #000000
//
// pt_br: Define a cor, gradiente ou padrão usado para o contorno
// value: um valor JavaScript valido ou um struct color.RGBA{}
// Valor padrão: #000000
func (el *Canvas) SetStrokeStyle(value interface{}) {
switch value.(type) {
case color.RGBA:
el.SelfContext.Set("strokeStyle", RGBAToJs(value.(color.RGBA)))
default:
el.SelfContext.Set("strokeStyle", value)
}
}
|
herbherbherb/Chess_Game
|
src/main/java/model/Board.java
|
package model;
import controller.Game_Controller;
import model.piece.*;
import view.Board_View;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Collectors;
public class Board {
public final int Board_Row;
public final int Board_Col;
protected Grid[][] board;
public Set<Piece> active_Pieces = new HashSet<>();
public boolean white_Turn;
public Board_View board_view;
public Stack<Movement> move_stack = new Stack<>();
public Game_Controller game_controller;
/**
* Constructor for Board class using default 8 * 8 dimension
*/
public Board(){
this.Board_Col = 8;
this.Board_Row = 8;
this.white_Turn = true;
board = new Grid[Board_Row][Board_Col];
for(int row = 0; row < Board_Row; row++)
for(int col = 0; col < Board_Col; col++)
board[row][col] = new Grid();
}
/**
* Constructor for Board class
* @param Input_Row Specified number of rows
* @param Input_Col Specified number pf columns
*/
public Board(int Input_Row, int Input_Col){
this.Board_Row = Input_Row;
this.Board_Col = Input_Col;
this.white_Turn = true;
board = new Grid[Board_Row][Board_Col];
for(int row = 0; row < Board_Row; row++)
for(int col = 0; col < Board_Col; col++)
board[row][col] = new Grid();
}
/**
* Initialize empty board with conventional layout
* @param black_Player
* @param white_Player
*/
public void Board_init(Player black_Player, Player white_Player, boolean has_special){
this.Add_Piece(new Rook(black_Player), 0, 7);
this.Add_Piece(new Knight(black_Player), 1, 7);
this.Add_Piece(new Bishop(black_Player), 2, 7);
this.Add_Piece(new Queen(black_Player), 3, 7);
this.Add_Piece(new King(black_Player), 4, 7);
this.Add_Piece(new Bishop(black_Player), 5, 7);
this.Add_Piece(new Knight(black_Player), 6, 7);
this.Add_Piece(new Rook(black_Player), 7, 7);
for(int row = 0; row <= 7; row++){
this.Add_Piece(new Pawn(black_Player), row, 6);
}
if(has_special){
this.Add_Piece(new Elephant(black_Player), 2, 5);
this.Add_Piece(new Cannon(black_Player), 5, 5);
}
this.Add_Piece(new Rook(white_Player), 0, 0);
this.Add_Piece(new Knight(white_Player), 1, 0);
this.Add_Piece(new Bishop(white_Player), 2, 0);
this.Add_Piece(new Queen(white_Player), 3, 0);
this.Add_Piece(new King(white_Player), 4, 0);
this.Add_Piece(new Bishop(white_Player), 5, 0);
this.Add_Piece(new Knight(white_Player), 6, 0);
this.Add_Piece(new Rook(white_Player), 7, 0);
for(int row = 0; row <= 7; row++){
this.Add_Piece(new Pawn(white_Player), row, 1);
}
if(has_special){
this.Add_Piece(new Elephant(white_Player), 2, 2);
this.Add_Piece(new Cannon(white_Player), 5, 2);
}
}
/**
* Check if the inputs are valid coordinates
* @param row input x coordinate
* @param col input y coordinate
* @return
*/
public boolean Valid_Pos(int row, int col){
if(row >= 0 && col >= 0 && row < Board_Row && col < Board_Col) return true;
return false;
}
/**
* Check if the coordinate is occupied by any pieces by any player
* @param row target coordinate x
* @param col target coordinate y
*/
public boolean Occpuied(int row, int col){
if(this.Valid_Pos(row, col) && !this.board[row][col].isEmpty()) return true;
return false;
}
/**
* @return the occupied piece @ coordinate (row, col)
*/
public Piece Occpuied_Piece(int row, int col){
if(this.Occpuied(row, col)) return this.board[row][col].piece;
else return null;
}
/**
* Designed specifically for Pawn movement,
* helper function to check if pawn can capture diagonal opponent
* @param piece Pawn piece
* @param row target coordinate x
* @param col target coordinate y
*/
public boolean Occpuied_by_Oppo(Piece piece, int row, int col){
return (this.Occpuied(row, col) && !piece.compareTo(this.Occpuied_Piece(row, col)));
}
/**
* Designed for any pieces that move by direction
* @param piece Bishop, Queen, Rook
* @param row target coordinate x
* @param col target coordinate y
* @return
*/
public boolean Occpuied_by_Friendly(Piece piece, int row, int col){
return (this.Occpuied(row, col) && piece.compareTo(this.Occpuied_Piece(row, col)));
}
/**
* Add a new piece to the board
* @param target
* @param row x coordinate to be placed in
* @param col y coordinate to be placed in
*/
public void Add_Piece(Piece target, int row, int col){
if(!this.Valid_Pos(row, col) || target == null) return;
this.active_Pieces.add(target);
this.set_Piece(target, row, col);
}
/**
* @return the piece @ coordinate (x, y)
*/
public Piece get_Piece(int x, int y){
return (this.Valid_Pos(x, y))?this.board[x][y].piece : null;
}
/**
* Set piece on a specific coordinate
* @param piece
* @param x target coordinate x to set
* @param y target coordinate y to set
*/
public void set_Piece(Piece piece, int x, int y){
if(!this.Valid_Pos(x, y) ) return;
this.board[x][y].setPiece(piece);
if(piece != null) {
// Set piece coordinate
piece.setPosition(x, y);
piece.board = this;
}
}
/**
* Remove a given piece from the board
* @param piece target piece to be removed
*/
public void remove_Piece(Piece piece){
if(piece == null) return;
remove_Piece(piece.pos_x, piece.pos_y);
}
/**
* Remove a given piece from the board
* @param x target piece coordinate x
* @param y target piece coordinate y
*/
public void remove_Piece(int x, int y){
if(!this.Valid_Pos(x, y)) return;
Piece piece = this.get_Piece(x, y);
if(piece != null) {
this.active_Pieces.remove(piece);
}
this.board[x][y].removePiece();
}
/**
* Move piece to a new location, if the piece is pawn, set isFirstMove to False
* If the target coordinate has opponent's piece, remove from global pieces set
* @param piece
* @param x target coordinate x
* @param y target coordinate y
*/
public void move(Piece piece, int x, int y){
Movement current = new Movement(this, new Coordinate(piece.pos_x, piece.pos_y), new Coordinate(x, y), this.get_Piece(x, y));
this.move_stack.push(current);
Piece target_piece = this.get_Piece(x, y);
if(target_piece != null && target_piece.piece_view != null) {
target_piece.piece_view.remove_View();
}
this.move_helper(piece, x, y);
if(piece.name.equals("Pawn")){
((Pawn)piece).isFirstMove = false;
}
if(piece != null && piece.piece_view != null) {
piece.piece_view.updateLocation();
}
this.white_Turn = !this.white_Turn;
}
/**
* Helper function for move
*/
public void move_helper(Piece piece, int x, int y){
if(piece == null) return;
if(!this.canMove(piece, x, y))
return;
this.remove_Piece(piece);
this.remove_Piece(x, y);
this.set_Piece(piece, x, y);
this.active_Pieces.add(piece);
}
/**
* Helper function when player decide to restore his previous move.
* Pop the top movement from the stack and execute.
*/
public void undo(){
if (move_stack.empty()) return;
Movement moveAtTop = move_stack.pop();
Coordinate dest = moveAtTop.dest;
Coordinate starting = moveAtTop.starting;
Piece current_piece = this.get_Piece(dest.x, dest.y);
this.move_helper(current_piece, starting.x, starting.y);
if(current_piece instanceof Pawn){
((Pawn) current_piece).isFirstMove = moveAtTop.isFirstMove;
}
Piece captured_piece = moveAtTop.captured_piece;
this.set_Piece(captured_piece, dest.x, dest.y);
if(captured_piece != null && !this.active_Pieces.contains(captured_piece)){
this.active_Pieces.add(captured_piece);
}
this.white_Turn = !this.white_Turn;
if(this.game_controller != null){
if(current_piece != null && current_piece.piece_view != null) {
current_piece.piece_view.updateLocation();
}
if(captured_piece != null && captured_piece.piece_view != null) {
captured_piece.piece_view.updateLocation();
}
this.game_controller.player_turn = this.game_controller.player_turn.equals("White")?"Black":"White";
this.game_controller.game_view.score_view.change_turn();
this.game_controller.isChecked();
this.game_controller.game_view.board_view.clear_Grid();
}
}
/**
* @param piece Current piece
* @param x target position x coordinate
* @param y target position y coordinate
* @return whether piece can move to coordinate (x, y)
*/
public boolean canMove(Piece piece, int x, int y){
// If it is not a valid position, return false;
if(!this.Valid_Pos(x, y)) return false;
Piece target = this.get_Piece(x, y);
//If the target grid is empty, return true
if(target == null) return true;
//If the current piece does NOT have the same color as target, return true
else if(!piece.compareTo(target)) return true;
else return false;
}
/**
* @param player Given player
* @return the king piece that belong to this player
*/
public Piece find_king(Player player){
if(player == null) return null;
String color = player.isBlack?"Black":"White";
for (Piece piece : this.active_Pieces) {
if(piece.color.equals(color) && piece.name.equals("King"))
return piece;
}
return null;
}
/**
* Helper function to check if a given set contains a coordinate object by values
* @param Next_Coordinate
* @param target coordinate's value to be checked with
* @return true if given set contains target coordinate by value
*/
public boolean Set_Check(Set<Coordinate>Next_Coordinate, Coordinate target){
if(target == null) return false;
int first = target.x;
int second = target.y;
for(Coordinate cur: Next_Coordinate){
if(cur.x == first && cur.y == second) return true;
}
return false;
}
/**
* @param Next_Coordinate input set to be checked
* @param first first coordinate of the target set
* @param second second coordinate of the target set
* @return true if Next_Coordinate equals target set by values
*/
public boolean Set_Check(Set<Coordinate>Next_Coordinate, int first, int second){
for(Coordinate cur: Next_Coordinate){
if(cur.x == first && cur.y == second) return true;
}
return false;
}
/**
* Check if the player is being checkmated
* @param player
* @return true is player's king is checked
*/
public boolean CheckMate(Player player){
if(player == null) return false;
Piece player_king = find_king(player);
if (player_king == null)
throw new IllegalArgumentException("King cannot be null");
Coordinate king_coordinate = new Coordinate(player_king.pos_x, player_king.pos_y);
String opponent_color = player.isBlack?"White":"Black";
for (Piece piece : this.active_Pieces) {
if(piece.color.equals(opponent_color)
&& this.Set_Check(piece.NextCoordinate(false), king_coordinate)){
return true;
}
}
return false;
}
/**
* Check if the current player is in Stalemate, player is in stalemate if it hs not valid
* action he/she can take without puting its own king in danger
* @param player Current player to check
* @return true if the player does not have any legal move left, hence, the player LOST!
*/
public boolean in_Stalemate(Player player){
if(player == null) return false;
boolean ret = true;
String color = player.isBlack?"Black":"White";
Set<Piece> active_Pieces_Copy = this.active_Pieces.stream().collect(Collectors.toSet());
for (Piece piece : active_Pieces_Copy){
if(piece.color.equals(color) && piece.NextCoordinate(true).size() != 0){
ret = false;
break;
}
}
return ret;
}
/**
* This function checks if any self-move will result checkmate
* @param piece piece to me moved
* @param x target coordinate x
* @param y target coordinate y
* @return whether it is safe to make the move
*/
public boolean valid_to_Move(Piece piece, int x, int y, boolean self_Round){
if(piece == null || !this.canMove(piece, x, y)) return false;
if(!self_Round) return true;
//*** Otherwise, check if such movement puts own king is checkmate
int prev_x = piece.pos_x; int prev_y = piece.pos_y;
Player player = piece.player;
Piece target_loc_piece = this.get_Piece(x, y);
//check if it is safe to move to the new coordinate
move_helper(piece, x, y);
boolean is_Checked = CheckMate(player);
move_helper(piece, prev_x, prev_y);
if(target_loc_piece != null) {
this.set_Piece(target_loc_piece, x, y);
this.active_Pieces.add(target_loc_piece);
}
return !is_Checked;
}
}
|
ControlThings/mist-node-api-node
|
examples/wish-app-stream-file.js
|
/**
* Copyright (C) 2020, ControlThings Oy Ab
*
* 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
*
* @license Apache-2.0
*/
//var WishApp = require('mist-api').WishApp;
var WishApp = require('../index.js').WishApp;
var Client = require('wish-rpc').Client;
var Server = require('wish-rpc').Server;
var inspect = require("util").inspect;
var repl = require('repl');
var path = require('path');
var fs = require('fs');
var bson = require('bson-buffer');
var BSON = new bson();
var white = '\u001b[37m';
var yellow = '\u001b[33m';
var green = '\u001b[34m';
var blue = '\u001b[32m';
var reset = '\u001b[39m';
function File() {
var self = this;
this.app = new WishApp({ name: process.env.SID || 'File', protocols: ['file'] });
this.peers = [];
var server = new Server({
_send: {},
send: function(req, res) {
console.log('receiving file:', req.args[0], 'size', req.args[1]);
var os = fs.createWriteStream('./'+req.args[0]);
this.data = function(data) {
//console.log('about to write', data);
os.write(data);
//console.log('receiving data for ', req.args[0], data.length);
process.stdout.write('.');
res.emit(data.length);
};
this.end = function() {
console.log('last chunk of ', req.args[0], 'received');
os.close();
};
res.emit('ok');
}
});
self.app.onlineCb = function(peer) {
peer.rpc = new Client(function(data) { self.app.send(peer, BSON.serialize(data)); });
self.peers.push(peer);
self.app.request('identity.get', [peer.ruid], function(err, user) {
console.log(reset+'online:'+blue, user.alias);
});
};
self.app.offlineCb = function(peer) {
self.app.request('identity.get', [peer.ruid], function(err, user) {
console.log(reset+'offline:'+blue, user.alias);
});
};
self.app.frameCb = function(peer, data) {
var msg = BSON.deserialize(data);
if (msg.op || msg.push || msg.end) {
server.parse(msg, function(data) { self.app.send(peer, BSON.serialize(data)); }, {});
} else {
for(var i in self.peers) {
if ( Buffer.compare(peer.luid, self.peers[i].luid) === 0
&& Buffer.compare(peer.ruid, self.peers[i].ruid) === 0
&& Buffer.compare(peer.rhid, self.peers[i].rhid) === 0
&& Buffer.compare(peer.rsid, self.peers[i].rsid) === 0 )
{
self.peers[i].rpc.messageReceived(msg);
return;
}
}
}
};
this.repl = repl.start({
prompt: "file> ",
input: process.stdin,
output: process.stdout,
terminal: true,
ignoreUndefined: true,
writer : function (obj) {
return inspect(obj, 10, null, true);
}
});
this.repl.resetContext();
this.repl.context.peers = this.peers;
this.repl.context.send = function(file) {
var rs = fs.createReadStream(file);
var id = self.peers[0].rpc.request('send', ['my-'+path.basename(file), fs.statSync(file).size], function(err, data) {
if(data ==='ok') {
rs.once('readable', function() {
self.peers[0].rpc.send(id, rs.read(16*1024));
});
rs.on('end', function() {
console.log('this is the end of the file...');
self.peers[0].rpc.end(id);
});
} else {
var chunk = rs.read(16*1024);
if (chunk === null) {
rs.once('readable', function() {
self.peers[0].rpc.send(id, rs.read(16*1024));
});
} else {
self.peers[0].rpc.send(id, chunk);
}
}
});
};
this.repl.on("exit", function () {
self.app.disconnect();
console.log("Bye!");
process.exit(0);
});
}
var file = new File();
|
jgru/memory-replay
|
src/fuzz.c
|
#include "private.h"
static bool fuzz_iterate(vmi_t *vmi, uint32_t fork_domid, uint64_t pa, uint64_t *mem, bool *stop)
{
if ( mem )
{
//uint8_t test[9] = "notbeef";
uint8_t test[9] = { [8] = '\0' };
memcpy(&test[0], mem, 8);
//printf("\t Starting test with '%s'\n ", test);
uint8_t *v = (uint8_t*)mem;
printf("\t Starting fuzz iteration with: %x%x %x%x %x%x %x%x",
v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);
if ( g_str_is_ascii((const gchar*)test) )
printf(": %s", test);
printf("\n");
if ( VMI_FAILURE == vmi_write_64_pa(vmi->libvmi, pa, (uint64_t*)mem) )
return false;
}
loop_exit_condition_t exit_cond = loop_vmi(vmi, 50, stop);
xc_dominfo_t info = { 0 };
xc_domain_getinfo(xc, fork_domid, 1, &info);
vmi_pagecache_flush(vmi->libvmi);
GTimer *timer = g_timer_new();
g_timer_start(timer);
xc_memshr_fork_reset(xc, fork_domid);
g_timer_stop(timer);
printf("\t - VM Fork memory used: %lu kbyte\n", info.nr_pages * 4096 / 1024);
printf("\t - Reset time: %f\n", g_timer_elapsed(timer, NULL));
printf("\t - Exit condition: %s\n", exit_cond_str(exit_cond));
printf("\t -------------------\n");
g_timer_destroy(timer);
return true;
}
uint64_t create_fork_and_fuzz(uint64_t domid, uint32_t vcpus, uint8_t *map, GHashTable *values, addr_t pagetable, addr_t rip, addr_t pa, addr_t va)
{
bool stop = false, fork_success;
uint32_t fork_domid = 0;
vmi_t *vmi = NULL;
code_tracer_t *code_tracer = NULL;
guint size = g_hash_table_size(values);
GTimer *timer = g_timer_new();
g_timer_start(timer);
fork_success = fork_vm(domid, vcpus, &fork_domid);
g_timer_stop(timer);
gdouble time = g_timer_elapsed(timer, NULL);
g_timer_destroy(timer);
if ( !fork_success )
goto done;
printf("[FUZZ] Fork: %u. Creation time: %f. Memory @ 0x%lx -> 0x%lx. CF: 0x%lx. Values: %u\n", fork_domid, time, va, pa, rip, size);
vmi = setup_vmi(NULL, fork_domid, NULL, true, false);
if ( !vmi )
goto done;
code_tracer = code_tracer_setup(vmi, map, &stop);
if ( !code_tracer )
goto done;
/* Record the baseline execution first without touching anything */
if ( !size )
{
printf("[FUZZ] Starting baseline execution to setup coverage map\n");
if ( code_tracer_start(code_tracer, pagetable, rip) )
fuzz_iterate(vmi, fork_domid, 0, NULL, &stop);
goto done;
}
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init (&iter, values);
while (g_hash_table_iter_next (&iter, &key, &value))
{
if ( !code_tracer_start(code_tracer, pagetable, rip) )
break;
if ( !fuzz_iterate(vmi, fork_domid, pa, key, &stop) )
break;
}
done:
code_tracer_close(code_tracer);
close_vmi(vmi);
if ( fork_domid )
xc_domain_destroy(xc, fork_domid);
return 0;
}
|
EwoutH/pik
|
pik/args.h
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
// Helpers for parsing command line arguments. No include guard needed.
#include "pik/pik_params.h" // Override
#include <stdio.h>
#include <string>
#include "pik/codec.h"
#include "pik/status.h"
namespace pik {
static inline bool ParseOverride(const char* arg, Override* out) {
const std::string s_arg(arg);
if (s_arg == "1") {
*out = Override::kOn;
return true;
}
if (s_arg == "0") {
*out = Override::kOff;
return true;
}
fprintf(stderr, "Invalid flag, %s must be 0 or 1\n", arg);
return PIK_FAILURE("Args");
}
static inline bool ParseUnsigned(const char* arg, size_t* out) {
char* end;
*out = static_cast<size_t>(strtoull(arg, &end, 0));
if (end[0] != '\0') {
fprintf(stderr, "Unable to interpret as unsigned integer: %s.\n", arg);
return PIK_FAILURE("Args");
}
return true;
}
static inline bool ParseSigned(const char* arg, int* out) {
char* end;
*out = static_cast<int>(strtol(arg, &end, 0));
if (end[0] != '\0') {
fprintf(stderr, "Unable to interpret as signed integer: %s.\n", arg);
return PIK_FAILURE("Args");
}
return true;
}
static inline bool ParseGaborishStrength(const char* arg, int* out) {
size_t strength;
if (!ParseUnsigned(arg, &strength)) return false;
if (strength >= static_cast<size_t>(GaborishStrength::kMaxValue)) {
fprintf(stderr, "Invalid GaborishStrength value: %s.\n", arg);
return PIK_FAILURE("Args");
}
*out = strength;
return true;
}
static inline bool ParseFloat(const char* arg, float* out) {
char* end;
*out = static_cast<float>(strtod(arg, &end));
if (end[0] != '\0') {
fprintf(stderr, "Unable to interpret as float: %s.\n", arg);
return PIK_FAILURE("Args");
}
return true;
}
static inline bool ParseDouble(const char* arg, double* out) {
char* end;
*out = static_cast<double>(strtod(arg, &end));
if (end[0] != '\0') {
fprintf(stderr, "Unable to interpret as double: %s.\n", arg);
return PIK_FAILURE("Args");
}
return true;
}
static inline bool ParseAndAppendKeyValue(const char* arg, DecoderHints* out) {
const char* eq = strchr(arg, '=');
if (!eq) {
fprintf(stderr, "Expected argument as 'key=value' but received '%s'\n",
arg);
return false;
}
std::string key(arg, eq);
out->Add(key, std::string(eq + 1));
return true;
}
static inline bool ParseString(const char* arg, std::string* out) {
out->assign(arg);
return true;
}
static inline bool ParseCString(const char* arg, const char** out) {
*out = arg;
return true;
}
static inline bool SetBooleanTrue(bool* out) {
*out = true;
return true;
}
static inline bool SetBooleanFalse(bool* out) {
*out = false;
return true;
}
} // namespace pik
|
Svolcano/python_exercise
|
dianhua/com/multiprocess_dama.py
|
<filename>dianhua/com/multiprocess_dama.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# ad huang
from com.connection import db
import os, time, sys
from com.logger import logger
from setting.dama2 import DAMA2_CODE
from setting.yundama_config import YUNDAMA_CODE
from setting.feifeidama import fateadm_code
from setting.dama_type import DAMA_TYPE
from com.yundama import yundama
from com.dama2 import dama2
from com.feifeidama import fateadm
from multiprocessing import Process,Pipe
import traceback
'''
dama_pad_code
err_times
priority_level
'''
def cross():
dama_cfg_info = db['dama_cfg'].find({})
for one_cfg in dama_cfg_info:
if one_cfg['priority_level']==2:
db['dama_cfg'].update({'dama_pad_code':one_cfg['dama_pad_code']},{'$set':{'priority_level':1,'err_times':0}})
elif one_cfg['priority_level']==3:
db['dama_cfg'].update({'dama_pad_code':one_cfg['dama_pad_code']},{'$set':{'priority_level':2,'err_times':0}})
elif one_cfg['priority_level']==1:
db['dama_cfg'].update({'dama_pad_code':one_cfg['dama_pad_code']},{'$set':{'priority_level':3,'err_times':0}})
return
def get_dama_pad(proc_no):
dama_cfg_info = db['dama_cfg'].find_one({'priority_level':1})
if dama_cfg_info['err_times']>=10:
cross()
elif proc_no==0:
return dama_cfg_info['dama_pad_code'],dama_cfg_info['dama_pad_code']
else:
dama_cfg_info = db['dama_cfg'].find_one({'priority_level':proc_no+1})
return dama_cfg_info['dama_pad_code'],dama_cfg_info['dama_pad_code']
return None
def __fateadm( img_data, code_type):
dama_dict = DAMA_TYPE.get(str(code_type), {})
# print dama_dict
if not dama_dict:
return 'crawl_error', u"打码类型错误:{}".format(code_type), "","__fateadm"
dama_type = dama_dict.get('channel')[2]
try:
ret, cid, result = fateadm.Predict(dama_type, img_data)
# print ret, result
if ret == 0 and result != "":
captcha_code = str(result).lower()
return 'success', captcha_code, cid,"__fateadm"
else:
fateadm.Justice(cid)
message = fateadm_code.get(str(ret), '').decode('utf-8')
if ret == "4003":
return 'crawl_error', u"打码欠费:\n{}".format(message), "","__fateadm"
return 'website_busy_error', u"打码异常:\n{}".format(message), "","__fateadm"
except:
error = traceback.format_exc()
return 'website_busy_error', u"打码异常:\n{}".format(error), "","__fateadm"
def __dama2( img_data, code_type):
dama_dict = DAMA_TYPE.get(str(code_type), {})
# print dama_dict
if not dama_dict:
return 'crawl_error', u"打码类型错误:{}".format(code_type), "","__dama2"
dama_type = dama_dict.get('channel')[0]
# print dama_type
try:
cid, result = dama2.decode(img_data, dama_type)
print cid, result
except:
error = traceback.format_exc()
return 'website_busy_error', u"打码异常:\n{}".format(error), "","__dama2"
if cid > 0 and result != "":
captcha_code = str(result).lower()
return 'success', captcha_code, cid,"__dama2"
else:
dama2.reportError(cid)
message = DAMA2_CODE.get(str(cid), '').decode('utf-8')
if cid == "-304":
return 'crawl_error', u"打码欠费:\n{}".format(message), "","__dama2"
return 'website_busy_error', u"打码异常:\n{}".format(message), "","__dama2"
def __yundama( img_data, code_type):
dama_dict = DAMA_TYPE.get(str(code_type), {})
# print dama_dict
if not dama_dict:
return 'crawl_error', u"打码类型错误:{}".format(code_type), "","__yundama"
dama_type = dama_dict.get('channel')[1]
try:
cid, result = yundama.decode(img_data, dama_type)
if cid > 0 and result != "":
captcha_code = str(result).lower()
return 'success', captcha_code, cid,"__yundama"
else:
yundama.report(cid)
message = YUNDAMA_CODE.get(str(cid), '').decode('utf-8')
if cid == "-1007":
return 'crawl_error', u"打码欠费:\n{}".format(message), "","__yundama"
return 'website_busy_error', u"打码异常:\n{}".format(message), "","__yundama"
# print code_type, cid, result
except:
error = traceback.format_exc()
return 'website_busy_error', u"打码异常:\n{}".format(error), "","__yundama"
def add_error_times(dama_pad_code):
db['dama_cfg'].update({'dama_pad_code':dama_pad_code},{'$inc':{'err_times':1}})
def init_error_times(dama_pad_code):
db['dama_cfg'].update({'dama_pad_code':dama_pad_code},{'$set':{'err_times':0}})
def dama_proccess(sid,img_data, code_type,proc_code,child_conn):
import gevent
import gevent.monkey
gevent.monkey.patch_all()
try:
dama_pad,dama_pad_code=get_dama_pad(proc_code)
if dama_pad==None:
return 'crawl_error', u"获取打码平台编号失败", "",None
dama_pad = globals().get(dama_pad)
# print (dama_pad)
task=gevent.spawn(dama_pad,img_data, code_type)
timer = gevent.Timeout(60).start()
try:
task.join(timer)
pass
except gevent.Timeout, e:
print( 'found error: thread 1 timeout.'+str(e))
child_conn.close()
add_error_times(dama_pad_code)
return False
# print task.value
if task.value[0] == 'success':
child_conn.send(task.value )
init_error_times(dama_pad_code)
child_conn.close()
else:
add_error_times(dama_pad_code)
except:
error = traceback.format_exc()
print(error)
return True
def multiprocess_dama(sid,img_data, code_type):
log_name='multiprocess_dama'
data={'sid':sid}
parent_conn,child_conn = Pipe()
begin_time=time.time()
proccess_flag=0
p1 = Process(target=dama_proccess, args=(sid,img_data, code_type,proccess_flag,child_conn,)) #申请子进程
p1.deamon = True
p1.start() #运行进程
proccess_flag=1
print ('A进程启动完毕')
data['p1']='p1'
data['A进程启动完毕']='A进程启动完毕'
while True:
end_time=time.time()
# print (end_time-begin_time)
if end_time-begin_time>20 and proccess_flag==1:
p2 = Process(target=dama_proccess, args=(sid,img_data, code_type,proccess_flag,child_conn,)) #申请子进程
p2.deamon = True
p2.start() #运行进程
proccess_flag=2
print ('B进程启动完毕')
data['B进程启动完毕']='B进程启动完毕'
data['p2']='p2'
if end_time-begin_time>40 and proccess_flag==2:
p3 = Process(target=dama_proccess, args=(sid,img_data, code_type,proccess_flag,child_conn,)) #申请子进程
p3.start() #运行进程
p3.deamon = True
proccess_flag=3
print ('C进程启动完毕')
data['C进程启动完毕']='C进程启动完毕'
data['p3']='p3'
data['proccess_flag']=proccess_flag
if parent_conn.poll():
task=parent_conn.recv()
if len(task)>2:
print ('收到管道信息'.format(task))
data['收到管道信息']=task
parent_conn.close()
child_conn.close()
logger(log_name, task[0],task[1], **data)
return task
if end_time-begin_time>60:
break
time.sleep(1)
print (end_time-begin_time)
logger(log_name, 'crawl_error','打码平台超时', **data)
return 'crawl_error', u"打码平台超时", "",None
|
pengzhuo/gameServer
|
server/models/base.py
|
# coding: utf-8
from common.constDefine import *
class Base:
"""玩家基类"""
name = None # 名称
identity = None # 身份
skills = None # 技能
isAliveFlag = True # 状态(True: 生存 False: 死亡)
die_reason = None # 死亡原因
buff = None # BUFF状态
hp = 0 # 当前生命值
max_hp = 0 # 生命值上限
def __init__(self, identity):
self.identity = identity
self.name = USER_NAME_DICT[self.identity]
def is_have_skill(self):
"""是否拥有技能"""
return False if self.skills is None else True
def is_alive(self):
"""玩家是否生存"""
return self.isAliveFlag
def do_skill(self, sid, targetId):
"""使用技能"""
pass
def die(self, reason):
"""玩家死亡"""
self.isAliveFlag = False
self.die_reason = reason
def add_buff(self, buff):
"""增加buff状态"""
self.buff = buff
|
wedataintelligence/vivaldi-source
|
chromium/content/browser/service_worker/service_worker_provider_host_unittest.cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/thread_task_runner_handle.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
#include "content/browser/service_worker/service_worker_register_job.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
class ServiceWorkerProviderHostTest : public testing::Test {
protected:
ServiceWorkerProviderHostTest()
: thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) {}
~ServiceWorkerProviderHostTest() override {}
void SetUp() override {
helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath()));
context_ = helper_->context();
script_url_ = GURL("http://www.example.com/service_worker.js");
registration1_ = new ServiceWorkerRegistration(
GURL("http://www.example.com/"), 1L, context_->AsWeakPtr());
registration2_ = new ServiceWorkerRegistration(
GURL("http://www.example.com/example"), 2L, context_->AsWeakPtr());
// Prepare provider hosts (for the same process).
scoped_ptr<ServiceWorkerProviderHost> host1(new ServiceWorkerProviderHost(
helper_->mock_render_process_id(), MSG_ROUTING_NONE,
1 /* provider_id */, SERVICE_WORKER_PROVIDER_FOR_WINDOW,
context_->AsWeakPtr(), NULL));
host1->SetDocumentUrl(GURL("http://www.example.com/example1.html"));
scoped_ptr<ServiceWorkerProviderHost> host2(new ServiceWorkerProviderHost(
helper_->mock_render_process_id(), MSG_ROUTING_NONE,
2 /* provider_id */, SERVICE_WORKER_PROVIDER_FOR_WINDOW,
context_->AsWeakPtr(), NULL));
host2->SetDocumentUrl(GURL("http://www.example.com/example2.html"));
provider_host1_ = host1->AsWeakPtr();
provider_host2_ = host2->AsWeakPtr();
context_->AddProviderHost(make_scoped_ptr(host1.release()));
context_->AddProviderHost(make_scoped_ptr(host2.release()));
}
void TearDown() override {
registration1_ = 0;
registration2_ = 0;
helper_.reset();
}
bool PatternHasProcessToRun(const GURL& pattern) const {
return context_->process_manager()->PatternHasProcessToRun(pattern);
}
content::TestBrowserThreadBundle thread_bundle_;
scoped_ptr<EmbeddedWorkerTestHelper> helper_;
ServiceWorkerContextCore* context_;
scoped_refptr<ServiceWorkerRegistration> registration1_;
scoped_refptr<ServiceWorkerRegistration> registration2_;
base::WeakPtr<ServiceWorkerProviderHost> provider_host1_;
base::WeakPtr<ServiceWorkerProviderHost> provider_host2_;
GURL script_url_;
private:
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerProviderHostTest);
};
TEST_F(ServiceWorkerProviderHostTest, PotentialRegistration_ProcessStatus) {
provider_host1_->AddMatchingRegistration(registration1_.get());
ASSERT_TRUE(PatternHasProcessToRun(registration1_->pattern()));
// Adding the same registration twice has no effect.
provider_host1_->AddMatchingRegistration(registration1_.get());
ASSERT_TRUE(PatternHasProcessToRun(registration1_->pattern()));
// Different matching registrations can be added.
provider_host1_->AddMatchingRegistration(registration2_.get());
ASSERT_TRUE(PatternHasProcessToRun(registration2_->pattern()));
// Removing a matching registration will decrease the process refs for its
// pattern.
provider_host1_->RemoveMatchingRegistration(registration1_.get());
ASSERT_FALSE(PatternHasProcessToRun(registration1_->pattern()));
// Multiple provider hosts could add the same matching registration.
// The process refs will become 0 after all provider hosts removed them.
provider_host2_->AddMatchingRegistration(registration2_.get());
provider_host1_->RemoveMatchingRegistration(registration2_.get());
ASSERT_TRUE(PatternHasProcessToRun(registration2_->pattern()));
provider_host2_->RemoveMatchingRegistration(registration2_.get());
ASSERT_FALSE(PatternHasProcessToRun(registration2_->pattern()));
}
TEST_F(ServiceWorkerProviderHostTest, AssociatedRegistration_ProcessStatus) {
// Associating the registration will also increase the process refs for
// the registration's pattern.
provider_host1_->AssociateRegistration(registration1_.get(),
false /* notify_controllerchange */);
ASSERT_TRUE(PatternHasProcessToRun(registration1_->pattern()));
// Disassociating the registration shouldn't affect the process refs for
// the registration's pattern.
provider_host1_->DisassociateRegistration();
ASSERT_TRUE(PatternHasProcessToRun(registration1_->pattern()));
}
TEST_F(ServiceWorkerProviderHostTest, MatchRegistration) {
provider_host1_->AddMatchingRegistration(registration1_.get());
provider_host1_->AddMatchingRegistration(registration2_.get());
// Match registration should return the longest matching one.
ASSERT_EQ(provider_host1_->MatchRegistration(), registration2_);
provider_host1_->RemoveMatchingRegistration(registration2_.get());
ASSERT_EQ(provider_host1_->MatchRegistration(), registration1_);
// Should return nullptr after removing all matching registrations.
provider_host1_->RemoveMatchingRegistration(registration1_.get());
ASSERT_EQ(provider_host1_->MatchRegistration(), nullptr);
}
} // namespace content
|
xyxiaoyou/snappy-store
|
gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/store/access/sort/MergeScan.java
|
/*
Derby - Class com.pivotal.gemfirexd.internal.impl.store.access.sort.MergeScan
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
*
* Portions Copyright (c) 2010-2015 <NAME>, Inc. 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. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.impl.store.access.sort;
import com.gemstone.gnu.trove.TLongArrayList;
// For JavaDoc references (i.e. @see)
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.store.access.SortObserver;
import com.pivotal.gemfirexd.internal.iapi.store.access.conglomerate.ScanManager;
import com.pivotal.gemfirexd.internal.iapi.store.access.conglomerate.TransactionManager;
import com.pivotal.gemfirexd.internal.iapi.store.raw.StreamContainerHandle;
import com.pivotal.gemfirexd.internal.iapi.store.raw.Transaction;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
/**
A sort scan that is capable of merging as many merge runs
as will fit in the passed-in sort buffer.
**/
public class MergeScan extends SortScan
{
/**
The sort buffer we will use.
**/
protected SortBuffer sortBuffer;
/**
The merge runs.
**/
protected TLongArrayList mergeRuns;
/**
Array of scan controllers for the merge runs.
Entries in the array become null as the last
row is pulled out and the scan is closed.
**/
protected StreamContainerHandle openScans[];
private final SortObserver sortObserver;
/*
* Constructors.
*/
MergeScan(
final MergeSort sort,
final TransactionManager tran,
final SortBuffer sortBuffer,
final TLongArrayList mergeRuns,
final SortObserver sortObserver,
final boolean hold)
{
super(sort, tran, hold);
this.sortBuffer = sortBuffer;
this.mergeRuns = mergeRuns;
this.tran = tran;
this.sortObserver = sortObserver;
}
/*
* Methods of MergeSortScan
*/
/**
Move to the next position in the scan.
@see com.pivotal.gemfirexd.internal.iapi.store.access.ScanController#next
**/
public boolean next()
throws StandardException
{
current = sortBuffer.removeFirst();
if (current != null)
mergeARow(sortBuffer.getLastAux());
return (current != null);
}
/**
Close the scan.
@see com.pivotal.gemfirexd.internal.iapi.store.access.ScanController#close
**/
public void close()
{
if (openScans != null)
{
for (int i = 0; i < openScans.length; i++)
{
if (openScans[i] != null)
{
openScans[i].close();
}
openScans[i] = null;
}
openScans = null;
}
// Hand sort buffer and remaining merge runs to sort.
if (super.sort != null)
{
sort.doneScanning(this, sortBuffer, mergeRuns);
sortBuffer = null;
mergeRuns = null;
}
// Sets sort to null
super.close();
}
/**
Close the scan.
@see ScanManager#closeForEndTransaction
**/
public boolean closeForEndTransaction(final boolean closeHeldScan)
{
if (!hold || closeHeldScan)
{
close();
return(true);
}
else
{
return(false);
}
}
/*
* Methods of MergeScan
*/
/**
Initialize the scan, returning false if there
was some error.
**/
public boolean init(final TransactionManager tran)
throws StandardException
{
if (SanityManager.DEBUG)
{
// We really expect to have at least one
// merge run.
SanityManager.ASSERT(mergeRuns != null);
SanityManager.ASSERT(mergeRuns.size() > 0);
// This sort scan also expects that the
// caller has ensured that the sort buffer
// capacity will hold a row from all the
// merge runs.
SanityManager.ASSERT(sortBuffer.capacity() >= mergeRuns.size());
}
// Clear the sort buffer.
sortBuffer.reset();
// Create an array to hold a scan controller
// for each merge run.
openScans = new StreamContainerHandle[mergeRuns.size()];
if (openScans == null)
return false;
// Open a scan on each merge run.
int scanindex = 0;
//final Enumeration e = mergeRuns.elements();
for (int i = 0; i < mergeRuns.size(); i++)
{
// get the container id
//final long id = ((Long) e.nextElement()).longValue();
final long id = mergeRuns.getQuick(i);
final Transaction rawTran = tran.getRawStoreXact(); // get raw transaction
final int segmentId = StreamContainerHandle.TEMPORARY_SEGMENT;
openScans[scanindex++] =
rawTran.openStreamContainer(segmentId, id, hold);
// GemStone changes BEGIN
// copy template row to observer
if (scanindex == 1) {
ExecRow templateRow = openScans[0].getTemplateRow();
if (templateRow != null) {
this.sortObserver.setTemplateRow(templateRow);
}
}
// GemStone changes END
}
// Load the initial rows.
for (scanindex = 0; scanindex < openScans.length; scanindex++)
mergeARow(scanindex);
// Success!
return true;
}
/**
Insert rows while we keep getting duplicates
from the merge run whose scan is in the
open scan array entry indexed by scanindex.
**/
void mergeARow(final int scanindex)
throws StandardException
{
if (SanityManager.DEBUG)
{
// Unless there's a bug, the scan index will refer
// to an open scan. That's because we never put
// a scan index for a closed scan into the sort
// buffer (via setNextAux).
SanityManager.ASSERT(openScans[scanindex] != null);
}
ExecRow row;
// Read rows from the merge run and stuff them into the
// sort buffer for as long as we encounter duplicates.
do
{
// GemStone changes BEGIN
// below fetch will clone in some sense (shallow/deep).
//row = sortObserver.getArrayClone();
row = sortObserver.getRowArray();
// GemStone changes END
// Fetch the row from the merge run.
if (!openScans[scanindex].fetchNext(row))
{
// If we're out of rows in the merge run, close the scan.
openScans[scanindex].close();
openScans[scanindex] = null;
return;
}
// Save the index of this merge run with
// the row we're putting in the sort buffer.
sortBuffer.setNextAux(scanindex);
}
while (sortBuffer.insert(row) == SortBuffer.INSERT_DUPLICATE);
}
}
|
SalamiArmy/TelegramSteamBotForGoogleAppEngine
|
integration_tests/integration_test_post.py
|
<reponame>SalamiArmy/TelegramSteamBotForGoogleAppEngine
# coding=utf-8
import unittest
from google.appengine.ext import ndb
from google.appengine.ext import testbed
import main
class TestPost(unittest.TestCase):
def setUp(self):
# First, create an instance of the Testbed class.
self.testbed = testbed.Testbed()
# Then activate the testbed, which prepares the service stubs for use.
self.testbed.activate()
# Next, declare which service stubs you want to use.
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
self.testbed.init_user_stub()
# Clear ndb's in-context cache between tests.
# This prevents data from leaking between tests.
# Alternatively, you could disable caching by
# using ndb.get_context().set_cache_policy(False)
ndb.get_context().clear_cache()
def integration_test_translate_post(self):
newRequestObject = main.WebhookHandler()
class Object(object):
pass
newRequestObject.request = Object()
newRequestObject.request.body = '{"message": {"from": {"username": "SalamiArmy", "first_name": "Ashley", "last_name": "Lewis"}, "text": "/game R.I.V.E", "chat": {"id": -55348600, "type": "group"}}}'
newRequestObject.response = Object()
newRequestObject.response.write = lambda x: None
newRequestObject.post()
|
seba-m/University-Projects
|
Third year/Primer Semestre/Proyecto inventariado/Servidor/src/main/java/com/pruebas/modelo/configuraciones/SecurityConfig.java
|
<reponame>seba-m/University-Projects<gh_stars>1-10
package com.pruebas.modelo.configuraciones;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.pruebas.modelo.tokens.JWTAuthorizationFilter;
import com.pruebas.modelo.usuario.UserService;
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${aws.access}")
private String accessKey;
@Value("${aws.secret}")
private String secretKey;
@Value("${aws.region}")
private String region;
@Autowired
private UserService userService;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JWTAuthorizationFilter jtwAuthorizationFilter() {
return new JWTAuthorizationFilter();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Bean
public BasicAWSCredentials basicAWSCredentials() {
return new BasicAWSCredentials(accessKey, secretKey);
}
@Bean
public AmazonS3 s3(AWSCredentials awsCredentials) {
AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
builder.withCredentials(new AWSStaticCredentialsProvider(awsCredentials));
builder.setRegion(region);
return builder.build();
}
/*-
@Bean
public AmazonS3 s3() {
AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
return AmazonS3ClientBuilder.standard().withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();
}
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
// .addFilterAfter(new JWTAuthorizationFilter(),
// UsernamePasswordAuthenticationFilter.class)
.authorizeRequests().antMatchers(HttpMethod.POST, "/api/v1/signup").permitAll()
.antMatchers(HttpMethod.POST, "/api/v1/login").permitAll()
.antMatchers(HttpMethod.POST, "/api/v1/forgot").permitAll()
.antMatchers(HttpMethod.POST, "/api/v1/productos/**", "/api/v1/tags/**").authenticated()
.antMatchers(HttpMethod.GET, "/api/v1/productos/**", "/api/v1/tags/**").authenticated()
.antMatchers(HttpMethod.PUT, "/api/v1/productos/**", "/api/v1/tags/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/api/v1/productos/**", "/api/v1/tags/**").authenticated()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')").antMatchers("/app/**")
.access("hasRole('ROLE_USER')").antMatchers("/**").permitAll().anyRequest().authenticated().and()
.formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/", true)
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
if (authentication.isAuthenticated()
&& authentication.getAuthorities().toString().contains("USER")) {
response.sendRedirect("/app");
} else if (authentication.isAuthenticated()
&& authentication.getAuthorities().toString().contains("ADMIN")) {
response.sendRedirect("/admin");
} /*- else if (authentication.isAuthenticated() && authentication.getAuthorities().toString().contains("CANCELED")) {
response.sendRedirect("/login?banned");
}*/
}
}).and().logout().invalidateHttpSession(true).clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout")
.permitAll();
/*-
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);*/
http.addFilterBefore(jtwAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
|
rugameuser/mpd-tools
|
parser/src/main/java/io/lindstrom/mpd/data/MPD.java
|
<filename>parser/src/main/java/io/lindstrom/mpd/data/MPD.java
package io.lindstrom.mpd.data;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import io.lindstrom.mpd.data.descriptor.Descriptor;
import io.lindstrom.mpd.support.Utils;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Objects;
@JsonPropertyOrder({
"programInformations",
"baseURLs",
"locations",
"periods",
"metrics",
"essentialProperties",
"supplementalProperties",
"utcTimings"
})
@JacksonXmlRootElement(localName = "MPD", namespace = io.lindstrom.mpd.data.MPD.NAMESPACE)
public class MPD {
static final String NAMESPACE = "urn:mpeg:dash:schema:mpd:2011";
@JacksonXmlProperty(localName = "ProgramInformation", namespace = NAMESPACE)
private final List<ProgramInformation> programInformations;
@JacksonXmlProperty(localName = "BaseURL", namespace = NAMESPACE)
private final List<BaseURL> baseURLs;
@JacksonXmlProperty(localName = "Location", namespace = NAMESPACE)
private final List<String> locations;
@JacksonXmlProperty(localName = "Period", namespace = NAMESPACE)
private final List<Period> periods;
@JacksonXmlProperty(localName = "Metrics", namespace = NAMESPACE)
private final List<Metrics> metrics;
@JacksonXmlProperty(localName = "EssentialProperty", namespace = NAMESPACE)
private final List<Descriptor> essentialProperties;
@JacksonXmlProperty(localName = "SupplementalProperty", namespace = NAMESPACE)
private final List<Descriptor> supplementalProperties;
@JacksonXmlProperty(localName = "UTCTiming", namespace = NAMESPACE)
private final List<UTCTiming> utcTimings;
@JacksonXmlProperty(isAttribute = true, namespace = "http://www.w3.org/2001/XMLSchema-instance")
private final String schemaLocation;
@JacksonXmlProperty(isAttribute = true)
private final String id;
@JacksonXmlProperty(isAttribute = true)
private final Profiles profiles;
@JacksonXmlProperty(isAttribute = true)
private final PresentationType type;
@JacksonXmlProperty(isAttribute = true)
private final OffsetDateTime availabilityStartTime;
@JacksonXmlProperty(isAttribute = true)
private final OffsetDateTime availabilityEndTime;
@JacksonXmlProperty(isAttribute = true)
private final OffsetDateTime publishTime;
@JacksonXmlProperty(isAttribute = true)
private final Duration mediaPresentationDuration;
@JacksonXmlProperty(isAttribute = true)
private final Duration minimumUpdatePeriod;
@JacksonXmlProperty(isAttribute = true)
private final Duration minBufferTime;
@JacksonXmlProperty(isAttribute = true)
private final Duration timeShiftBufferDepth;
@JacksonXmlProperty(isAttribute = true)
private final Duration suggestedPresentationDelay;
@JacksonXmlProperty(isAttribute = true)
private final Duration maxSegmentDuration;
@JacksonXmlProperty(isAttribute = true)
private final Duration maxSubsegmentDuration;
private MPD(String schemaLocation, List<ProgramInformation> programInformations, List<BaseURL> baseURLs, List<String> locations,
List<Period> periods, List<Metrics> metrics, List<Descriptor> essentialProperties,
List<Descriptor> supplementalProperties, List<UTCTiming> utcTimings, String id,
Profiles profiles, PresentationType type, OffsetDateTime availabilityStartTime,
OffsetDateTime availabilityEndTime, OffsetDateTime publishTime, Duration mediaPresentationDuration,
Duration minimumUpdatePeriod, Duration minBufferTime, Duration timeShiftBufferDepth,
Duration suggestedPresentationDelay, Duration maxSegmentDuration, Duration maxSubsegmentDuration) {
this.schemaLocation = schemaLocation;
this.programInformations = programInformations;
this.baseURLs = baseURLs;
this.locations = locations;
this.periods = periods;
this.metrics = metrics;
this.essentialProperties = essentialProperties;
this.supplementalProperties = supplementalProperties;
this.utcTimings = utcTimings;
this.id = id;
this.profiles = profiles;
this.type = type;
this.availabilityStartTime = availabilityStartTime;
this.availabilityEndTime = availabilityEndTime;
this.publishTime = publishTime;
this.mediaPresentationDuration = mediaPresentationDuration;
this.minimumUpdatePeriod = minimumUpdatePeriod;
this.minBufferTime = minBufferTime;
this.timeShiftBufferDepth = timeShiftBufferDepth;
this.suggestedPresentationDelay = suggestedPresentationDelay;
this.maxSegmentDuration = maxSegmentDuration;
this.maxSubsegmentDuration = maxSubsegmentDuration;
}
@SuppressWarnings("unused")
private MPD() {
this.programInformations = null;
this.baseURLs = null;
this.locations = null;
this.periods = null;
this.metrics = null;
this.essentialProperties = null;
this.supplementalProperties = null;
this.utcTimings = null;
this.id = null;
this.profiles = null;
this.type = null;
this.availabilityStartTime = null;
this.availabilityEndTime = null;
this.publishTime = null;
this.mediaPresentationDuration = null;
this.minimumUpdatePeriod = null;
this.minBufferTime = null;
this.timeShiftBufferDepth = null;
this.suggestedPresentationDelay = null;
this.maxSegmentDuration = null;
this.maxSubsegmentDuration = null;
this.schemaLocation = null;
}
public List<ProgramInformation> getProgramInformations() {
return Utils.unmodifiableList(programInformations);
}
public List<BaseURL> getBaseURLs() {
return Utils.unmodifiableList(baseURLs);
}
public List<String> getLocations() {
return Utils.unmodifiableList(locations);
}
public List<Period> getPeriods() {
return Utils.unmodifiableList(periods);
}
public List<Metrics> getMetrics() {
return Utils.unmodifiableList(metrics);
}
public List<Descriptor> getEssentialProperties() {
return Utils.unmodifiableList(essentialProperties);
}
public List<Descriptor> getSupplementalProperties() {
return Utils.unmodifiableList(supplementalProperties);
}
public List<UTCTiming> getUtcTimings() {
return Utils.unmodifiableList(utcTimings);
}
public String getId() {
return id;
}
public List<Profile> getProfiles() {
if (profiles == null) {
return List.of();
} else {
return profiles.getProfiles();
}
}
public List<String> getInteroperabilityPointsAndExtensions() {
if (profiles == null) {
return List.of();
} else {
return profiles.getInteroperabilityPointsAndExtensions();
}
}
public PresentationType getType() {
return type;
}
public OffsetDateTime getAvailabilityStartTime() {
return availabilityStartTime;
}
public OffsetDateTime getAvailabilityEndTime() {
return availabilityEndTime;
}
public OffsetDateTime getPublishTime() {
return publishTime;
}
public Duration getMediaPresentationDuration() {
return mediaPresentationDuration;
}
public Duration getMinimumUpdatePeriod() {
return minimumUpdatePeriod;
}
public Duration getMinBufferTime() {
return minBufferTime;
}
public Duration getTimeShiftBufferDepth() {
return timeShiftBufferDepth;
}
public Duration getSuggestedPresentationDelay() {
return suggestedPresentationDelay;
}
public Duration getMaxSegmentDuration() {
return maxSegmentDuration;
}
public Duration getMaxSubsegmentDuration() {
return maxSubsegmentDuration;
}
public String getSchemaLocation() {
return schemaLocation;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MPD mpd = (MPD) o;
return Objects.equals(programInformations, mpd.programInformations) &&
Objects.equals(baseURLs, mpd.baseURLs) &&
Objects.equals(locations, mpd.locations) &&
Objects.equals(periods, mpd.periods) &&
Objects.equals(metrics, mpd.metrics) &&
Objects.equals(essentialProperties, mpd.essentialProperties) &&
Objects.equals(supplementalProperties, mpd.supplementalProperties) &&
Objects.equals(utcTimings, mpd.utcTimings) &&
Objects.equals(id, mpd.id) &&
Objects.equals(profiles, mpd.profiles) &&
type == mpd.type &&
Objects.equals(availabilityStartTime, mpd.availabilityStartTime) &&
Objects.equals(availabilityEndTime, mpd.availabilityEndTime) &&
Objects.equals(publishTime, mpd.publishTime) &&
Objects.equals(mediaPresentationDuration, mpd.mediaPresentationDuration) &&
Objects.equals(minimumUpdatePeriod, mpd.minimumUpdatePeriod) &&
Objects.equals(minBufferTime, mpd.minBufferTime) &&
Objects.equals(timeShiftBufferDepth, mpd.timeShiftBufferDepth) &&
Objects.equals(suggestedPresentationDelay, mpd.suggestedPresentationDelay) &&
Objects.equals(maxSegmentDuration, mpd.maxSegmentDuration) &&
Objects.equals(maxSubsegmentDuration, mpd.maxSubsegmentDuration) &&
Objects.equals(schemaLocation, mpd.schemaLocation);
}
@Override
public int hashCode() {
return Objects.hash(programInformations, baseURLs, locations, periods, metrics, essentialProperties, supplementalProperties, utcTimings, id, profiles, type, availabilityStartTime, availabilityEndTime, publishTime, mediaPresentationDuration, minimumUpdatePeriod, minBufferTime, timeShiftBufferDepth, suggestedPresentationDelay, maxSegmentDuration, maxSubsegmentDuration, schemaLocation);
}
@Override
public String toString() {
return "MPD{" +
"programInformations=" + programInformations +
", baseURLs=" + baseURLs +
", locations=" + locations +
", periods=" + periods +
", metrics=" + metrics +
", essentialProperties=" + essentialProperties +
", supplementalProperties=" + supplementalProperties +
", utcTimings=" + utcTimings +
", id='" + id + '\'' +
", profiles='" + profiles + '\'' +
", type=" + type +
", availabilityStartTime=" + availabilityStartTime +
", availabilityEndTime=" + availabilityEndTime +
", publishTime=" + publishTime +
", mediaPresentationDuration=" + mediaPresentationDuration +
", minimumUpdatePeriod=" + minimumUpdatePeriod +
", minBufferTime=" + minBufferTime +
", timeShiftBufferDepth=" + timeShiftBufferDepth +
", suggestedPresentationDelay=" + suggestedPresentationDelay +
", maxSegmentDuration=" + maxSegmentDuration +
", maxSubsegmentDuration=" + maxSubsegmentDuration +
", schemaLocation='" + schemaLocation + '\'' +
'}';
}
public Builder buildUpon() {
return new Builder()
.withProgramInformations(programInformations)
.withBaseURLs(baseURLs)
.withLocations(locations)
.withPeriods(periods)
.withMetrics(metrics)
.withEssentialProperties(essentialProperties)
.withSupplementalProperties(supplementalProperties)
.withUtcTimings(utcTimings)
.withId(id)
.withProfiles(profiles)
.withType(type)
.withAvailabilityStartTime(availabilityStartTime)
.withAvailabilityEndTime(availabilityEndTime)
.withPublishTime(publishTime)
.withMediaPresentationDuration(mediaPresentationDuration)
.withMinimumUpdatePeriod(minimumUpdatePeriod)
.withMinBufferTime(minBufferTime)
.withTimeShiftBufferDepth(timeShiftBufferDepth)
.withSuggestedPresentationDelay(suggestedPresentationDelay)
.withMaxSegmentDuration(maxSegmentDuration)
.withMaxSubsegmentDuration(maxSubsegmentDuration)
.withSchemaLocation(schemaLocation);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private static final String DEFAULT_SCHEMA_LOCATION = "urn:mpeg:dash:schema:mpd:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd";
private List<ProgramInformation> programInformations;
private List<BaseURL> baseURLs;
private List<String> locations;
private List<Period> periods;
private List<Metrics> metrics;
private List<Descriptor> essentialProperties;
private List<Descriptor> supplementalProperties;
private List<UTCTiming> utcTimings;
private String id;
private Profiles profiles;
private PresentationType type;
private OffsetDateTime availabilityStartTime;
private OffsetDateTime availabilityEndTime;
private OffsetDateTime publishTime;
private Duration mediaPresentationDuration;
private Duration minimumUpdatePeriod;
private Duration minBufferTime;
private Duration timeShiftBufferDepth;
private Duration suggestedPresentationDelay;
private Duration maxSegmentDuration;
private Duration maxSubsegmentDuration;
private String schemaLocation;
public Builder() {
this.schemaLocation = DEFAULT_SCHEMA_LOCATION;
this.type = PresentationType.STATIC;
this.minBufferTime = Duration.ZERO;
}
public Builder withProgramInformations(List<ProgramInformation> programInformations) {
this.programInformations = programInformations;
return this;
}
public Builder withBaseURLs(List<BaseURL> baseURLs) {
this.baseURLs = baseURLs;
return this;
}
public Builder withLocations(List<String> locations) {
this.locations = locations;
return this;
}
public Builder withPeriods(List<Period> periods) {
this.periods = periods;
return this;
}
public Builder withPeriods(Period period, Period ...morePeriods) {
this.periods = Utils.varargsToList(period, morePeriods);
return this;
}
public Builder withMetrics(List<Metrics> metrics) {
this.metrics = metrics;
return this;
}
public Builder withEssentialProperties(List<Descriptor> essentialProperties) {
this.essentialProperties = essentialProperties;
return this;
}
public Builder withSupplementalProperties(List<Descriptor> supplementalProperties) {
this.supplementalProperties = supplementalProperties;
return this;
}
public Builder withUtcTimings(List<UTCTiming> utcTimings) {
this.utcTimings = utcTimings;
return this;
}
public Builder withUtcTimings(UTCTiming utcTiming, UTCTiming ...moreUtcTiming) {
this.utcTimings = Utils.varargsToList(utcTiming, moreUtcTiming);
return this;
}
public Builder withId(String id) {
this.id = id;
return this;
}
public Builder withProfiles(Profiles profiles) {
this.profiles = profiles;
return this;
}
public Builder withProfiles(Profile profile, Profile ...moreProfiles) {
if (this.profiles == null) {
this.profiles = new Profiles();
}
this.profiles = this.profiles.buildUpon()
.withProfiles(Utils.varargsToList(profile, moreProfiles))
.build();
return this;
}
public Builder withInteroperabilityPointsAndExtensions(String value, String ...moreValues) {
if (this.profiles == null) {
this.profiles = new Profiles();
}
this.profiles = this.profiles.buildUpon()
.withInteroperabilityPointsAndExtensions(Utils.varargsToList(value, moreValues))
.build();
return this;
}
public Builder withType(PresentationType type) {
this.type = type;
return this;
}
public Builder withAvailabilityStartTime(OffsetDateTime availabilityStartTime) {
this.availabilityStartTime = availabilityStartTime;
return this;
}
public Builder withAvailabilityEndTime(OffsetDateTime availabilityEndTime) {
this.availabilityEndTime = availabilityEndTime;
return this;
}
public Builder withPublishTime(OffsetDateTime publishTime) {
this.publishTime = publishTime;
return this;
}
public Builder withMediaPresentationDuration(Duration mediaPresentationDuration) {
this.mediaPresentationDuration = mediaPresentationDuration;
return this;
}
public Builder withMinimumUpdatePeriod(Duration minimumUpdatePeriod) {
this.minimumUpdatePeriod = minimumUpdatePeriod;
return this;
}
public Builder withMinBufferTime(Duration minBufferTime) {
this.minBufferTime = minBufferTime;
return this;
}
public Builder withTimeShiftBufferDepth(Duration timeShiftBufferDepth) {
this.timeShiftBufferDepth = timeShiftBufferDepth;
return this;
}
public Builder withSuggestedPresentationDelay(Duration suggestedPresentationDelay) {
this.suggestedPresentationDelay = suggestedPresentationDelay;
return this;
}
public Builder withMaxSegmentDuration(Duration maxSegmentDuration) {
this.maxSegmentDuration = maxSegmentDuration;
return this;
}
public Builder withMaxSubsegmentDuration(Duration maxSubsegmentDuration) {
this.maxSubsegmentDuration = maxSubsegmentDuration;
return this;
}
public Builder withSchemaLocation(String schemaLocation) {
this.schemaLocation = schemaLocation;
return this;
}
public MPD build() {
return new MPD(schemaLocation, programInformations, baseURLs, locations, periods, metrics, essentialProperties, supplementalProperties, utcTimings, id, profiles, type, availabilityStartTime, availabilityEndTime, publishTime, mediaPresentationDuration, minimumUpdatePeriod, minBufferTime, timeShiftBufferDepth, suggestedPresentationDelay, maxSegmentDuration, maxSubsegmentDuration);
}
}
}
|
haraisao/fcl
|
test/narrowphase/detail/primitive_shape_algorithm/test_sphere_cylinder.cpp
|
<filename>test/narrowphase/detail/primitive_shape_algorithm/test_sphere_cylinder.cpp
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2018. Toyota Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of CNRS-LAAS and AIST nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** @author <NAME> (<EMAIL>) (2018) */
// Tests the custom sphere-cylinder tests: distance and collision.
#include "fcl/narrowphase/detail/primitive_shape_algorithm/sphere_cylinder-inl.h"
#include <sstream>
#include <string>
#include <gtest/gtest.h>
#include "eigen_matrix_compare.h"
#include "fcl/geometry/shape/cylinder.h"
#include "fcl/geometry/shape/sphere.h"
namespace fcl {
namespace detail {
namespace {
// In the worst case (with arbitrary frame orientations) it seems like I'm
// losing about 4 bits of precision in the solution (compared to performing
// the equivalent query without any rotations). This encodes that bit loss to
// an epsilon value appropriate to the scalar type.
//
// TODO(SeanCurtis-TRI): These eps values are *not* optimal. They are the result
// of a *number* of issues.
// 1. Generally, for float the scalar must be at least 20 * ε. The arbitrary
// rotation *really* beats up on the precision.
// 2. CI uses Eigen 3.2.0. The threshold must be 22 * ε for the tests to pass.
// This is true, even for doubles. Later versions (e.g., 3.2.92, aka
// 3.3-beta1) can pass with a tolerance of 16 * ε.
// 3. Mac CI requires another bump in the multiplier for floats. So, floats here
// are 24.
// Upgrade the Eigen version so that this tolerance can be reduced.
template <typename S>
struct Eps {
using Real = typename constants<S>::Real;
static Real value() { return 22 * constants<S>::eps(); }
};
template <>
struct Eps<float> {
using Real = typename constants<float>::Real;
static Real value() { return 24 * constants<float>::eps(); }
};
// Utility function for evaluating points inside cylinders. Tests various
// configurations of points and cylinders.
template <typename S> void NearestPointInCylinder() {
// Picking sizes that are *not* powers of two and *not* uniform in size.
const S r = 0.6;
const S h = 1.8;
Vector3<S> p_CN;
Vector3<S> p_CQ;
// Case: query point at origin.
p_CQ << 0, 0, 0;
bool N_is_not_S = nearestPointInCylinder(h, r, p_CQ, &p_CN);
EXPECT_FALSE(N_is_not_S) << "point at origin";
EXPECT_TRUE(CompareMatrices(p_CN, p_CQ, 0, MatrixCompareType::absolute))
<< "point at origin";
// Per cylinder-half tests (i.e., above and below the z = 0 plane).
for (S z_sign : {-1, 1}) {
for (const auto& dir : {Vector3<S>(1, 0, 0),
Vector3<S>(0, 1, 0),
Vector3<S>(1, 1, 0).normalized(),
Vector3<S>(-1, 2, 0).normalized(),
Vector3<S>(1, -2, 0).normalized(),
Vector3<S>(-2, -3, 0).normalized()}) {
const Vector3<S> z_offset_internal{0, 0, h * S(0.5) * z_sign};
const Vector3<S> z_offset_external{0, 0, h * S(1.5) * z_sign};
const Vector3<S> radial_offset_internal = dir * (r * S(0.5));
const Vector3<S> radial_offset_external = dir * (r * S(1.5));
using std::to_string;
std::stringstream ss;
ss << "dir: " << dir.transpose() << ", z: " << z_sign;
const std::string parameters = ss.str();
// Case: point inside (no clamped values).
p_CQ = radial_offset_internal + z_offset_internal;
N_is_not_S = nearestPointInCylinder(h, r, p_CQ, &p_CN);
EXPECT_FALSE(N_is_not_S) << "Sphere at origin - " << parameters;
EXPECT_TRUE(
CompareMatrices(p_CN, p_CQ, 0, MatrixCompareType::absolute))
<< "Sphere at origin - " << parameters;
// Case: clamped only by the barrel.
p_CQ = radial_offset_external + z_offset_internal;
N_is_not_S = nearestPointInCylinder(h, r, p_CQ, &p_CN);
EXPECT_TRUE(N_is_not_S)
<< "Clamped by barrel - " << parameters;
const Vector3<S> point_on_barrel = z_offset_internal + dir * r;
EXPECT_NEAR(point_on_barrel(0), p_CN(0), Eps<S>::value())
<< "Clamped by barrel - " << parameters;
EXPECT_NEAR(point_on_barrel(1), p_CN(1), Eps<S>::value())
<< "Clamped by barrel - " << parameters;
EXPECT_EQ(p_CQ(2), p_CN(2))
<< "Clamped by barrel - " << parameters;
// Case: clamped only by the end face.
p_CQ = radial_offset_internal + z_offset_external;
N_is_not_S = nearestPointInCylinder(h, r, p_CQ, &p_CN);
EXPECT_TRUE(N_is_not_S) << "Clamped by end face - " << parameters;
EXPECT_EQ(p_CQ(0), p_CN(0)) << "Clamped by end face - " << parameters;
EXPECT_EQ(p_CQ(1), p_CN(1)) << "Clamped by end face - " << parameters;
EXPECT_EQ(0.5 * h * z_sign, p_CN(2)) << "Clamped by end face - "
<< parameters;
// Case: clamped by both end face and barrel.
p_CQ = radial_offset_external + z_offset_external;
N_is_not_S = nearestPointInCylinder(h, r, p_CQ, &p_CN);
EXPECT_TRUE(N_is_not_S) << "Fully clamped - " << parameters;
EXPECT_NEAR(point_on_barrel(0), p_CN(0), Eps<S>::value())
<< "Fully clamped - " << parameters;
EXPECT_NEAR(point_on_barrel(1), p_CN(1), Eps<S>::value())
<< "Fully clamped - " << parameters;
EXPECT_EQ(0.5 * h * z_sign, p_CN(2)) << "Fully clamped - "
<< parameters;
}
}
}
// Defines the test configuration for a single test. It includes the geometry
// and the pose of the sphere in the cylinder's frame C. It also includes the
// expected answers in that same frame. It does not include those quantities
// that vary from test invocation to invocation (e.g., the pose of the cylinder
// in the world frame or the *orientation* of the sphere).
//
// Collision and distance are complementary queries -- two objects in collision
// have no defined distance because they are *not* separated and vice versa.
// These configurations allow for the test of the complementarity property.
template <typename S>
struct TestConfiguration {
TestConfiguration(const std::string& name_in, const S& r_c_in,
const S& h_c_in, const S& r_s_in,
const Vector3<S> &p_CSo_in, bool colliding)
: name(name_in),
cylinder_half_len(h_c_in / 2),
r_c(r_c_in),
r_s(r_s_in),
p_CSo(p_CSo_in),
expected_colliding(colliding) {}
// Descriptive name of the test configuration.
std::string name;
// Half the length of the cylinder along the z-axis.
S cylinder_half_len;
// Radius of the cylinder.
S r_c;
// Radius of the sphere.
S r_s;
// Position of the sphere's center in the cylinder frame.
Vector3<S> p_CSo;
// Indicates if this test configuration is expected to be in collision.
bool expected_colliding{false};
// Collision values; only valid if expected_colliding is true.
S expected_depth{-1};
Vector3<S> expected_normal;
Vector3<S> expected_pos;
// Distance values; only valid if expected_colliding is false.
S expected_distance{-1};
// The points on sphere and cylinder, respectively, closest to the other shape
// measured and expressed in the cylinder frame C. Only defined if separated.
Vector3<S> expected_p_CSc;
Vector3<S> expected_p_CCs;
};
// Utility for creating a copy of the input configurations and appending more
// labels to the configuration name -- aids in debugging.
template <typename S>
std::vector<TestConfiguration<S>> AppendLabel(
const std::vector<TestConfiguration<S>>& configurations,
const std::string& label) {
std::vector<TestConfiguration<S>> configs;
for (const auto& config : configurations) {
configs.push_back(config);
configs.back().name += " - " + label;
}
return configs;
}
// Returns a collection of configurations where sphere and cylinder are similar
// in size.
template <typename S>
std::vector<TestConfiguration<S>> GetUniformConfigurations() {
std::vector<TestConfiguration<S>> configurations;
// Common configuration values
// Cylinder and sphere dimensions.
const S h_c = 0.6;
const S half_h_c = h_c / 2;
const S r_c = 1.2;
const S r_s = 0.7;
const bool collides = true;
// Collection of directions parallel to the z = 0 plane. Used for sampling
// queries in various directions around the barrel. Note: for the tests to be
// correct, these normals must all have unit length and a zero z-component.
std::vector<Vector3<S>> barrel_directions{
Vector3<S>{1, 0, 0},
Vector3<S>{0, 1, 0},
Vector3<S>(1, S(0.5), 0).normalized(),
Vector3<S>(-1, S(0.5), 0).normalized(),
Vector3<S>(-1, -S(0.5), 0).normalized(),
Vector3<S>(1, -S(0.5), 0).normalized()};
{
// Case: Completely separated. Nearest point on the +z face.
const Vector3<S> p_CS{r_c * S(0.25), r_c * S(0.25),
half_h_c + r_s * S(1.1)};
configurations.emplace_back(
"Separated; nearest face +z", r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = p_CS(2) - half_h_c - r_s;
config.expected_p_CCs = Vector3<S>{p_CS(0), p_CS(1), half_h_c};
config.expected_p_CSc = Vector3<S>{p_CS(0), p_CS(1), p_CS(2) - r_s};
}
{
// Case: Sphere completely separated with center in barrel Voronoi region.
const S target_distance = 0.1;
const Vector3<S> n_SC = Vector3<S>{-1, -1, 0}.normalized();
const Vector3<S> p_CS = Vector3<S>{0, 0, half_h_c * S(0.5)} -
n_SC * (r_s + r_c + target_distance);
configurations.emplace_back(
"Separated; near barrel", r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = target_distance;
config.expected_p_CCs = -n_SC * r_c + Vector3<S>{0, 0, p_CS(2)};
config.expected_p_CSc = p_CS + n_SC * r_s;
}
{
// Case: Sphere completely separated with center in *edge* Voronoi region.
const S target_distance = .1;
const Vector3<S> n_SC = Vector3<S>{-1, -1, -1}.normalized();
const Vector3<S> p_CCs = Vector3<S>{0, 0, half_h_c} +
Vector3<S>{-n_SC(0), -n_SC(1), 0}.normalized() * r_c;
const Vector3<S> p_CS = p_CCs - n_SC * (r_s + target_distance);
configurations.emplace_back(
"Separated; near barrel edge", r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = target_distance;
config.expected_p_CCs = p_CCs;
config.expected_p_CSc = p_CS + n_SC * r_s;
}
using std::min;
const S target_depth = min(r_c, r_s) * S(0.25);
// Case contact - sphere center outside cylinder.
// Sub-cases intersection *only* through cap face; one test for each face.
for (S sign : {S(-1), S(1)}) {
const Vector3<S> n_SC = Vector3<S>::UnitZ() * -sign;
const Vector3<S> p_CCs = Vector3<S>{r_c * S(0.25), r_c * S(0.25),
half_h_c * sign};
const Vector3<S> p_CS = p_CCs - n_SC * (r_s - target_depth);
configurations.emplace_back(
"Colliding external sphere center; cap face in " +
(sign < 0 ? std::string("-z") : std::string("+z")),
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = n_SC;
config.expected_pos = p_CCs + n_SC * (target_depth / 2);
// Colliding; no distance values required.
}
// Sub-cases intersection *only* through barrel. Sampled in multiple
// directions.
for (const Vector3<S>& n_CS : barrel_directions) {
const Vector3<S> p_CCs = Vector3<S>{0, 0, half_h_c * S(.1)} +
n_CS * r_c;
const Vector3<S> p_CS = p_CCs + n_CS * (r_s - target_depth);
std::stringstream ss;
ss << "Colliding external sphere center; barrel from sphere center in"
<< n_CS.transpose() << " direction";
configurations.emplace_back(ss.str(), r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -n_CS;
config.expected_pos = p_CCs - n_CS * (target_depth / 2);
// Colliding; no distance values required.
}
// Sub-cases intersection through edge.
for (S sign : {S(-1), S(1)}) {
// Projection of vector from cylinder center to sphere center on the z=0
// plane (and then normalized).
for (const Vector3<S>& n_CS_xy : barrel_directions) {
const Vector3<S> p_CCs = Vector3<S>{0, 0, sign * half_h_c} +
n_CS_xy * r_c;
const Vector3<S> n_CS = p_CCs.normalized();
const Vector3<S> p_CS = p_CCs + n_CS * (r_s - target_depth);
std::stringstream ss;
ss << "Colliding external sphere center; edge from sphere center in"
<< n_CS.transpose() << " direction";
configurations.emplace_back(ss.str(), r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -n_CS;
config.expected_pos = p_CCs - n_CS * (target_depth / 2);
// Colliding; no distance values required.
}
}
// Case contact - sphere center *inside* cylinder.
// Sub-cases: sphere is unambiguously closest to end face. One test for each
// end face.
for (S sign : {S(-1), S(1)}) {
// Distance from sphere center S to face F.
const S d_SF = 0.1;
const Vector3<S> n_SC = Vector3<S>::UnitZ() * -sign;
const Vector3<S> p_CCs = Vector3<S>{r_c * S(0.25), r_c * S(0.25),
half_h_c * sign};
const Vector3<S> p_CS = p_CCs + n_SC * d_SF;
configurations.emplace_back(
"Colliding internal sphere center; cap face in " +
(sign < 0 ? std::string("-z") : std::string("+z")),
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = d_SF + r_s;
config.expected_normal = n_SC;
config.expected_pos = p_CCs + n_SC * (config.expected_depth / 2);
// Colliding; no distance values required.
}
// Sub-cases: sphere is unambiguously closest to barrel; sampling multiple
// directions.
for (const Vector3<S>& n_CS : barrel_directions) {
// Distance from sphere center S to point B on barrel.
const S d_SB = 0.1;
const Vector3<S> p_CCs = Vector3<S>{0, 0, half_h_c * S(.1)} +
n_CS * r_c;
const Vector3<S> p_CS = p_CCs - n_CS * d_SB;
std::stringstream ss;
ss << "Colliding internal sphere center; barrel from sphere located in "
<< n_CS.transpose() << " direction";
configurations.emplace_back(ss.str(), r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r_s + d_SB;
config.expected_normal = -n_CS;
config.expected_pos = p_CCs - n_CS * (config.expected_depth / 2);
// Colliding; no distance values required.
}
// Case contact - sphere center is *near* error-dominated regions
// Sub-case: Sphere center is within epsilon *outside* of end face.
// Numerically, this is processed as if the center were inside the cylinder.
// For face contact, there's no difference. This test subsumes the test where
// the center lies *on* the surface of the cylinder.
for (S sign : {S(-1), S(1)}) {
// Distance from sphere center S to face F.
const S d_SF = Eps<S>::value() / 2;
const Vector3<S> n_SC = Vector3<S>::UnitZ() * -sign;
const Vector3<S> p_CCs = Vector3<S>{r_c * S(0.25), r_c * S(0.25),
half_h_c * sign};
const Vector3<S> p_CS = p_CCs - n_SC * d_SF;
configurations.emplace_back(
"Colliding sphere center outside by ε; cap face in " +
(sign < 0 ? std::string("-z") : std::string("+z")),
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r_s;
config.expected_normal = n_SC;
config.expected_pos = p_CCs + n_SC * (config.expected_depth / 2);
// Colliding; no distance values required.
}
// Sub-case: Sphere center is within epsilon *outside* of barrel.
// Numerically, this is processed as if the center were inside the cylinder.
// For barrel contact, there's no difference. This test subsumes the test
// where the center lies *on* the surface of the cylinder.
for (const Vector3<S>& n_CS : barrel_directions) {
// Distance from sphere center S to point B on barrel.
const S d_SB = Eps<S>::value() / 2;
const Vector3<S> p_CCs = Vector3<S>{0, 0, half_h_c * S(.1)} +
n_CS * r_c;
const Vector3<S> p_CS = p_CCs - n_CS * d_SB;
std::stringstream ss;
ss << "Colliding sphere center outside by ε; barrel from sphere located in "
<< n_CS.transpose() << " direction";
configurations.emplace_back(ss.str(), r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r_s;
config.expected_normal = -n_CS;
config.expected_pos = p_CCs - n_CS * (config.expected_depth / 2);
// Colliding; no distance values required.
}
// Sub-case: Sphere center is within epsilon *outside* of edge.
// Numerically, this is processed as if the center were inside the cylinder.
// If the center is in the Voronoi region of the edge, the reported normal
// will be either the face or the barrel -- whichever is closer. In this
// configuration, it is the face normal. This test subsumes the test where
// the center lies *on* the surface of the cylinder.
for (S sign : {S(-1), S(1)}) {
// Projection of vector from cylinder center to sphere center on the z=0
// plane (and then normalized).
const S d_SC = Eps<S>::value() / 2;
for (const Vector3<S>& n_CS_xy : barrel_directions) {
const Vector3<S> p_CCs = Vector3<S>{0, 0, sign * half_h_c} +
n_CS_xy * r_c;
const Vector3<S> n_CS = p_CCs.normalized();
const Vector3<S> p_CS = p_CCs + n_CS * d_SC;
std::stringstream ss;
ss << "Colliding sphere center outside by ε; edge from sphere center in"
<< n_CS.transpose() << " direction";
configurations.emplace_back(ss.str(), r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r_s;
// NOTE: Epsilon *outside* is considered inside so the normal direction
// will be either face or barrel -- and, in this case, it's face.
config.expected_normal = -sign * Vector3<S>::UnitZ();
config.expected_pos = p_CCs + config.expected_normal * (r_s / 2);
// Colliding; no distance values required.
}
}
{
// Sub-case: Sphere center is on origin - face is closer. It should prefer
// the +z face.
const Vector3<S> p_CS = Vector3<S>::Zero();
// Guarantee that the barrel is farther than the face.
const S big_radius = h_c * 2;
configurations.emplace_back(
"Collision with sphere at origin; face nearest", big_radius, h_c, r_s,
p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r_s + h_c / 2;
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_pos = Vector3<S>{0, 0, h_c / 2 - config.expected_depth / 2};
// Colliding; no distance values required.
}
{
// Sub-case: Sphere center is on origin - barrel is closer.
const Vector3<S> p_CS = Vector3<S>::Zero();
// Guarantee that the barrel is closer than the face.
const S big_height = r_c * 4;
configurations.emplace_back(
"Collision with sphere at origin; barrel nearest", r_c, big_height, r_s,
p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r_s + r_c;
config.expected_normal = -Vector3<S>::UnitX();
config.expected_pos = Vector3<S>{r_c - config.expected_depth / 2, 0, 0};
// Colliding; no distance values required.
}
return configurations;
}
// Returns a collection of configurations where sphere and cylinder are scaled
// very differently.
template <typename S>
std::vector<TestConfiguration<S>> GetNonUniformConfigurations() {
std::vector<TestConfiguration<S>> configurations;
// Case: Large, flat cylinder and tiny sphere.
{
const S r_c = 9;
const S h_c = 0.1;
const S r_s = 0.025;
const bool collides = true;
const S target_depth = r_s / 2;
// Sub-case: Colliding -- contact with +z face.
{
// Colliding sub-case.
const Vector3<S> p_CCs = Vector3<S>(1, 2, 0).normalized() * (r_c - r_s) +
Vector3<S>::UnitZ() * (h_c / 2);
const Vector3<S> p_CS{p_CCs + Vector3<S>::UnitZ() * (r_s - target_depth)};
configurations.emplace_back(
"Collision large disk, small sphere - contact at face",
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_pos = p_CCs - Vector3<S>::UnitZ() * (target_depth / 2);
// Colliding; no distance values required.
}
// Sub-case: Separated -- nearest feature +z face.
{
// Separated sub-case.
const Vector3<S> p_CCs = Vector3<S>(1, 2, 0).normalized() * (r_c - r_s) +
Vector3<S>::UnitZ() * (h_c / 2);
const Vector3<S> p_CS{p_CCs +
Vector3<S>::UnitZ() * (r_s + target_depth)};
configurations.emplace_back(
"Separation large disk, small sphere - nearest +z face",
r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = target_depth;
config.expected_p_CCs = p_CCs;
config.expected_p_CSc = p_CS - Vector3<S>::UnitZ() * r_s;
}
// Sub-case: Colliding -- contact with barrel.
const Vector3<S> n_CS = Vector3<S>(1, 2, 0).normalized();
const Vector3<S> p_CCs = n_CS * r_c + Vector3<S>::UnitZ() * (r_s * 0.1);
{
// Colliding sub-case.
const Vector3<S> p_CS{p_CCs + n_CS * (r_s - target_depth)};
configurations.emplace_back(
"Collision large disk, small sphere - contact at barrel",
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -n_CS;
config.expected_pos = p_CCs - n_CS * (target_depth / 2);
// Colliding; no distance values required.
}
// Sub-case: Separated -- nearest feature is barrel.
{
// Separated sub-case.
const Vector3<S> p_CS{p_CCs + n_CS * (r_s + target_depth)};
configurations.emplace_back(
"Separation large disk, small sphere - nearest barrel",
r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = target_depth;
config.expected_p_CCs = p_CCs;
config.expected_p_CSc = p_CS - n_CS * r_s;
}
}
// Case: Large sphere and *tiny* cylinder.
{
const S r_c = 0.025;
const S h_c = 0.1;
const S r_s = 9;
const bool collides = true;
const S target_depth = r_c / 2;
// Sub-case -- nearest feature is +z face.
{
const Vector3<S> p_CCs =
Vector3<S>(1, 2, 0).normalized() * (r_c * S(0.5)) +
Vector3<S>::UnitZ() * (h_c / 2);
// Sub-case: Colliding.
{
const Vector3<S>
p_CS{p_CCs + Vector3<S>::UnitZ() * (r_s - target_depth)};
configurations.emplace_back(
"Collision large sphere, small disk - contact at face",
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_pos = p_CCs - Vector3<S>::UnitZ() * (target_depth / 2);
// Colliding; no distance values required.
}
// Subsub-case: Separated
{
const Vector3<S> p_CS{p_CCs +
Vector3<S>::UnitZ() * (r_s + target_depth)};
configurations.emplace_back(
"Separation large sphere, small disk - nearest +z face",
r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = target_depth;
config.expected_p_CCs = p_CCs;
config.expected_p_CSc = p_CS - Vector3<S>::UnitZ() * r_s;
}
}
// Sub-case: Nearest feature is barrel
{
const Vector3<S> n_CS = Vector3<S>(1, 2, 0).normalized();
const Vector3<S> p_CCs = n_CS * r_c + Vector3<S>::UnitZ() * (h_c * 0.1);
// Subsub-case: Colliding.
{
const Vector3<S> p_CS{p_CCs + n_CS * (r_s - target_depth)};
configurations.emplace_back(
"Collision large sphere, small disk - contact at barrel",
r_c, h_c, r_s, p_CS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -n_CS;
config.expected_pos = p_CCs - n_CS * (target_depth / 2);
// Colliding; no distance values required.
}
// Subsub-case: Separated .
{
const Vector3<S> p_CS{p_CCs + n_CS * (r_s + target_depth)};
configurations.emplace_back(
"Separation large sphere, small disk - nearest barrel",
r_c, h_c, r_s, p_CS, !collides);
TestConfiguration<S>& config = configurations.back();
// Not colliding --> no collision values.
config.expected_distance = target_depth;
config.expected_p_CCs = p_CCs;
config.expected_p_CSc = p_CS - n_CS * r_s;
}
}
}
return configurations;
}
template <typename S>
using EvalFunc =
std::function<void(const TestConfiguration<S>&, const Transform3<S>&,
const Matrix3<S>&, S)>;
// This evaluates an instance of a test configuration and confirms the results
// match the expected data. The test configuration is defined in the cylinder's
// frame with an unrotated sphere. The parameters provide the test parameters:
// the sphere orientation and the cylinder's pose in the world frame.
//
// Evaluates the collision query twice. Once as the boolean "is colliding" test
// and once with the collision characterized with depth, normal, and position.
template <typename S>
void EvalCollisionForTestConfiguration(const TestConfiguration<S>& config,
const Transform3<S>& X_WC,
const Matrix3<S>& R_CS,
S eps) {
// Set up the experiment from input parameters and test configuration.
Cylinder<S> cylinder(config.r_c, config.cylinder_half_len * S(2));
Sphere<S> sphere{config.r_s};
Transform3<S> X_CS = Transform3<S>::Identity();
X_CS.translation() = config.p_CSo;
X_CS.linear() = R_CS;
Transform3<S> X_WS = X_WC * X_CS;
bool colliding = sphereCylinderIntersect<S>(sphere, X_WS, cylinder, X_WC,
nullptr);
EXPECT_EQ(config.expected_colliding, colliding) << config.name;
std::vector<ContactPoint<S>> contacts;
colliding = sphereCylinderIntersect<S>(sphere, X_WS, cylinder, X_WC, &contacts);
EXPECT_EQ(colliding, config.expected_colliding) << config.name;
if (config.expected_colliding) {
EXPECT_EQ(1u, contacts.size()) << config.name;
const ContactPoint<S> &contact = contacts[0];
EXPECT_NEAR(config.expected_depth, contact.penetration_depth, eps)
<< config.name;
EXPECT_TRUE(CompareMatrices(contact.normal,
X_WC.linear() * config.expected_normal, eps,
MatrixCompareType::absolute))
<< config.name;
EXPECT_TRUE(CompareMatrices(contact.pos, X_WC * config.expected_pos, eps,
MatrixCompareType::absolute))
<< config.name;
} else {
EXPECT_EQ(contacts.size(), 0u) << config.name;
}
}
// This evaluates an instance of a test configuration and confirms the results
// match the expected data. The test configuration is defined in the cylinder's
// frame with an unrotated sphere. The parameters provide the test
// configuration.
//
// Evaluates the distance query twice. Once as the boolean "is separated" test
// and once with the separation characterized with distance and surface points.
template <typename S>
void EvalDistanceForTestConfiguration(const TestConfiguration<S>& config,
const Transform3<S>& X_WC,
const Matrix3<S>& R_CS,
S eps) {
// Set up the experiment from input parameters and test configuration.
Cylinder<S> cylinder(config.r_c, config.cylinder_half_len * S(2));
Sphere<S> sphere{config.r_s};
Transform3<S> X_CS = Transform3<S>::Identity();
X_CS.translation() = config.p_CSo;
X_CS.linear() = R_CS;
Transform3<S> X_WS = X_WC * X_CS;
bool separated = sphereCylinderDistance<S>(sphere, X_WS, cylinder, X_WC,
nullptr, nullptr, nullptr);
EXPECT_NE(separated, config.expected_colliding) << config.name;
// Initializing this to -2, to confirm that a non-colliding scenario sets
// distance to -1.
S distance{-2};
Vector3<S> p_WSc{0, 0, 0};
Vector3<S> p_WCs{0, 0, 0};
separated = sphereCylinderDistance<S>(sphere, X_WS, cylinder, X_WC, &distance,
&p_WSc, &p_WCs);
EXPECT_NE(separated, config.expected_colliding) << config.name;
if (!config.expected_colliding) {
EXPECT_NEAR(distance, config.expected_distance, eps)
<< config.name;
EXPECT_TRUE(CompareMatrices(p_WSc,
X_WC * config.expected_p_CSc, eps,
MatrixCompareType::absolute))
<< config.name;
EXPECT_TRUE(CompareMatrices(p_WCs,
X_WC * config.expected_p_CCs, eps,
MatrixCompareType::absolute))
<< config.name;
} else {
EXPECT_EQ(distance, S(-1)) << config.name;
EXPECT_TRUE(CompareMatrices(p_WSc, Vector3<S>::Zero(), 0,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(p_WCs, Vector3<S>::Zero(), 0,
MatrixCompareType::absolute));
}
}
// This test defines the transforms for performing the single collision test.
template <typename S>
void QueryWithVaryingWorldFrames(
const std::vector<TestConfiguration<S>>& configurations,
EvalFunc<S> query_eval, const Matrix3<S>& R_CS = Matrix3<S>::Identity()) {
// Evaluate all the configurations with the given cylinder pose in frame F.
auto evaluate_all = [&R_CS, query_eval](
const std::vector<TestConfiguration<S>>& configs,
const Transform3<S>& X_FC) {
for (const auto config : configs) {
query_eval(config, X_FC, R_CS, Eps<S>::value());
}
};
// Frame F is coincident and aligned with the cylinder frame.
Transform3<S> X_FC = Transform3<S>::Identity();
evaluate_all(AppendLabel(configurations, "X_FC = I"), X_FC);
// Simple arbitrary translation away from the origin.
X_FC.translation() << 1.3, 2.7, 6.5;
evaluate_all(AppendLabel(configurations, "X_FC is translation"), X_FC);
std::string axis_name[] = {"x", "y", "z"};
// 90 degree rotation around each axis.
for (int axis = 0; axis < 3; ++axis) {
std::string label = "X_FC is 90-degree rotation around " + axis_name[axis];
AngleAxis<S> angle_axis{constants<S>::pi() / 2, Vector3<S>::Unit(axis)};
X_FC.linear() << angle_axis.matrix();
evaluate_all(AppendLabel(configurations, label), X_FC);
}
// Arbitrary orientation.
{
AngleAxis<S> angle_axis{constants<S>::pi() / 3,
Vector3<S>{1, 2, 3}.normalized()};
X_FC.linear() << angle_axis.matrix();
evaluate_all(AppendLabel(configurations, "X_FC is arbitrary rotation"),
X_FC);
}
// Near axis aligned.
{
AngleAxis<S> angle_axis{constants<S>::eps_12(), Vector3<S>::UnitX()};
X_FC.linear() << angle_axis.matrix();
evaluate_all(AppendLabel(configurations, "X_FC is near identity"),
X_FC);
}
}
// Runs all test configurations across multiple poses in the world frame --
// changing the orientation of the sphere -- should have no affect on the
// results.
template <typename S>
void QueryWithOrientedSphere(
const std::vector<TestConfiguration<S>>& configurations,
EvalFunc<S> query_eval) {
std::string axis_name[] = {"x", "y", "z"};
// 90 degree rotation around each axis.
for (int axis = 0; axis < 3; ++axis) {
AngleAxis<S> angle_axis{constants<S>::pi() / 2, Vector3<S>::Unit(axis)};
std::string label = "sphere rotate 90-degrees around " + axis_name[axis];
QueryWithVaryingWorldFrames<S>(AppendLabel(configurations, label),
query_eval, angle_axis.matrix());
}
// Arbitrary orientation.
{
AngleAxis<S> angle_axis{constants<S>::pi() / 3,
Vector3<S>{1, 2, 3}.normalized()};
std::string label = "sphere rotated arbitrarily";
QueryWithVaryingWorldFrames<S>(AppendLabel(configurations, label),
query_eval, angle_axis.matrix());
}
// Near axis aligned.
{
AngleAxis<S> angle_axis{constants<S>::eps_12(), Vector3<S>::UnitX()};
std::string label = "sphere rotated near axes";
QueryWithVaryingWorldFrames<S>(AppendLabel(configurations, label),
query_eval, angle_axis.matrix());
}
}
//======================================================================
// Tests the helper function that finds the closest point in the cylinder.
GTEST_TEST(SphereCylinderPrimitiveTest, NearestPointInCylinder) {
NearestPointInCylinder<float>();
NearestPointInCylinder<double>();
}
// Evaluates collision on all test configurations across multiple poses in the
// world frame - but the sphere rotation is always the identity.
GTEST_TEST(SphereCylinderPrimitiveTest, CollisionAcrossVaryingWorldFrames) {
QueryWithVaryingWorldFrames<float>(GetUniformConfigurations<float>(),
EvalCollisionForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(
GetUniformConfigurations<double>(),
EvalCollisionForTestConfiguration<double>);
}
// Evaluates collision on all test configurations across multiple poses in the
// world frame - the sphere is rotated arbitrarily.
GTEST_TEST(SphereCylinderPrimitiveTest, CollisionWithSphereRotations) {
QueryWithOrientedSphere<float>(GetUniformConfigurations<float>(),
EvalCollisionForTestConfiguration<float>);
QueryWithOrientedSphere<double>(GetUniformConfigurations<double>(),
EvalCollisionForTestConfiguration<double>);
}
// Evaluates collision on a small set of configurations where the cylinder and
// sphere are of radically different scales - evaluation across multiple poses
// in the world frame.
GTEST_TEST(SphereCylinderPrimitiveTest, CollisionIncompatibleScales) {
QueryWithVaryingWorldFrames<float>(GetNonUniformConfigurations<float>(),
EvalCollisionForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(
GetNonUniformConfigurations<double>(),
EvalCollisionForTestConfiguration<double>);
}
// Evaluates distance on all test configurations across multiple poses in the
// world frame - but the sphere rotation is always the identity.
GTEST_TEST(SphereCylinderPrimitiveTest, DistanceAcrossVaryingWorldFrames) {
QueryWithVaryingWorldFrames<float>(GetUniformConfigurations<float>(),
EvalDistanceForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(GetUniformConfigurations<double>(),
EvalDistanceForTestConfiguration<double>);
}
// Evaluates distance on all test configurations across multiple poses in the
// world frame - the sphere is rotated arbitrarily.
GTEST_TEST(SphereCylinderPrimitiveTest, DistanceWithSphereRotations) {
QueryWithOrientedSphere<float>(GetUniformConfigurations<float>(),
EvalDistanceForTestConfiguration<float>);
QueryWithOrientedSphere<double>(GetUniformConfigurations<double>(),
EvalDistanceForTestConfiguration<double>);
}
// Evaluates distance on a small set of configurations where the cylinder and
// sphere are of radically different scales - evaluation across multiple poses
// in the world frame.
GTEST_TEST(SphereCylinderPrimitiveTest, DistanceIncompatibleScales) {
QueryWithVaryingWorldFrames<float>(GetNonUniformConfigurations<float>(),
EvalDistanceForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(GetNonUniformConfigurations<double>(),
EvalDistanceForTestConfiguration<double>);
}
} // namespace
} // namespace detail
} // namespace fcl
//==============================================================================
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
grantgarrett/grantgarrett-design
|
src/components/suggest-case-study/suggest-new-case-study.js
|
<gh_stars>1-10
import React from "react"
import GoToInvision from "./go-to-invision"
import GoToInquicker from "./go-to-inquicker"
import GoToSprinklr from "./go-to-sprinklr"
import GoToSightbox from "./go-to-sightbox"
//Components
import LinkArrow from "../ui/LinkArrow"
const SuggestNewCaseStudy = (props) => {
return (
<section className="suggest-new-case-study">
<div className="case-study-grid">
<div className="thanks-for-reading g3-7">
<h3>Thanks for reading!</h3>
<p>
If you’d like to read more about my thoughts on design or my
approach and process check out my other case studies.
</p>
<LinkArrow url={"/"} label={"Portfolio Home"} theme={"default"} arrowDirectionForward={false} />
</div>
<div className="g1-5 cs-item">
{(() => {
switch (props.linkone) {
case "sprinklr": return <GoToSprinklr />;
case "sightbox": return <GoToSightbox />;
case "inquicker": return <GoToInquicker />;
case "invision": return <GoToInvision />;
default: return <GoToSprinklr />;
}
})()}
</div>
<div className="g5-9 cs-item">
{(() => {
switch (props.linktwo) {
case "sprinklr": return <GoToSprinklr />;
case "sightbox": return <GoToSightbox />;
case "inquicker": return <GoToInquicker />;
case "invision": return <GoToInvision />;
default: return <GoToSprinklr />;
}
})()}
</div>
</div>
</section>
);
}
export default SuggestNewCaseStudy;
|
Matt-Dub/HISE
|
tools/snex_playground/test_files/basic/if_false.h
|
/*
BEGIN_TEST_DATA
f: main
ret: float
args: int
input: 0
output: 2.0
error: ""
filename: "basic/if_false"
END_TEST_DATA
*/
float value = 2.0f;
float main(int input)
{
if (input == 0)
{
return value;
}
else
{
return value;
}
}
|
nimile/Balance-Shoe
|
doc/esp32/html/search/defines_3.js
|
var searchData=
[
['device_5fname_75',['DEVICE_NAME',['../_e_s_p32_8c.html#a5f5a2c9450ebc584b4fe743c6b1a280b',1,'ESP32.c']]],
['dout_5fpin_76',['DOUT_PIN',['../_e_s_p32_8c.html#ade0fb7dd3abd429354e0715d25f3d03a',1,'ESP32.c']]]
];
|
rtlayzell/rush
|
include/rush/ast/decls/prototype.hpp
|
<reponame>rtlayzell/rush<filename>include/rush/ast/decls/prototype.hpp<gh_stars>1-10
/*************************************************************************
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*************************************************************************/
#pragma once
#ifndef RUSH_AST_DECLS_PROTOTYPE_HPP
#define RUSH_AST_DECLS_PROTOTYPE_HPP
#include "rush/ast/types/type_ref.hpp"
#include <string>
namespace rush::ast {
class prototype_declaration {
public:
prototype_declaration(
std::string name,
ast::type_ref ret_type,
std::vector<ast::type_ref> param_types)
: _name { std::move(name) }
, _ret_type { ret_type }
, _param_type { std::move(param_types) } {}
virtual void attached(ast::scope& scope, ast::context& context) override {
_type = context.function_type(*this);
if (auto type = std::get_if<ast::type_ref>(&_type))
_type = ast::resolve_named_types(*type, scope, context);
}
virtual void detached(ast::context&) override {
_type = types::undefined;
detach(*_params);
detach(*_body);
}
private:
std::string _name;
ast::type_ref _type;
std::vector<ast::type_ref
};
namespace decls {
std::unique_ptr<ast::prototype_declaration>
} // decls
} // rush::ast
#endif // RUSH_AST_DECLS_PROTOTYPE_HPP
|
zwliew/ctci
|
solutions/leetcode/product-of-array-except-self/main.py
|
from typing import List
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
result = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
result[i] = result[i - 1] * nums[i - 1]
cur_prod = 1
for i in range(len(nums) - 2, -1, -1):
cur_prod *= nums[i + 1]
result[i] *= cur_prod
return result
|
indunet/fastproto
|
src/main/java/org/indunet/fastproto/TypeAssist.java
|
/*
* Copyright 2019-2021 indunet.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.indunet.fastproto;
import lombok.*;
import org.indunet.fastproto.annotation.*;
import org.indunet.fastproto.annotation.type.AutoType;
import org.indunet.fastproto.decoder.DecodeContext;
import org.indunet.fastproto.decoder.TypeDecoder;
import org.indunet.fastproto.encoder.EncodeContext;
import org.indunet.fastproto.encoder.TypeEncoder;
import org.indunet.fastproto.exception.*;
import org.indunet.fastproto.pipeline.AbstractFlow;
import org.indunet.fastproto.pipeline.ValidationContext;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.reflect.*;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Type assist.
*
* @author <NAME>
* @since 1.0.0
*/
@Getter
@Setter
@Builder
@AllArgsConstructor
public class TypeAssist {
protected static ConcurrentHashMap<Class<?>, TypeAssist> typeAssists = new ConcurrentHashMap<>();
protected final static ThreadLocal<Object> instance = new ThreadLocal<>();
protected static final ThreadLocal<Map<Class<?>, Object>> objects = new ThreadLocal<>();
protected static final ThreadLocal<Set<Class<?>>> protocolClasses = new ThreadLocal<>();
TypeAssist parent;
Class<?> clazz;
Field field;
Annotation typeAnnotation;
EndianPolicy endianPolicy;
Boolean decodeIgnore;
Boolean encodeIgnore;
ElementType elementType;
List<TypeAssist> elements;
Class<? extends TypeDecoder> decoderClass;
Class<? extends TypeEncoder> encoderClass;
Class<? extends Function> decodeFormula;
Class<? extends Function> encodeFormula;
Function<DecodeContext, ?> decoder;
Consumer<?> encoder;
Integer fixedLength;
EnableCrypto enableCrypto;
byte[] key;
EnableCompress enableCompress;
EnableProtocolVersion enableProtocolVersion;
EnableChecksum enableChecksum;
Boolean circularReference = false;
Integer byteOffset;
Integer bitOffset;
Integer size;
Integer length;
long codecFeature;
Boolean noArgsConstructor;
protected TypeAssist() {
}
public static TypeAssist byClass(Class<?> protocolClass) {
return typeAssists.computeIfAbsent(protocolClass, c -> TypeAssist.get(c));
}
public static TypeAssist get(@NonNull Class<?> protocolClass) {
protocolClasses.set(new HashSet<>());
TypeAssist assist = resolveClass(protocolClass);
// Crypto policy and key.
val enableCrypto = Optional.of(protocolClass)
.map(c -> c.getAnnotation(EnableCrypto.class))
.orElse(null);
assist.setEnableCrypto(enableCrypto);
if (enableCrypto != null) {
if (!enableCrypto.key().isEmpty()) {
assist.setKey(
enableCrypto.key().getBytes());
} else if (enableCrypto.keySupplier().length != 0) {
assist.setKey(Optional.of(enableCrypto)
.map(EnableCrypto::keySupplier)
.map(a -> {
try {
val c = a[0];
return c.newInstance()
.get();
} catch (InstantiationException | IllegalAccessException e) {
throw new CryptoException(CodecError.INVALID_CRYPTO_KEY_SUPPLIER, e);
}
}).get()
);
} else {
throw new CryptoException(CodecError.NO_CRYPTO_KEY);
}
}
assist.setEnableCompress(Optional.of(protocolClass)
.map(c -> c.getAnnotation(EnableCompress.class))
.orElse(null));
assist.setEnableProtocolVersion(Optional.of(protocolClass)
.map(c -> c.getAnnotation(EnableProtocolVersion.class))
.orElse(null));
assist.setEnableChecksum(Optional.of(protocolClass)
.map(c -> c.getAnnotation(EnableChecksum.class))
.orElse(null));
assist.setFixedLength(Optional.of(protocolClass)
.map(c -> c.getAnnotation(EnableFixedLength.class))
.map(EnableFixedLength::value)
.orElse(null));
assist.setCodecFeature(CodecFeature.of(assist));
protocolClasses.remove();
return assist;
}
protected static TypeAssist resolveClass(@NonNull Class<?> protocolClass) {
protocolClasses.get().add(protocolClass);
// Constructor flag
val noArgsConstructor = Arrays.stream(protocolClass.getConstructors())
.anyMatch(c -> c.getParameterCount() == 0);
Predicate<Field> isType = f -> Arrays.stream(f.getAnnotations())
.map(Annotation::annotationType)
.anyMatch(t -> t.isAnnotationPresent(TypeFlag.class));
// Nested types.
Stream<TypeAssist> typeStream = Arrays.stream(protocolClass.getDeclaredFields())
.filter(f -> !f.isAnnotationPresent(DecodeIgnore.class)
&& !f.isAnnotationPresent(EncodeIgnore.class))
.filter(isType.negate())
.filter(f -> !f.getType().isEnum()) // Non enum.
// .filter(f -> !Modifier.isFinal(f.getModifiers())) // Non final.
.filter(f -> !Modifier.isTransient(f.getModifiers())) // Non transient.
.filter(f -> !f.getType().isArray()) // Non array.
.filter(f -> f.getType() instanceof Class)
.filter(f -> Arrays.stream(ProtocolType.supportedTypes())
.noneMatch(t -> t == f.getType()))
.map(f -> {
f.setAccessible(true);
Class<?> c = f.getType();
if (protocolClasses.get().contains(c)) {
Boolean decodeIgnore = f.isAnnotationPresent(DecodeIgnore.class);
return TypeAssist.builder()
.clazz(c)
.field(f)
.typeAnnotation(null)
.decoderClass(null)
.encoderClass(null)
.decodeFormula(null)
.encodeFormula(null)
.endianPolicy(EndianPolicy.LITTLE)
.decodeIgnore(decodeIgnore)
.encodeIgnore(true)
.elementType(ElementType.TYPE)
.circularReference(true)
.elements(new ArrayList<TypeAssist>())
.build();
} else {
TypeAssist a = TypeAssist.resolveClass(c);
Boolean decodeIgnore = f.isAnnotationPresent(DecodeIgnore.class);
Boolean encodeIgnore = f.isAnnotationPresent(EncodeIgnore.class);
a.setDecodeIgnore(decodeIgnore);
a.setEncodeIgnore(encodeIgnore);
a.setField(f);
a.setCircularReference(false);
return a;
}
})
.filter(a -> a.hasElement() || a.getCircularReference());
// Default as little endian.
EndianPolicy endianPolicy = Optional.ofNullable(protocolClass.getAnnotation(Endian.class))
.map(Endian::value)
.orElse(EndianPolicy.LITTLE);
Boolean decodeIgnore = protocolClass.isAnnotationPresent(DecodeIgnore.class);
Boolean encodeIgnore = protocolClass.isAnnotationPresent(EncodeIgnore.class);
Stream<TypeAssist> fieldStream = Arrays.stream(protocolClass.getDeclaredFields())
.filter(f -> !f.isAnnotationPresent(DecodeIgnore.class)
&& !f.isAnnotationPresent(EncodeIgnore.class))
.filter(isType)
.peek(f -> f.setAccessible(true))
.map(TypeAssist::resolveField)
.peek(a -> {
if (a.getEndianPolicy() == null) {
a.setEndianPolicy(endianPolicy);
}
});
TypeAssist assist = TypeAssist.builder()
.clazz(protocolClass)
.field(null)
.typeAnnotation(null)
.decoderClass(null)
.encoderClass(null)
.decodeFormula(null)
.encodeFormula(null)
.endianPolicy(endianPolicy)
.decodeIgnore(decodeIgnore)
.encodeIgnore(encodeIgnore)
.elementType(ElementType.TYPE)
.circularReference(false)
.noArgsConstructor(noArgsConstructor)
.build();
List<TypeAssist> elements = Stream.concat(fieldStream, typeStream)
.peek(a -> a.setParent(assist))
.collect(Collectors.toList());
assist.setElements(elements);
return assist;
}
protected static TypeAssist resolveField(Field field) {
EndianPolicy policy = Optional.ofNullable(field.getAnnotation(Endian.class))
.map(Endian::value)
.orElse(null);
Boolean decodeIgnore = field.isAnnotationPresent(DecodeIgnore.class);
// || Modifier.isFinal(field.getModifiers()); // Removed for case class.
Boolean encodeIgnore = field.isAnnotationPresent(EncodeIgnore.class);
Class<? extends Annotation> typeAnnotationClass = getTypeAnnotationClass(field);
Annotation typeAnnotation = getTypeAnnotation(field);
Class<? extends TypeDecoder> decoder = Optional.of(typeAnnotationClass)
.map(t -> t.getAnnotation(Decoder.class))
.map(Decoder::value)
.orElse(null);
Class<? extends TypeEncoder> encoder = Optional.of(typeAnnotationClass)
.map(t -> t.getAnnotation(Encoder.class))
.map(Encoder::value)
.orElse(null);
Function<String, Class<? extends Function>> formula = name -> {
try {
Method method = typeAnnotation.getClass().getMethod(name);
Object array = method.invoke(typeAnnotation);
return Optional.of(array)
.filter(a -> a.getClass().isArray())
.filter(a -> Array.getLength(a) >= 1)
.map(a -> Array.get(a, 0))
.map(o -> (Class<? extends Function>) o)
.orElse(null);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
throw new CodecException(
MessageFormat.format(
CodecError.FAIL_GETTING_DECODE_FORMULA.getMessage(), typeAnnotation.annotationType().getName(), field.getName()), e);
}
};
Class<? extends Function> afterDecode = formula.apply("afterDecode");
Class<? extends Function> beforeEncode = formula.apply("beforeEncode");
val context = ValidationContext.builder()
.field(field)
.typeAnnotation(getProxyTypeAnnotation(field))
.build();
try {
AbstractFlow.getValidateFlow()
.process(context);
} catch(CodecException e) {
throw new CodecException(MessageFormat.format(
CodecError.FAIL_RESOLVING_FILED.getMessage(), field.toString()
), e);
}
val proxyTypeAnnotation = getProxyTypeAnnotation(field);
return TypeAssist.builder()
.clazz(field.getType())
.field(field)
.typeAnnotation(proxyTypeAnnotation)
.decoderClass(decoder)
.encoderClass(encoder)
.decodeFormula(afterDecode)
.encodeFormula(beforeEncode)
.endianPolicy(policy)
.decodeIgnore(decodeIgnore)
.encodeIgnore(encodeIgnore)
.elementType(ElementType.FIELD)
.circularReference(false)
.byteOffset(ProtocolType.byteOffset(proxyTypeAnnotation))
.bitOffset(ProtocolType.bitOffset(proxyTypeAnnotation))
.length(ProtocolType.length(proxyTypeAnnotation))
.size(ProtocolType.size(proxyTypeAnnotation))
.build();
}
protected static Class<? extends Annotation> getTypeAnnotationClass(@NonNull Field field) {
Annotation typeAnnotation = getTypeAnnotation(field);
if (typeAnnotation instanceof AutoType) {
return ProtocolType
.byAutoType(field.getType())
.typeAnnotationClass;
} else {
return typeAnnotation.annotationType();
}
}
protected static Annotation getTypeAnnotation(@NonNull Field field) {
return Arrays.stream(field.getAnnotations())
.filter(a -> a.annotationType().isAnnotationPresent(TypeFlag.class))
.findAny()
.orElseThrow(CodecException::new);
}
protected static Annotation getProxyTypeAnnotation(@NonNull Field field) {
Annotation typeAnnotation = getTypeAnnotation(field);
if (typeAnnotation instanceof AutoType) {
Class<? extends Annotation> typeAnnotationClass = ProtocolType
.byAutoType(field.getType())
.typeAnnotationClass;
return typeAnnotationClass.cast(Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{typeAnnotationClass},
(object, method, parameters) -> {
return Arrays.stream(typeAnnotation.annotationType().getMethods())
.filter(m -> m.getName().equals(method.getName()))
.findAny()
.orElseThrow(CodecException::new)
.invoke(typeAnnotation);
}));
} else {
return typeAnnotation;
}
}
public <T> T getObject(Class<T> clazz) {
T object = (T) instance.get();
instance.remove();
return object;
}
public boolean hasElement() {
return this.elements != null && !this.elements.isEmpty();
}
public void setValue(Object object, Object value) {
try {
this.field.set(object, value);
} catch (IllegalAccessException e) {
throw new DecodeException(
MessageFormat.format(CodecError.FAIL_ASSIGN_VALUE.getMessage(), this.field.getName()), e);
}
}
public DecodeContext toDecodeContext(byte[] datagram, Object object) {
return DecodeContext.builder()
.object(object)
.datagram(datagram)
.typeAssist(this)
.build();
}
protected List<DecodeContext> toDecodeContexts(byte[] datagram, Object parent) {
try {
Object value;
if (objects.get().containsKey(this.clazz)) {
value = objects.get().get(this.clazz);
} else {
value = this.clazz.newInstance();
objects.get().put(this.clazz, value);
}
if (parent == null) {
instance.set(value);
}
if (parent != null && field != null) {
try {
this.field.set(parent, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Stream<DecodeContext> fieldStream = this.elements.stream()
.filter(a -> a.getElementType() == ElementType.FIELD)
.map(a -> a.toDecodeContext(datagram, value));
Stream<DecodeContext> classStream = this.elements.stream()
.filter(a -> a.getElementType() == ElementType.TYPE)
.flatMap(a -> a.toDecodeContexts(datagram, value).stream());
return Stream.concat(fieldStream, classStream)
.collect(Collectors.toList());
} catch (InstantiationException | IllegalAccessException e) {
throw new DecodeException(
MessageFormat.format(CodecError.FAIL_INITIALIZING_DECODE_OBJECT.getMessage(), this.clazz.getName()), e);
}
}
public List<DecodeContext> toDecodeContexts(byte[] datagram) {
objects.set(new HashMap<Class<?>, Object>());
val contexts = this.toDecodeContexts(datagram, null);
objects.remove();
return contexts;
}
public EncodeContext toEncodeContext(Object object, byte[] datagram) {
try {
return EncodeContext.builder()
.datagram(datagram)
.typeAssist(this)
.value(this.field.get(object))
.build();
} catch (IllegalAccessException e) {
throw new EncodeException(
MessageFormat.format(CodecError.FAIL_GETTING_FIELD_VALUE.getMessage(), this.field.getName()), e);
}
}
public List<EncodeContext> toEncodeContexts(Object object, byte[] datagram) {
Stream<EncodeContext> fieldStream = this.elements.stream()
.filter(a -> a.getElementType() == ElementType.FIELD)
.map(a -> a.toEncodeContext(object, datagram));
Stream<EncodeContext> classStream = this.elements.stream()
.filter(a -> a.getElementType() == ElementType.TYPE)
.flatMap(a -> {
try {
if (object != null && a.field.get(object) != null) {
return a.toEncodeContexts(a.field.get(object), datagram).stream();
} else {
return Stream.empty();
}
} catch (IllegalAccessException e) {
throw new DecodeException(
MessageFormat.format(CodecError.FAIL_GETTING_FIELD_VALUE.getMessage(), this.clazz.getName()), e);
}
});
return Stream.concat(fieldStream, classStream)
.filter(c -> c.getValue() != null)
.collect(Collectors.toList());
}
}
|
lectureStudio/avdev
|
avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoManager.cpp
|
<filename>avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoManager.cpp
/*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MFVideoManager.h"
#include "MFInitializer.h"
#include "WindowsHelper.h"
#include "ComPtr.h"
#include <algorithm>
#include <Ksmedia.h>
namespace avdev
{
MFVideoManager::MFVideoManager() :
WinHotplugNotifier(std::list<GUID> { KSCATEGORY_VIDEO })
{
start();
}
MFVideoManager::~MFVideoManager()
{
}
std::set<PVideoCaptureDevice> MFVideoManager::getVideoCaptureDevices()
{
if (captureDevices.empty()) {
enumerateDevices(nullptr);
}
return captureDevices.devices();
}
void MFVideoManager::enumerateDevices(std::wstring * symLink)
{
MFInitializer initializer;
jni::ComPtr<IMFAttributes> pAttributes;
UINT32 deviceCount = 0;
IMFActivate ** ppDevices;
HRESULT hr;
hr = MFCreateAttributes(&pAttributes, 1);
THROW_IF_FAILED(hr, "MMF: Create attributes failed.");
hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
THROW_IF_FAILED(hr, "MMF: Set video source GUID failed.");
hr = MFEnumDeviceSources(pAttributes, &ppDevices, &deviceCount);
THROW_IF_FAILED(hr, "MMF: Enumerate video sources failed.");
for (DWORD i = 0; i < deviceCount; i++) {
WCHAR * friendlyName = nullptr;
WCHAR * symbolicLink = nullptr;
hr = ppDevices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &friendlyName, nullptr);
if (FAILED(hr)) {
LOGDEV_ERROR("MMF: Get video source name failed: hr = 0x%08x.", hr);
continue;
}
hr = ppDevices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &symbolicLink, nullptr);
if (FAILED(hr)) {
LOGDEV_ERROR("MMF: Get video source symbolic link failed: hr = 0x%08x.", hr);
continue;
}
if (symLink == nullptr) {
std::shared_ptr<VideoDevice> device = createVideoDevice(symbolicLink, friendlyName);
insertVideoDevice(device);
}
else {
// IMFActivate and the device broadcaster return different
// symbolic links. Compare only the device instance id.
std::wstring link(symbolicLink);
size_t pos = link.find(L"#{", 0);
pos = (pos == -1) ? (std::min)(link.length(), (*symLink).length()) : pos;
if ((*symLink).compare(0, pos, link, 0, pos) == 0) {
std::shared_ptr<VideoDevice> device = createVideoDevice(symbolicLink, friendlyName);
if (insertVideoDevice(device)) {
notifyDeviceConnected(device);
}
break;
}
}
CoTaskMemFree(friendlyName);
CoTaskMemFree(symbolicLink);
ppDevices[i]->Release();
}
if (deviceCount != 0) {
CoTaskMemFree(ppDevices);
ppDevices = nullptr;
}
}
std::shared_ptr<VideoDevice> MFVideoManager::createVideoDevice(WCHAR * symbolicLink, WCHAR * friendlyName)
{
std::string id = WideStrToStr(symbolicLink);
std::string name = WideStrToStr(friendlyName);
std::shared_ptr<VideoDevice> device = nullptr;
device = std::make_shared<MFVideoCaptureDevice>(name, id);
return device;
}
bool MFVideoManager::insertVideoDevice(std::shared_ptr<VideoDevice> device)
{
if (device == nullptr) {
return false;
}
captureDevices.insertDevice(std::static_pointer_cast<MFVideoCaptureDevice>(device));
return true;
}
void MFVideoManager::onDeviceConnected(std::wstring symLink)
{
enumerateDevices(&symLink);
}
void MFVideoManager::onDeviceDisconnected(std::wstring symLink)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
auto predicate = [&converter, symLink](const PVideoCaptureDevice & dev) {
std::wstring link = converter.from_bytes(dev->getDescriptor());
std::transform(link.begin(), link.end(), link.begin(), ::tolower);
// IMFActivate and the device broadcaster return different
// symbolic links. Compare only the device instance id.
size_t pos = link.find(L"#{", 0);
pos = (pos == -1) ? (std::min)(link.length(), symLink.length()) : pos;
return symLink.compare(0, pos, link, 0, pos) == 0;
};
PVideoCaptureDevice removed = captureDevices.removeDevice(predicate);
if (removed) {
notifyDeviceDisconnected(removed);
}
}
}
|
jackshirazi/apm-agent-java
|
apm-agent-core/src/main/java/co/elastic/apm/agent/collections/SpanConcurrentHashMap.java
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package co.elastic.apm.agent.collections;
import co.elastic.apm.agent.impl.transaction.AbstractSpan;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
* Hash map dedicated to storage of in-flight spans and transactions, reference count is being incremented/decremented
* when entry is added/removed. Usage of this map is intended for providing GC-based storage of context associated
* to a framework-level object key, when the latter is collected by GC it allows to decrement and then recycle the
* span/transaction.
*
* @param <K> key type
* @param <V> context type
*/
public class SpanConcurrentHashMap<K, V extends AbstractSpan<?>> extends ConcurrentHashMap<K, V> {
SpanConcurrentHashMap() {
}
@Nullable
@Override
public V remove(Object key) {
V removed = super.remove(key);
onRemove(removed);
return removed;
}
@Override
public V put(K key, V value) {
V previous = super.put(key, value);
onPut(previous, value);
return previous;
}
@Override
public V putIfAbsent(K key, V value) {
V previous = super.putIfAbsent(key, value);
if (previous == null) {
onPut(null, value);
}
return previous;
}
@Override
public void clear() {
Iterator<V> entries = values().iterator();
while (entries.hasNext()) {
onRemove(entries.next());
}
super.clear();
}
private void onPut(@Nullable AbstractSpan<?> previous, AbstractSpan<?> value) {
if (previous == null) {
// new entry
value.incrementReferences();
} else if (previous != value) {
// entry replaced
value.incrementReferences();
previous.decrementReferences();
}
}
private void onRemove(@Nullable AbstractSpan<?> removed) {
if (removed == null) {
return;
}
removed.decrementReferences();
}
}
|
sme777/esaas-engagements
|
db/migrate/20171202215817_rename_engagement_id_from_users.rb
|
class RenameEngagementIdFromUsers < ActiveRecord::Migration[6.1]
def change
rename_column :users, :engagement_id, :developing_engagement_id
end
end
|
timboudreau/netbeans-contrib
|
python.project/src/main/java/org/netbeans/modules/python/project/ui/customizer/CompositePanelProviderImpl.java
|
<reponame>timboudreau/netbeans-contrib
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.modules.python.project.ui.customizer;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.netbeans.spi.project.ui.support.ProjectCustomizer;
import org.netbeans.spi.project.ui.support.ProjectCustomizer.CompositeCategoryProvider;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
/**
*
* @author <NAME>
*/
public class CompositePanelProviderImpl implements CompositeCategoryProvider {
public static final String SOURCES = "Sources"; // NOI18N
public static final String PYTHON_PATH = "PythonPath"; //NOI18N
public static final String RUN = "Run"; // NOI18N
private final String name;
public CompositePanelProviderImpl(String name) {
this.name = name;
}
@Override
public ProjectCustomizer.Category createCategory(Lookup context) {
ProjectCustomizer.Category toReturn = null;
final ProjectCustomizer.Category[] categories = null;
if (SOURCES.equals(name)) {
toReturn = ProjectCustomizer.Category.create(
SOURCES,
NbBundle.getMessage(CompositePanelProviderImpl.class, "LBL_Config_Sources"),
null,
categories);
} else if (RUN.equals(name)) {
toReturn = ProjectCustomizer.Category.create(
RUN,
NbBundle.getMessage(CompositePanelProviderImpl.class, "LBL_Config_RunConfig"),
null,
categories);
} else if (PYTHON_PATH.equals(name)) {
toReturn = ProjectCustomizer.Category.create(
PYTHON_PATH,
NbBundle.getMessage(CompositePanelProviderImpl.class, "LBL_Config_PhpIncludePath"),
null,
categories);
}
assert toReturn != null : "No category for name: " + name;
return toReturn;
}
@Override
public JComponent createComponent(ProjectCustomizer.Category category, Lookup context) {
String nm = category.getName();
PythonProjectProperties uiProps = context.lookup(PythonProjectProperties.class);
if (SOURCES.equals(nm)) {
return new CustomizerSources(uiProps);
} else if (RUN.equals(nm)) {
return new CustomizerRun(uiProps);
} else if (PYTHON_PATH.equals(nm)) {
return new CustomizerPythonPath(uiProps);
}
return new JPanel();
}
public static CompositePanelProviderImpl createSources() {
return new CompositePanelProviderImpl(SOURCES);
}
public static CompositePanelProviderImpl createRunConfig() {
return new CompositePanelProviderImpl(RUN);
}
public static CompositePanelProviderImpl createPythonPath() {
return new CompositePanelProviderImpl(PYTHON_PATH);
}
}
|
MeGysssTaa/ReflexAutoban
|
src/main/java/rip/reflex/autoban/command/base/CommandArguments.java
|
<reponame>MeGysssTaa/ReflexAutoban<gh_stars>1-10
/*
* Copyright 2021 <NAME> (DarksideCode)
*
* 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 rip.reflex.autoban.command.base;
import lombok.AllArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import rip.reflex.autoban.util.str.Strings;
import java.util.Arrays;
import java.util.UUID;
@SuppressWarnings("MismatchedReadAndWriteOfArray")
@AllArgsConstructor
public class CommandArguments {
private String[] args;
public String get(int i) {
return has(i) ? args[i] : null;
}
public String joinFrom(int start) {
return has(start) ? Strings.join(start, args, " ") : null;
}
public int getInt(int i) {
return has(i) ? Integer.valueOf(get(i)) : -1;
}
public Player getPlayer(int i) {
return has(i) ? Bukkit.getPlayer(get(i)) : null;
}
public OfflinePlayer getOfflinePlayer(int i) {
return has(i) ? Bukkit.getOfflinePlayer(get(i)) : null;
}
public UUID getUUID(int i) {
return has(i) ? UUID.fromString(get(i)) : null;
}
public boolean has(int i) {
return i >= 0 && i < args.length;
}
public CommandArguments cut() {
args = Arrays.copyOfRange(args, 1, args.length);
return this;
}
public Boolean getBool(int i) {
return has(i) ? Boolean.valueOf(get(i)) : null;
}
}
|
iogogogo/supervisord-spring-boot
|
ext/supervisord4j/src/main/java/com/iogogogo/supervisord4j/util/IdHelper.java
|
<gh_stars>0
package com.iogogogo.supervisord4j.util;
import java.util.UUID;
/**
* Created by tao.zeng on 2019-07-24.
*/
public class IdHelper {
private IdHelper() {
}
public static Long id() {
return new Snowflake(2).next();
}
public static String uuid() {
return UUID.randomUUID().toString().toLowerCase().replace("-", "");
}
}
|
rrsharma7/Interview_Preparations
|
CodePractice/LCAAndTreeProblems/LeastCommonAncestor.java
|
<reponame>rrsharma7/Interview_Preparations
/**
Q1. Least Common Ancestor
Problem Description
Find the lowest common ancestor in an unordered binary tree A given two values B and C in the tree.
Lowest common ancestor : the lowest common ancestor (LCA) of two nodes and w in a tree or directed acyclic graph (DAG) is the lowest (i.e. deepest) node that has both v and w as descendants.
Problem Constraints
1 <= size of tree <= 100000
1 <= B, C <= 109
Input Format
First argument is head of tree A.
Second argument is integer B.
Third argument is integer C.
Output Format
Return the LCA.
Example Input
Input 1:
1
/ \
2 3
B = 2
C = 3
Input 2:
1
/ \
2 3
/ \
4 5
B = 4
C = 5
Example Output
Output 1:
1
Output 2:
2
Example Explanation
Explanation 1:
LCA is 1.
Explanation 2:
LCA is 2.
*/
package LCAAndTreeProblems;
class LeastCommonAncestor {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
left = null;
right = null;
}
}
public TreeNode LCA(TreeNode root, int val1, int val2) {
if (root == null)
return null;
if (root.val == val1 || root.val == val2)
return root;
TreeNode l = LCA(root.left, val1, val2);
TreeNode r = LCA(root.right, val1, val2);
if (l != null && r != null)
return root;
if (l != null)
return l;
return r;
}
public static boolean find(TreeNode root, int val1) {
if (root == null)
return false;
if (root.val == val1)
return true;
return (find(root.left, val1) || find(root.right, val1));
}
public int lca(TreeNode A, int B, int C) {
int val1 = B;
int val2 = C;
TreeNode root = A;
if (find(root, val1) == false || find(root, val2) == false)
return -1;
TreeNode ans = LCA(root, val1, val2);
if (ans == null)
return -1;
return ans.val;
}
public static void main(String[] args) {
LeastCommonAncestor lca = new LeastCommonAncestor();
TreeNode root1 = new TreeNode(1);
root1.left = new TreeNode(2);
root1.right = new TreeNode(3);
int x = lca.lca(root1, 2, 3);
System.out.println(x);
}
}
|
timm-gs/bazel
|
src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java
|
<filename>src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java
// Copyright 2015 The Bazel 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.
package com.google.devtools.build.lib.bazel.rules.android;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.syntax.Type.INTEGER;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpls;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder;
import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType;
import com.google.devtools.build.lib.rules.repository.WorkspaceBaseRule;
import com.google.devtools.build.lib.rules.repository.WorkspaceConfiguredTargetFactory;
import java.util.Map;
/**
* Definition of the {@code android_ndk_repository} rule.
*/
public class AndroidNdkRepositoryRule implements RuleDefinition {
public static final String NAME = "android_ndk_repository";
private static final Function<? super Rule, Map<String, Label>> BINDINGS_FUNCTION =
rule -> {
String defaultToolchainName =
AndroidNdkRepositoryFunction.createToolchainName(StlImpls.DEFAULT_STL_NAME);
return ImmutableMap.of(
"android/crosstool",
Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:" + defaultToolchainName),
"android_ndk_for_testing",
Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:files"));
};
@Override
public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) {
return builder
.setWorkspaceOnly()
.setExternalBindingsFunction(BINDINGS_FUNCTION)
/* <!-- #BLAZE_RULE(android_ndk_repository).ATTRIBUTE(path) -->
An absolute or relative path to an Android NDK. Either this attribute or the
<code>$ANDROID_NDK_HOME</code> environment variable must be set.
<p>The Android NDK can be downloaded from
<a href='https://developer.android.com/ndk/downloads/index.html'>the Android developer site
</a>.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("path", STRING).nonconfigurable("WORKSPACE rule"))
/* <!-- #BLAZE_RULE(android_ndk_repository).ATTRIBUTE(api_level) -->
The Android API level to build against. If not specified, the highest API level installed
will be used.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("api_level", INTEGER).nonconfigurable("WORKSPACE rule"))
.build();
}
@Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name(AndroidNdkRepositoryRule.NAME)
.type(RuleClassType.WORKSPACE)
.ancestors(WorkspaceBaseRule.class)
.factoryClass(WorkspaceConfiguredTargetFactory.class)
.build();
}
}
/*<!-- #BLAZE_RULE (NAME = android_ndk_repository, TYPE = OTHER, FAMILY = Android) -->
<p>Configures Bazel to use an Android NDK to support building Android targets with native
code. NDK versions 10, 11, 12, 13 and 14 are currently supported.
<p>Note that building for Android also requires an <code>android_sdk_repository</code> rule in your
<code>WORKSPACE</code> file.
<h4 id="android_ndk_repository_examples">Examples</h4>
<pre class="code">
android_ndk_repository(
name = "androidndk",
)
</pre>
<p>The above example will locate your Android NDK from <code>$ANDROID_NDK_HOME</code> and detect
the highest API level that it supports.
<pre class="code">
android_ndk_repository(
name = "androidndk",
path = "./android-ndk-r12b",
api_level = 24,
)
</pre>
<p>The above example will use the Android NDK located inside your workspace in
<code>./android-ndk-r12b</code>. It will use the API level 24 libraries when compiling your JNI
code.
<h4 id="android_ndk_repository_cpufeatures">cpufeatures</h4>
<p>The Android NDK contains the
<a href="https://developer.android.com/ndk/guides/cpu-features.html">cpufeatures library</a>
which can be used to detect a device's CPU at runtime. The following example demonstrates how to use
cpufeatures with Bazel.
<pre class="code">
# jni.cc
#include "ndk/sources/android/cpufeatures/cpu-features.h"
...
</pre>
<pre class="code">
# BUILD
cc_library(
name = "jni",
srcs = ["jni.cc"],
deps = ["@androidndk//:cpufeatures"],
)
</pre>
<!-- #END_BLAZE_RULE -->*/
|
IU-Libraries-Joint-Development/curation_concerns
|
spec/services/repository_audit_service_spec.rb
|
require 'spec_helper'
describe CurationConcerns::RepositoryAuditService do
let(:user) { FactoryGirl.create(:user) }
let!(:file) do
fs = FileSet.create! do |f|
f.apply_depositor_metadata(user)
end
Hydra::Works::AddFileToFileSet.call(fs, File.open(fixture_path + '/world.png'), :original_file)
fs
end
describe '#audit_everything' do
it 'audits everything' do
expect_any_instance_of(FileSet).to receive(:audit)
described_class.audit_everything
end
end
end
|
canonical/microk8s-cluster-agent
|
pkg/snap/mock/mock.go
|
<filename>pkg/snap/mock/mock.go
package mock
import (
"context"
"fmt"
"io"
"io/ioutil"
"github.com/canonical/microk8s-cluster-agent/pkg/snap"
"github.com/canonical/microk8s-cluster-agent/pkg/util"
)
// Snap is a generic mock for the snap.Snap interface.
type Snap struct {
GroupName string
EnableAddonCalledWith []string
DisableAddonCalledWith []string
RestartServiceCalledWith []string
RunUpgradeCalledWith []string // "{upgrade} {phase}"
CA string
CAKey string
ServiceAccountKey string
CNIYaml string
WriteCNIYamlCalledWith [][]byte
ApplyCNICalled []struct{}
DqliteCert string
DqliteKey string
DqliteClusterYaml string
DqliteInfoYaml string
WriteDqliteUpdateYamlCalledWith []string
KubeconfigFile string
KubeliteLock bool
DqliteLock bool
NoCertsReissueLock bool
CreateNoCertsReissueLockCalledWith []struct{}
ServiceArguments map[string]string
WriteServiceArgumentsCalled bool
ClusterTokens []string
CertificateRequestTokens []string
SelfCallbackTokens []string
AddCertificateRequestTokenCalledWith []string
AddCallbackTokenCalledWith []string // "{clusterAgentEndpoint} {token}"
ConsumeClusterTokenCalledWith []string
ConsumeCertificateRequestTokenCalledWith []string
SelfCallbackToken string
KubeletTokens map[string]string // map hostname to token
KnownTokens map[string]string // map username to token
SignCertificateCalledWith []string // string(csrPEM)
SignedCertificate string
ImportImageCalledWith []string // string(io.ReadAll(reader))
}
// GetGroupName is a mock implementation for the snap.Snap interface.
func (s *Snap) GetGroupName() string {
return s.GroupName
}
// EnableAddon is a mock implementation for the snap.Snap interface.
func (s *Snap) EnableAddon(_ context.Context, addon string) error {
s.EnableAddonCalledWith = append(s.EnableAddonCalledWith, addon)
return nil
}
// DisableAddon is a mock implementation for the snap.Snap interface.
func (s *Snap) DisableAddon(_ context.Context, addon string) error {
s.DisableAddonCalledWith = append(s.DisableAddonCalledWith, addon)
return nil
}
// RestartService is a mock implementation for the snap.Snap interface.
func (s *Snap) RestartService(_ context.Context, service string) error {
s.RestartServiceCalledWith = append(s.RestartServiceCalledWith, service)
return nil
}
// ReadCA is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadCA() (string, error) {
return s.CA, nil
}
// ReadCAKey is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadCAKey() (string, error) {
return s.CAKey, nil
}
// ReadServiceAccountKey is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadServiceAccountKey() (string, error) {
return s.ServiceAccountKey, nil
}
// ReadCNIYaml is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadCNIYaml() (string, error) {
return s.CNIYaml, nil
}
// WriteCNIYaml is a mock implementation for the snap.Snap interface.
func (s *Snap) WriteCNIYaml(b []byte) error {
s.CNIYaml = string(b)
return nil
}
// ApplyCNI is a mock implementation for the snap.Snap interface.
func (s *Snap) ApplyCNI(_ context.Context) error {
s.ApplyCNICalled = append(s.ApplyCNICalled, struct{}{})
return nil
}
// ReadDqliteCert is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadDqliteCert() (string, error) {
return s.DqliteCert, nil
}
// ReadDqliteKey is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadDqliteKey() (string, error) {
return s.DqliteKey, nil
}
// ReadDqliteInfoYaml is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadDqliteInfoYaml() (string, error) {
return s.DqliteInfoYaml, nil
}
// ReadDqliteClusterYaml is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadDqliteClusterYaml() (string, error) {
return s.DqliteClusterYaml, nil
}
// WriteDqliteUpdateYaml is a mock implementation for the snap.Snap interface.
func (s *Snap) WriteDqliteUpdateYaml(b []byte) error {
s.WriteDqliteUpdateYamlCalledWith = append(s.WriteDqliteUpdateYamlCalledWith, string(b))
return nil
}
// GetKubeconfigFile is a mock implementation for the snap.Snap interface.
func (s *Snap) GetKubeconfigFile() string {
return s.KubeconfigFile
}
// HasKubeliteLock is a mock implementation for the snap.Snap interface.
func (s *Snap) HasKubeliteLock() bool {
return s.KubeliteLock
}
// HasDqliteLock is a mock implementation for the snap.Snap interface.
func (s *Snap) HasDqliteLock() bool {
return s.DqliteLock
}
// HasNoCertsReissueLock is a mock implementation for the snap.Snap interface.
func (s *Snap) HasNoCertsReissueLock() bool {
return s.NoCertsReissueLock
}
// CreateNoCertsReissueLock is a mock implementation for the snap.Snap interface.
func (s *Snap) CreateNoCertsReissueLock() error {
s.NoCertsReissueLock = true
s.CreateNoCertsReissueLockCalledWith = append(s.CreateNoCertsReissueLockCalledWith, struct{}{})
return nil
}
// ReadServiceArguments is a mock implementation for the snap.Snap interface.
func (s *Snap) ReadServiceArguments(service string) (string, error) {
if s.ServiceArguments == nil {
s.ServiceArguments = make(map[string]string)
}
return s.ServiceArguments[service], nil
}
// WriteServiceArguments is a mock implementation for the snap.Snap interface.
func (s *Snap) WriteServiceArguments(service string, b []byte) error {
if s.ServiceArguments == nil {
s.ServiceArguments = make(map[string]string)
}
s.ServiceArguments[service] = string(b)
s.WriteServiceArgumentsCalled = true
return nil
}
func contains(list []string, item string) bool {
for _, i := range list {
if item == i {
return true
}
}
return false
}
// ConsumeClusterToken is a mock implementation for the snap.Snap interface.
func (s *Snap) ConsumeClusterToken(token string) bool {
if s.ConsumeClusterTokenCalledWith == nil {
s.ConsumeClusterTokenCalledWith = make([]string, 0, 1)
}
s.ConsumeClusterTokenCalledWith = append(s.ConsumeClusterTokenCalledWith, token)
return contains(s.ClusterTokens, token)
}
// ConsumeCertificateRequestToken is a mock implementation for the snap.Snap interface.
func (s *Snap) ConsumeCertificateRequestToken(token string) bool {
if s.ConsumeCertificateRequestTokenCalledWith == nil {
s.ConsumeCertificateRequestTokenCalledWith = make([]string, 0, 1)
}
s.ConsumeCertificateRequestTokenCalledWith = append(s.ConsumeCertificateRequestTokenCalledWith, token)
return contains(s.CertificateRequestTokens, token)
}
// ConsumeSelfCallbackToken is a mock implementation for the snap.Snap interface.
func (s *Snap) ConsumeSelfCallbackToken(token string) bool {
return contains(s.SelfCallbackTokens, token)
}
// AddCertificateRequestToken is a mock implementation for the snap.Snap interface.
func (s *Snap) AddCertificateRequestToken(token string) error {
if s.AddCertificateRequestTokenCalledWith == nil {
s.AddCertificateRequestTokenCalledWith = make([]string, 0, 1)
}
s.AddCertificateRequestTokenCalledWith = append(s.AddCertificateRequestTokenCalledWith, token)
return nil
}
// AddCallbackToken is a mock implementation for the snap.Snap interface.
func (s *Snap) AddCallbackToken(clusterAgentEndpoint string, token string) error {
if s.AddCallbackTokenCalledWith == nil {
s.AddCallbackTokenCalledWith = make([]string, 0, 1)
}
s.AddCallbackTokenCalledWith = append(s.AddCallbackTokenCalledWith, fmt.Sprintf("%s %s", clusterAgentEndpoint, token))
return nil
}
// RemoveClusterToken is a mock implementation for the snap.Snap interface.
func (s *Snap) RemoveClusterToken(token string) error {
if s.ConsumeClusterTokenCalledWith == nil {
s.ConsumeClusterTokenCalledWith = make([]string, 0, 1)
}
s.ConsumeClusterTokenCalledWith = append(s.ConsumeClusterTokenCalledWith, token)
return nil
}
// GetOrCreateSelfCallbackToken is a mock implementation for the snap.Snap interface.
func (s *Snap) GetOrCreateSelfCallbackToken() (string, error) {
if s.SelfCallbackToken == "" {
s.SelfCallbackToken = "callback-token"
}
return s.SelfCallbackToken, nil
}
// GetOrCreateKubeletToken is a mock implementation for the snap.Snap interface.
func (s *Snap) GetOrCreateKubeletToken(hostname string) (string, error) {
if s.KubeletTokens == nil {
s.KubeletTokens = make(map[string]string, 1)
}
if t, ok := s.KubeletTokens[hostname]; ok {
fmt.Println("AA")
return t, nil
}
s.KubeletTokens[hostname] = util.NewRandomString(util.Alpha, 32)
return s.KubeletTokens[hostname], nil
}
// GetKnownToken is a mock implementation for the snap.Snap interface.
func (s *Snap) GetKnownToken(username string) (string, error) {
if t, ok := s.KnownTokens[username]; ok {
return t, nil
}
return "", fmt.Errorf("no known token for user %s", username)
}
// RunUpgrade is a mock implementation for the snap.Snap interface.
func (s *Snap) RunUpgrade(ctx context.Context, upgrade string, phase string) error {
if s.RunUpgradeCalledWith == nil {
s.RunUpgradeCalledWith = make([]string, 0, 1)
}
s.RunUpgradeCalledWith = append(s.RunUpgradeCalledWith, fmt.Sprintf("%s %s", upgrade, phase))
return nil
}
// SignCertificate is a mock implementation for the snap.Snap interface.
func (s *Snap) SignCertificate(ctx context.Context, csrPEM []byte) ([]byte, error) {
if s.SignCertificateCalledWith == nil {
s.SignCertificateCalledWith = make([]string, 0, 1)
}
s.SignCertificateCalledWith = append(s.SignCertificateCalledWith, string(csrPEM))
return []byte(s.SignedCertificate), nil
}
// ImportImage is a mock implementation for the snap.Snap interface.
func (s *Snap) ImportImage(ctx context.Context, reader io.Reader) error {
if s.ImportImageCalledWith == nil {
s.ImportImageCalledWith = make([]string, 0, 1)
}
b, _ := ioutil.ReadAll(reader)
s.ImportImageCalledWith = append(s.ImportImageCalledWith, string(b))
return nil
}
var _ snap.Snap = &Snap{}
|
jpsalo/extendedmind
|
backend/src/main/scala/org/extendedmind/bl/CollectiveActions.scala
|
/**
* Copyright (c) 2013-2014 Extended Mind Technologies Oy
*
* This file is part of Extended Mind.
*
* Extended Mind 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.extendedmind.bl
import org.extendedmind.domain._
import org.extendedmind.db._
import org.extendedmind._
import org.extendedmind.email._
import org.extendedmind.security._
import org.extendedmind.Response._
import scaldi.Injector
import scaldi.Injectable
import org.extendedmind.db.EmbeddedGraphDatabase
import scala.util.{Success, Failure}
import scala.concurrent.ExecutionContext
import akka.actor.ActorRefFactory
import akka.actor.ActorSystem
import java.util.UUID
import akka.event.LoggingAdapter
trait CollectiveActions {
def db: GraphDatabase
def settings: Settings
def putNewCollective(creatorUUID: UUID, collective: Collective)(implicit log: LoggingAdapter): Response[SetResult] = {
if (!db.hasCommonCollective){
log.info("Making collective {} a common collective to all "
+"users because it is the first inserted collective", collective.title)
db.putNewCollective(creatorUUID, collective, true)
}else{
db.putNewCollective(creatorUUID, collective, false)
}
}
def putExistingCollective(collectiveUUID: UUID, collective: Collective)(implicit log: LoggingAdapter): Response[SetResult] = {
log.info("putExistingCollective: collective {}", collectiveUUID)
db.putExistingCollective(collectiveUUID, collective)
}
def getCollective(collectiveUUID: UUID)(implicit log: LoggingAdapter): Response[Collective] = {
log.info("getCollective: collective {}", collectiveUUID)
db.getCollective(collectiveUUID)
}
def setCollectiveUserPermission(collectiveUUID: UUID, founderUUID: UUID, userUUID: UUID, access: Option[Byte])
(implicit log: LoggingAdapter): Response[SetResult] = {
log.info("setCollectiveUserPermission: collective {}, founder {}, user {}, access {}", collectiveUUID, founderUUID, userUUID, access)
db.setCollectiveUserPermission(collectiveUUID, founderUUID, userUUID, access)
}
}
class CollectiveActionsImpl(implicit val implSettings: Settings, implicit val inj: Injector)
extends CollectiveActions with Injectable {
override def settings = implSettings
override def db = inject[GraphDatabase]
}
|
AnimatorPro/Animator-Pro
|
src/PJ/a3ddat.c
|
<filename>src/PJ/a3ddat.c
/* a3ddat.c - This file contains the data structures for the optics panel.
Also some functions for enabling/disabling buttons and rearranging
the optics panel for example to bring up the reduce/enlarge sliders
when you press the size button */
/* Gak this is next to completely gnarly. There's I'm not sure,
3 or 4 levels to the menu tree. The main branches are
1. Mouse control area on left.
Size specific controls (x y xy proportional)
Everyone else's controls (x y z yz zx xy)
2. The 'major' mode strip - whether it's turn/size/move/path
Just 4 radio buttons in the center.
3. The subpanel area - which changes depending which
major mode you are in.
The subpanel area is where it gets really complicated:
In the case of 'turn' and 'size' the left part of the subpanel
contains radio buttons which select a subsubpanel to the right.
What I did to minimize as best I could the number of buttons
serving only as hierarchical place holders is too complex for
me to remember any more. Lets hope no-one wants us to add
'just one more feature' that would require re-laying this out.
In the case of 'move' you go straight to an x/y/z slider set
covering the entire subpanel.
The path sub panel also isn't too bad. At least the menus
aren't alway spontaniously re-arranging themselves.
Oh well. Someday I'll figure out a simpler way to do this,
or maybe just give up doing these paint-box like interfaces
when they go beyond simple columns of text.
*/
#include <stdio.h>
#include "jimk.h"
#include "a3d.h"
#include "brush.h"
#include "celmenu.h"
#include "filemenu.h"
#include "fli.h"
#include "inks.h"
#include "mask.h"
#include "memory.h"
#include "menus.h"
#include "palmenu.h"
#include "pentools.h"
#include "rastcurs.h"
#include "softmenu.h"
#include "timemenu.h"
#include "util.h"
static void seebg_a3d(Menuwndo *mw);
static void a3d_go_color_grid(Button *b);
static void change_rot_scale(Button *m);
static void change_size_mode(Button *m);
static void change_spin_mode(Button *m);
static void change_ado_mode(Button *m);
static void set_axis(Button *m);
static void csame_size(Button *m);
static void csame_spin(Button *m);
static void csize_default(Button *m);
static void see_size_ratio(Button *m);
static void feel_rdc_qslider(Button *m);
static void cspin_default(Button *m);
static void clear_track(void);
static void clear_pos(void);
static void mgo_path_files(void);
Short_xyz rot_theta; /* where the xyz sliders usually point... */
SHORT got_path;
char inspin;
/* The usual x/y/z optics sliders */
static Qslider a3d_xslider =
QSL_INIT1( -500, 500, NULL, 0, NULL, leftright_arrs);
static Qslider a3d_yslider =
QSL_INIT1( -500, 500, NULL, 0, NULL, updown_arrs);
static Qslider a3d_zslider =
QSL_INIT1( -500, 500, NULL, 0, NULL, zoutin_arrs);
/* reduce/enlarge sliders */
static Qslider a3d_rdc_slider =
QSL_INIT1( 0, 100, NULL, 0, NULL, leftright_arrs);
static Qslider a3d_enl_slider =
QSL_INIT1( 1, 100, NULL, 0, NULL, leftright_arrs);
#define MCOFF (-9)
/* Branch of tree that covers mouse control buttons */
/* Mouse control section for size */
static Button a3d_y_szm = MB_INIT1(
NONEXT,
NOCHILD,
20,11,MCOFF+278,59,
"Y",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_szmouse,3,
NOKEY,
MB_B_GHILITE
);
static Button a3d_x_szm = MB_INIT1(
&a3d_y_szm,
NOCHILD,
20,11,MCOFF+255,59,
"X",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_szmouse,2,
NOKEY,
MB_B_GHILITE
);
static Button a3d_xy_szm = MB_INIT1(
&a3d_x_szm,
NOCHILD,
20,11,MCOFF+232,59,
"XY",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_szmouse,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_prop_sel = MB_INIT1(
&a3d_xy_szm,
NOCHILD,
77,11,MCOFF+227,46,
NODATA, /* "Proportional", */
dcorner_text,
change_mode,
NOOPT,
&vs.ado_szmouse,0,
NOKEY,
MB_B_GHILITE
);
static Button a3d_szcleart_sel = MB_INIT1(
&a3d_prop_sel,
NOCHILD,
72,9,MCOFF+229,35,
NODATA, /* "Mouse control", */
grey_ctext,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_szm_group = MB_INIT1(
NONEXT,
&a3d_szcleart_sel,
85,41,214,32,
NOTEXT,
wbg_ncorner_back,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
/* mouse control section for all other states */
static Button a3d_x_spm = MB_INIT1(
NONEXT,
NOCHILD,
20,11,MCOFF+277,59,
"X",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_mouse,5,
NOKEY,
MB_B_GHILITE
);
static Button a3d_y_spm = MB_INIT1(
&a3d_x_spm,
NOCHILD,
20,11,MCOFF+255,59,
"Y",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_mouse,4,
NOKEY,
MB_B_GHILITE
);
static Button a3d_z_spm = MB_INIT1(
&a3d_y_spm,
NOCHILD,
20,11,MCOFF+233,59,
"Z",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_mouse,3,
NOKEY,
MB_B_GHILITE
);
static Button a3d_yz_spm = MB_INIT1(
&a3d_z_spm,
NOCHILD,
20,11,MCOFF+277,47,
"ZY",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_mouse,2,
NOKEY,
MB_B_GHILITE
);
static Button a3d_zx_spm = MB_INIT1(
&a3d_yz_spm,
NOCHILD,
20,11,MCOFF+255,47,
"XZ",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_mouse,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_xy_spm = MB_INIT1(
&a3d_zx_spm,
NOCHILD,
20,11,MCOFF+233,47,
"XY",
dcorner_text,
change_mode,
NOOPT,
&vs.ado_mouse,0,
NOKEY,
MB_B_GHILITE
);
static Button a3d_cleart_sel = MB_INIT1(
&a3d_xy_spm,
NOCHILD,
72,9,MCOFF+229,35,
NODATA, /* "Mouse control", */
grey_ctext,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spm_group = MB_INIT1(
NONEXT,
&a3d_cleart_sel,
85,41,214,32,
NOTEXT,
wbg_ncorner_back,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_g4_sel = MB_INIT1(
NONEXT,
&a3d_spm_group,
85,41,4,28,
NOTEXT,
hang_children,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_eslide_sel = MB_INIT1(
NONEXT,
NOCHILD,
146,11,69,62,
&a3d_enl_slider,
see_qslider,
feel_rdc_qslider,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spt_1 = MB_INIT1(
NONEXT,
NOCHILD,
14,11,201,62,
"1",
ncorner_text,
change_rot_scale,
NOOPT,
&vs.ado_turn,1,
NOKEY,
MB_GHILITE
);
static Button a3d_spt_2 = MB_INIT1(
&a3d_spt_1,
NOCHILD,
25,11,177,62,
"1/2",
ncorner_text,
change_rot_scale,
NOOPT,
&vs.ado_turn,2,
NOKEY,
MB_GHILITE
);
static Button a3d_spt_4 = MB_INIT1(
&a3d_spt_2,
NOCHILD,
25,11,153,62,
"1/4",
ncorner_text,
change_rot_scale,
NOOPT,
&vs.ado_turn,4,
NOKEY,
MB_GHILITE
);
static Button a3d_spt_6 = MB_INIT1(
&a3d_spt_4,
NOCHILD,
24,11,130,62,
"1/6",
ncorner_text,
change_rot_scale,
NOOPT,
&vs.ado_turn,6,
NOKEY,
MB_GHILITE
);
static Button a3d_spt_8 = MB_INIT1(
&a3d_spt_6,
NOCHILD,
25,11,106,62,
"1/8",
ncorner_text,
change_rot_scale,
NOOPT,
&vs.ado_turn,8,
NOKEY,
MB_GHILITE
);
static Button a3d_spt_360 = MB_INIT1(
&a3d_spt_8,
NOCHILD,
38,11,69,62,
"1/360",
ncorner_text,
change_rot_scale,
NOOPT,
&vs.ado_turn,360,
NOKEY,
MB_GHILITE
);
static Button a3d_spt_3group = MB_INIT1(
NONEXT,
&a3d_spt_360,
146,11,69,62,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spa_z = MB_INIT1(
NONEXT,
NOCHILD,
50,11,165,62,
"Z",
ncorner_text,
set_axis,
NOOPT,
NOGROUP,2,
NOKEY,
0
);
static Button a3d_spa_y = MB_INIT1(
&a3d_spa_z,
NOCHILD,
49,11,117,62,
"Y",
ncorner_text,
set_axis,
NOOPT,
NOGROUP,1,
NOKEY,
0
);
static Button a3d_spa_x = MB_INIT1(
&a3d_spa_y,
NOCHILD,
49,11,69,62,
"X",
ncorner_text,
set_axis,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spa_3group = MB_INIT1(
NONEXT,
&a3d_spa_x,
146,11,69,62,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_szc_same = MB_INIT1(
NONEXT,
NOCHILD,
85,11,130,62,
NODATA, /* "Same as Spin", */
ncorner_text,
csame_spin,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_szc_default = MB_INIT1(
&a3d_szc_same,
NOCHILD,
62,11,69,62,
NODATA, /* "Default", */
ncorner_text,
csize_default,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_szc_3group = MB_INIT1(
NONEXT,
&a3d_szc_default,
146,11,69,62,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spc_same = MB_INIT1(
NONEXT,
NOCHILD,
85,11,130,62,
NODATA, /* "Same as Size", */
ncorner_text,
csame_size,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spc_default = MB_INIT1(
&a3d_spc_same,
NOCHILD,
62,11,69,62,
NODATA, /* "Default", */
ncorner_text,
cspin_default,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spc_3group = MB_INIT1(
NONEXT,
&a3d_spc_default,
146,11,69,62,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_g3_sel = MB_INIT1(
NONEXT,
&a3d_spc_3group,
146,11,69,62,
NOTEXT,
hang_children,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_zslide_sel = MB_INIT1(
NONEXT,
NOCHILD,
146,11,69,52,
&a3d_zslider,
see_qslider,
ado_xyz_slider,
xyz_zero_sl,
NOGROUP,2,
NOKEY,
0
);
static Button a3d_yslide_sel = MB_INIT1(
&a3d_zslide_sel,
NOCHILD,
146,11,69,42,
&a3d_yslider,
see_qslider,
ado_xyz_slider,
xyz_zero_sl,
NOGROUP,1,
NOKEY,
0
);
static Button a3d_xslide_sel = MB_INIT1(
&a3d_yslide_sel,
NOCHILD,
146,11,69,32,
&a3d_xslider,
see_qslider,
ado_xyz_slider,
xyz_zero_sl,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_slider_group = MB_INIT1(
NONEXT,
&a3d_xslide_sel,
146,31,69,32,
NOTEXT,
iscale_theta,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_etag_sel = MB_INIT1(
NONEXT,
NOCHILD,
146,11,69,52,
NODATA, /* "Enlarge", */
ncorner_text,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_rslide_sel = MB_INIT1(
&a3d_etag_sel,
NOCHILD,
146,11,69,42,
&a3d_rdc_slider,
see_qslider,
feel_rdc_qslider,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_rtag_sel = MB_INIT1(
&a3d_rslide_sel,
NOCHILD,
146,11,69,32,
NODATA, /* "Reduce", */
ncorner_text,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_szslide_group = MB_INIT1(
NONEXT,
&a3d_rtag_sel,
146,41,69,32,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_g2_sel = MB_INIT1(
&a3d_g3_sel,
&a3d_slider_group,
146,31,69,32,
NOTEXT,
hang_children,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_sz_ratio = MB_INIT1(
NONEXT,
NOCHILD,
42,11,28,62,
NOTEXT,
see_size_ratio,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_sz_both = MB_INIT1(
&a3d_sz_ratio,
NOCHILD,
42,11,28,52,
NODATA, /* "Both", */
ncorner_text,
change_size_mode,
NOOPT,
&vs.ado_size,3,
NOKEY,
MB_B_GHILITE
);
static Button a3d_sz_y = MB_INIT1(
&a3d_sz_both,
NOCHILD,
21,11,49,42,
"Y",
ncorner_text,
change_size_mode,
NOOPT,
&vs.ado_size,2,
NOKEY,
MB_B_GHILITE
);
static Button a3d_sz_x = MB_INIT1(
&a3d_sz_y,
NOCHILD,
22,11,28,42,
"X",
ncorner_text,
change_size_mode,
NOOPT,
&vs.ado_size,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_sz_center = MB_INIT1(
&a3d_sz_x,
NOCHILD,
42,11,28,32,
NODATA, /* "Center", */
ncorner_text,
change_size_mode,
NOOPT,
&vs.ado_size,0,
NOKEY,
MB_B_GHILITE
);
static Button a3d_size_group = MB_INIT1(
NONEXT,
&a3d_sz_center,
42,41,28,32,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_sp_turns = MB_INIT1(
NONEXT,
NOCHILD,
42,14,28,59,
NODATA, /* "Turns", */
ncorner_text,
change_spin_mode,
NOOPT,
&vs.ado_spin,2,
NOKEY,
MB_B_GHILITE
);
static Button a3d_sp_axis = MB_INIT1(
&a3d_sp_turns,
NOCHILD,
42,14,28,46,
NODATA, /* "Axis", */
ncorner_text,
change_spin_mode,
NOOPT,
&vs.ado_spin,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_sp_center = MB_INIT1(
&a3d_sp_axis,
NOCHILD,
42,15,28,32,
NODATA, /* "Center", */
ncorner_text,
change_spin_mode,
NOOPT,
&vs.ado_spin,0,
NOKEY,
MB_B_GHILITE
);
static Button a3d_spin_group = MB_INIT1(
NONEXT,
&a3d_sp_center,
42,41,28,32,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_g1_sel = MB_INIT1(
&a3d_g2_sel,
&a3d_spin_group,
42,41,28,32,
NOTEXT,
hang_children,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_spsz_group = MB_INIT1(
NONEXT,
&a3d_g1_sel,
187,41,28,32,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
#define PAX (-100)
#define PAY (4)
static Qslider ptens_sl =
QSL_INIT1( -20, 20, &vs.pa_tens, 0, NULL, leftright_arrs);
static Qslider pcont_sl =
QSL_INIT1( -20, 20, &vs.pa_cont, 0, NULL, leftright_arrs);
static Qslider pbias_sl =
QSL_INIT1( -20, 20, &vs.pa_bias, 0, NULL, leftright_arrs);
static Button a3d_bias_sel = MB_INIT1(
NONEXT,
NOCHILD,
112,11,PAX+203,(PAY+185)-127,
&pbias_sl,
see_qslider,
feel_qslider,
zero_sl,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_cont_sel = MB_INIT1(
&a3d_bias_sel,
NOCHILD,
112,11,PAX+203,(PAY+175)-127,
&pcont_sl,
see_qslider,
feel_qslider,
zero_sl,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_tens_sel = MB_INIT1(
&a3d_cont_sel,
NOCHILD,
112,11,PAX+203,(PAY+165)-127,
&ptens_sl,
see_qslider,
feel_qslider,
zero_sl,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_pa_closed = MB_INIT1(
&a3d_tens_sel,
NOCHILD,
63,11,PAX+252,(PAY+155)-127,
NODATA, /* "Closed", */
ncorner_text,
change_mode,
NOOPT,
&vs.pa_closed,1,
NOKEY,
MB_GHILITE
);
static Button a3d_pa_open = MB_INIT1(
&a3d_pa_closed,
NOCHILD,
50,11,PAX+203,(PAY+155)-127,
NODATA, /* "Open", */
ncorner_text,
change_mode,
NOOPT,
&vs.pa_closed,0,
NOKEY,
MB_GHILITE
);
static Button a3d_pa_save = MB_INIT1(
&a3d_pa_open,
NOCHILD,
31,11,73,62,
NODATA, /* "Save", */
ncorner_text,
mgo_path_files,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_pa_load = MB_INIT1(
&a3d_pa_save,
NOCHILD,
31,11,73,52,
NODATA, /* "Load", */
ncorner_text,
mgo_path_files,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_pa_view = MB_INIT1(
&a3d_pa_load,
NOCHILD,
31,11,73,42,
NODATA, /* "View", */
ncorner_text,
mview_path,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_pa_edit = MB_INIT1(
&a3d_pa_view,
NOCHILD,
31,11,73,32,
NODATA, /* "Edit", */
ncorner_text,
edit_path,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_pa_clocked = MB_INIT1(
&a3d_pa_edit,
NOCHILD,
46,11,28,62,
NODATA, /* "Clocked", */
ncorner_text,
change_mode,
NOOPT,
&vs.ado_path,3,
NOKEY,
MB_B_GHILITE
);
static Button a3d_pa_sampled = MB_INIT1(
&a3d_pa_clocked,
NOCHILD,
46,11,28,52,
NODATA, /* "Sampled", */
ncorner_text,
change_mode,
NOOPT,
&vs.ado_path,2,
NOKEY,
MB_B_GHILITE
);
static Button a3d_pa_poly = MB_INIT1(
&a3d_pa_sampled,
NOCHILD,
46,11,28,42,
NODATA, /* "Polygon", */
ncorner_text,
change_mode,
NOOPT,
&vs.ado_path,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_pa_spline = MB_INIT1(
&a3d_pa_poly,
NOCHILD,
46,11,28,32,
NODATA, /* "Spline", */
ncorner_text,
change_mode,
NOOPT,
&vs.ado_path,0,
NOKEY,
MB_B_GHILITE
);
static Button a3d_path_group = MB_INIT1(
NONEXT,
&a3d_pa_spline,
187,41,28,32,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_mzslide_sel = MB_INIT1(
NONEXT,
NOCHILD,
187,14,28,59,
&a3d_zslider,
see_qslider,
feel_qslider,
zero_sl,
NOGROUP,2,
NOKEY,
0
);
static Button a3d_myslide_sel = MB_INIT1(
&a3d_mzslide_sel,
NOCHILD,
187,14,28,(173)-127,
&a3d_yslider,
see_qslider,
feel_qslider,
zero_sl,
NOGROUP,1,
NOKEY,
0
);
static Button a3d_mxslide_sel = MB_INIT1(
&a3d_myslide_sel,
NOCHILD,
187,15,28,32,
&a3d_xslider,
see_qslider,
feel_qslider,
zero_sl,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_move_group = MB_INIT1(
NONEXT,
&a3d_mxslide_sel,
187,41,28,32,
NOTEXT,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_g0_sel = MB_INIT1(
&a3d_g4_sel,
&a3d_spsz_group,
187,41,128,28,
NOTEXT,
hang_children,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_path_sel = MB_INIT1(
&a3d_g0_sel,
NOCHILD,
29,11,94,(185)-127,
NODATA, /* "Path", */
ncorner_text,
change_ado_mode,
NOOPT,
&vs.ado_mode,3,
NOKEY,
MB_B_GHILITE
);
static Button a3d_move_sel = MB_INIT1(
&a3d_path_sel,
NOCHILD,
29,11,94,(175)-127,
NODATA, /* "Move", */
ncorner_text,
change_ado_mode,
NOOPT,
&vs.ado_mode,2,
NOKEY,
MB_B_GHILITE
);
static Button a3d_size_sel = MB_INIT1(
&a3d_move_sel,
NOCHILD,
29,11,94,(165)-127,
NODATA, /* "Size", */
ncorner_text,
change_ado_mode,
NOOPT,
&vs.ado_mode,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_spin_sel = MB_INIT1(
&a3d_size_sel,
NOCHILD,
29,11,94,28,
NODATA, /* "Spin", */
ncorner_text,
change_ado_mode,
NOOPT,
&vs.ado_mode,0,
NOKEY,
MB_B_GHILITE
);
static Button a3d_clear_sel = MB_INIT1(
&a3d_spin_sel,
NOCHILD,
71,9,244,15,
NODATA, /* "Clear Track", */
ccorner_text,
clear_track,
NOOPT,
NOGROUP,0,
NOKEY,
MB_HIONSEL
);
static Button a3d_clearm_sel = MB_INIT1(
&a3d_clear_sel,
NOCHILD,
63,9,177,15,
NODATA, /* "Clear Move", */
ccorner_text,
clear_pos,
NOOPT,
NOGROUP,0,
NOKEY,
MB_HIONSEL
);
static Button a3d_contin_sel = MB_INIT1(
&a3d_clearm_sel,
NOCHILD,
58,9,115,15,
NODATA, /* "Continue", */
ccorner_text,
move_along,
NOOPT,
NOGROUP,0,
NOKEY,
MB_HIONSEL
);
static Button a3d_render_sel = MB_INIT1(
&a3d_contin_sel,
NOCHILD,
33,9,77,15,
NODATA, /* "Use", */
ccorner_text,
mauto_ado,
NOOPT,
NOGROUP,0,
'r',
0
);
static Button a3d_loop_sel = MB_INIT1(
&a3d_render_sel,
NOCHILD,
33,9,40,15,
NODATA, /* "Loop", */
ccorner_text,
mado_loop,
NOOPT,
NOGROUP,0,
'l',
0
);
static Button a3d_view_sel = MB_INIT1(
&a3d_loop_sel,
NOCHILD,
33,9,4,15,
NODATA, /* "View", */
ccorner_text,
mado_view,
NOOPT,
NOGROUP,0,
'v',
0
);
static Button a3d_cco_sel = MB_INIT1(
&a3d_view_sel,
NOCHILD,
11,9,306,2,
NOTEXT,
ccolor_box,
a3d_go_color_grid,
ppalette,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_bru_sel = MB_INIT1(
&a3d_cco_sel,
NOCHILD,
11,11,293,2,
NOTEXT,
see_pen,
toggle_pen,
set_pbrush,
NOGROUP,0,
NOKEY,
0
);
static Button a3d_kmo_sel = MB_INIT1(
&a3d_bru_sel,
NOCHILD,
11,9,220,3,
NODATA, /* "K", */
ncorner_text,
mb_toggle_zclear,
go_cel_menu,
&vs.zero_clear,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_fmo_sel = MB_INIT1(
&a3d_kmo_sel,
NOCHILD,
11,9,210,3,
NODATA, /* "F", */
ncorner_text,
toggle_bgroup,
NOOPT,
&vs.fillp,1,
NOKEY,
MB_B_GHILITE
);
static Button a3d_ink_sel = MB_INIT1(
&a3d_fmo_sel,
NOCHILD,
53,9,238,3,
NOTEXT,
see_cur_ink,
qinks,
qinks,
&vs.ink_id,opq_INKID,
NOKEY,
MB_GHILITE
);
static Button a3d_minitime_hanger_sel = MB_INIT1(
&a3d_ink_sel,
&minitime_sel,
79,9,129,3,
NOTEXT,
hang_children,
NOFEEL,
NOOPT,
&flxtime_data,0,
NOKEY,
0
);
static Button a3d_a_sel = MB_INIT1(
&a3d_minitime_hanger_sel,
NOCHILD,
11,9,113,3,
NODATA, /* "A", */
dcorner_text,
change_mode,
NOOPT,
&vs.time_mode,2,
NOKEY,
MB_GHILITE
);
static Button a3d_s_sel = MB_INIT1(
&a3d_a_sel,
NOCHILD,
11,9,103,3,
NODATA, /* "S", */
dcorner_text,
change_mode,
NOOPT,
&vs.time_mode,1,
NOKEY,
MB_GHILITE
);
static Button a3d_frame_sel = MB_INIT1(
&a3d_s_sel,
NOCHILD,
11,9,93,3,
NODATA, /* "F", */
dcorner_text,
change_mode,
NOOPT,
&vs.time_mode,0,
NOKEY,
MB_GHILITE
);
static Button a3d_moveq_sel = MB_INIT1(
&a3d_frame_sel,
NOCHILD,
82,9,4,3,
NODATA, /* "Optics", */
see_titlebar,
feel_titlebar,
mb_menu_to_bottom,
&tbg_moveclose,0,
'q',
0 /* flags */
);
Menuhdr a3d_menu = {
{320,72,0,127}, /* width, height, x y */
OPTIC_MUID, /* id */
PANELMENU, /* type */
&a3d_moveq_sel, /* buttons */
SCREEN_FONT, /* font */
&menu_cursor.hdr, /* cursor */
seebg_a3d, /* seebg */
NULL, /* dodata */
NULL, /* domenu */
(MBPEN|MBRIGHT|KEYHIT), /* ioflags */
0, /* flags */
NULL, /* mw */
NULL, /* group */
{ NULL, NULL }, /* node */
NULL, /* procmouse */
NULL, /* on_showhide */
NULL, /* cleanup */
0, 0, 0, 0 /* scaled width, height, x, y */
};
static Smu_button_list a3d_smblist[] = {
{ "title", { &a3d_moveq_sel } },
{ "prop", { &a3d_prop_sel } },
{ "szby_mouse", { &a3d_szcleart_sel } },
{ "by_mouse", { &a3d_cleart_sel } },
{ "as_spin", { &a3d_szc_same } },
{ "szc_dflt", { &a3d_szc_default } },
{ "as_size", { &a3d_spc_same } },
{ "spc_dflt", { &a3d_spc_default } },
{ "enlarge", { &a3d_etag_sel } },
{ "reduce", { &a3d_rtag_sel } },
{ "sz_both", { &a3d_sz_both } },
{ "sz_cent", { &a3d_sz_center } },
{ "sp_turns", { &a3d_sp_turns } },
{ "sp_axis", { &a3d_sp_axis } },
{ "sp_cent", { &a3d_sp_center } },
{ "sp_closed", { &a3d_pa_closed } },
{ "pa_open", { &a3d_pa_open } },
{ "pa_save", { &a3d_pa_save } },
{ "pa_load", { &a3d_pa_load } },
{ "pa_view", { &a3d_pa_view } },
{ "pa_edit", { &a3d_pa_edit } },
{ "pa_clock", { &a3d_pa_clocked } },
{ "pa_samp", { &a3d_pa_sampled } },
{ "pa_poly", { &a3d_pa_poly } },
{ "pa_spline", { &a3d_pa_spline } },
{ "path", { &a3d_path_sel } },
{ "move", { &a3d_move_sel } },
{ "size", { &a3d_size_sel } },
{ "spin", { &a3d_spin_sel } },
{ "clear_tk", { &a3d_clear_sel } },
{ "clear_mv", { &a3d_clearm_sel } },
{ "continue", { &a3d_contin_sel } },
{ "use", { &a3d_render_sel } },
{ "loop", { &a3d_loop_sel } },
{ "view", { &a3d_view_sel } },
{ "kcol", { &a3d_kmo_sel } },
{ "fillp", { &a3d_fmo_sel } },
{ "t_all", { &a3d_a_sel } },
{ "t_seg", { &a3d_s_sel } },
{ "t_frm", { &a3d_frame_sel } },
{ "pen", { &a3d_bru_sel } },
};
Errcode load_a3d_panel(void **ss)
{
return(soft_buttons("optics_panel", a3d_smblist,
Array_els(a3d_smblist), ss));
}
static void seebg_a3d(Menuwndo *mw)
{
seebg_white(mw);
arrange_a3d_menu();
}
static void a3d_go_color_grid(Button *b)
{
go_color_grid(b);
draw_button(&a3d_cco_sel);
}
void a3d_disables(void)
{
static Button *disabtab[] = {
&a3d_pa_view,
&a3d_pa_save,
&a3d_pa_edit,
NULL,
};
got_path = pj_exists(ppoly_name);
set_mbtab_disables(disabtab,!got_path);
}
static Button *g3_spin_sels[] = {
&a3d_spc_3group,
&a3d_spa_3group,
&a3d_spt_3group,
};
static
void sliders_to_point(Short_xyz *pt)
{
a3d_xslider.value = &pt->x;
a3d_yslider.value = &pt->y;
a3d_zslider.value = &pt->z;
}
static
void sliders_500(void)
{
a3d_xslider.min = a3d_yslider.min = a3d_zslider.min = -500;
a3d_xslider.max = a3d_yslider.max = a3d_zslider.max = 500;
}
static
void sliders_center_bounds(void)
{
SHORT cent;
sliders_500();
cent = vb.pencel->width/2;
a3d_xslider.min += cent;
a3d_xslider.max += cent;
cent = vb.pencel->height/2;
a3d_yslider.min += cent;
a3d_yslider.max += cent;
}
static
void change_rot_scale(Button *m)
{
change_mode(m);
arrange_a3d_menu();
draw_button(&a3d_g2_sel);
}
static
void change_size_mode(Button *m)
{
change_mode(m);
arrange_a3d_menu();
draw_button(&a3d_g2_sel);
draw_button(&a3d_g3_sel);
draw_button(&a3d_g4_sel);
draw_buttontop(&a3d_sz_ratio);
}
static
void change_spin_mode(Button *m)
{
change_mode(m);
arrange_a3d_menu();
draw_button(&a3d_g2_sel);
draw_button(&a3d_g3_sel);
}
static
void change_ado_mode(Button *m)
{
change_mode(m);
arrange_a3d_menu();
a3d_disables();
draw_button(&a3d_g0_sel);
draw_button(&a3d_g4_sel);
}
static
void set_axis(Button *m)
{
vs.move3.spin_axis.x = vs.move3.spin_axis.y = vs.move3.spin_axis.z = 0;
switch (m->identity)
{
case 0:
vs.move3.spin_axis.x = 100;
break;
case 1:
vs.move3.spin_axis.y = 100;
break;
case 2:
vs.move3.spin_axis.z = 100;
break;
}
draw_button(&a3d_g2_sel);
}
static
void csame_size(Button *m)
{
(void)m;
pj_copy_structure(&vs.move3.size_center,
&vs.move3.spin_center, sizeof(Short_xyz) );
draw_button(&a3d_g2_sel);
}
static
void csame_spin(Button *m)
{
(void)m;
pj_copy_structure(&vs.move3.spin_center,
&vs.move3.size_center, sizeof(Short_xyz) );
draw_button(&a3d_g2_sel);
}
static
void csize_default(Button *m)
{
(void)m;
default_center(&vs.move3.size_center);
draw_button(&a3d_g2_sel);
}
static
void see_size_ratio(Button *m)
{
char buf[12];
int over, under;
Boolean sign = FALSE;
switch (vs.ado_size)
{
case 1: /* x */
over = vs.move3.xp;
under = vs.move3.xq;
break;
case 2: /* y */
over = vs.move3.yp;
under = vs.move3.yq;
break;
case 0: /* center */
case 3: /* both */
over = vs.move3.bp;
under = vs.move3.bq;
break;
}
if (over < 0)
{
sign = TRUE;
over = -over;
}
if (under < 0)
{
sign = !sign;
under = -under;
}
/* Convert to unsigned to avoid divide overflow in huge cases. */
over *= 100;
over /= under;
sprintf(buf, "%s%d.%2d", (sign ? "-" : ""), over/100, over%100);
tr_string(buf, ' ', '0');
m->datme = buf;
ncorner_text(m);
}
static
void feel_rdc_qslider(Button *m)
{
feel_qslider(m);
draw_buttontop(&a3d_sz_ratio);
}
static
void cspin_default(Button *m)
{
(void)m;
default_center(&vs.move3.spin_center);
draw_button(&a3d_g2_sel);
}
static
void clear_track(void)
{
switch (vs.ado_mode)
{
case ADO_SPIN:
default_center(&vs.move3.spin_center);
pj_copy_structure(&default_vs.move3.spin_axis, &vs.move3.spin_axis,
sizeof(Short_xyz) );
pj_copy_structure(&default_vs.move3.spin_theta, &vs.move3.spin_theta,
sizeof(Short_xyz) );
iscale_theta();
break;
case ADO_SIZE:
pj_copy_words(&default_vs.move3.xp, &vs.move3.xp, 6);
default_center(&vs.move3.size_center);
break;
case ADO_MOVE:
pj_copy_structure(&default_vs.move3.move, &vs.move3.move,
sizeof(Short_xyz) );
break;
case ADO_PATH:
pj_delete(ppoly_name);
a3d_disables();
break;
}
draw_button(&a3d_g0_sel);
}
static void clear_pos(void)
{
ado_clear_pos();
a3d_disables();
draw_button(&a3d_g0_sel);
}
static void mgo_path_files(void)
{
hide_mp();
go_files(FTP_PATH);
show_mp();
}
void arrange_a3d_menu(void)
{
inspin = 0;
a3d_g4_sel.children = &a3d_spm_group;
switch (vs.ado_mode)
{
case ADO_SPIN: /* spin */
a3d_g0_sel.children = &a3d_spsz_group;
a3d_g1_sel.children = &a3d_spin_group;
a3d_g2_sel.children = &a3d_slider_group;
a3d_g3_sel.children = g3_spin_sels[vs.ado_spin];
switch (vs.ado_spin)
{
case SPIN_CENTER: /* center */
sliders_to_point(&vs.move3.spin_center);
sliders_center_bounds();
break;
case SPIN_AXIS: /* axis */
sliders_to_point(&vs.move3.spin_axis);
sliders_500();
break;
case SPIN_TURNS: /* turns */
inspin = 1;
sliders_to_point(&rot_theta);
a3d_xslider.min = a3d_yslider.min = a3d_zslider.min =
-vs.ado_turn*10;
a3d_xslider.max = a3d_yslider.max = a3d_zslider.max =
vs.ado_turn*10;
break;
}
break;
case ADO_SIZE: /* size */
a3d_g0_sel.children = &a3d_spsz_group;
a3d_g1_sel.children = &a3d_size_group;
a3d_g2_sel.children = &a3d_szslide_group;
a3d_g3_sel.children = &a3d_eslide_sel;
a3d_g4_sel.children = &a3d_szm_group;
switch (vs.ado_size)
{
case 0: /* center */
a3d_g2_sel.children = &a3d_slider_group;
a3d_g3_sel.children = &a3d_szc_3group;
a3d_g4_sel.children = &a3d_spm_group;
sliders_to_point(&vs.move3.size_center);
sliders_center_bounds();
break;
case 1: /* x */
a3d_rdc_slider.value = &vs.move3.xp;
a3d_enl_slider.value = &vs.move3.xq;
break;
case 2: /* y */
a3d_rdc_slider.value = &vs.move3.yp;
a3d_enl_slider.value = &vs.move3.yq;
break;
case 3: /* both */
a3d_rdc_slider.value = &vs.move3.bp;
a3d_enl_slider.value = &vs.move3.bq;
break;
}
break;
case ADO_MOVE: /* move */
a3d_g0_sel.children = &a3d_move_group;
sliders_to_point(&vs.move3.move);
sliders_500();
break;
case ADO_PATH: /* path */
a3d_g0_sel.children = &a3d_path_group;
break;
}
}
|
xingyunwork/neb.vm
|
example/node/testUnit.js
|
<reponame>xingyunwork/neb.vm
const Uint = require('../../src/node/uint');
var Uint64 = Uint.Uint64;
var a = new Uint64(7);
var b = new Uint64("2");
console.log({
'a+b': a.plus(b).toString(10), // 9
'a-b': a.minus(b).toString(10), // 5
'a*b': a.mul(b).toString(10), // 14
'a/b': a.div(b).toString(10), // 3
'a%b': a.mod(b).toString(10), // 1
'a^b': a.pow(b).toString(10), // 49
'a>b': a.cmp(b) == 1, // true
'a==0': a.isZero(), // false
'a': a.toString(), // 7
'MaxUint64': Uint64.MaxValue.toString(16), // ffffffffffffffff
});
|
fieranmason/mem-admin
|
scripts/generateProjectData.js
|
<reponame>fieranmason/mem-admin
'use strict';
var request = require('request');
var _ = require('lodash');
var fs = require('fs');
var memfile = './mem.json';
var epicfile = './epic.json';
// Initialize files.
fs.writeFileSync(memfile, "[]");
fs.writeFileSync(epicfile, "[]");
function addToObj(obj, file) {
var configFile = fs.readFileSync(file);
var config = JSON.parse(configFile);
config.push(obj);
var configJSON = JSON.stringify(config);
fs.writeFileSync(file, configJSON);
}
// Get the project listing first.
// Get the objectID for the project in question.
var base = "https://projects.eao.gov.bc.ca";
request ({
url : base + "/api/project",
method : 'GET'
}, function (err, res, body) {
if (err) {
console.log("error:",err);
} else if (res.statusCode !== 200) {
console.log("error:",err);
} else {
console.log("200 OK.");
var projects = JSON.parse(body);
_.each(projects, function (p) {
var newObj = {
_id: p._id,
code: p.code,
eacDecision: p.eacDecision,
name: p.name,
proponent: {
_id: p.proponent._id,
name: p.proponent.name
}
};
addToObj(newObj, epicfile);
});
}
});
base = "https://mines.empr.gov.bc.ca";
request ({
url : base + "/api/project",
method : 'GET'
}, function (err, res, body) {
if (err) {
console.log("error:",err);
} else if (res.statusCode !== 200) {
console.log("error:",err);
} else {
console.log("200 OK.");
var projects = JSON.parse(body);
_.each(projects, function (p) {
var ownership = {};
if (p.proponent !== null) {
ownership._id = p.proponent._id;
ownership.name = p.proponent.name;
} else {
ownership.name = p.ownership;
}
var newObj = {
_id: p._id,
code: p.code,
name: p.name,
memPermitID: p.memPermitID,
proponent: ownership
};
addToObj(newObj, memfile);
});
}
});
|
dgolombek/protobuffy
|
lib/protobuf/tasks/compile.rake
|
<filename>lib/protobuf/tasks/compile.rake
require 'fileutils'
namespace :protobuf do
desc 'Clean & Compile the protobuf source to ruby classes. Pass PB_NO_CLEAN=1 if you do not want to force-clean first.'
task :compile, [ :package, :source, :destination, :plugin, :file_extension ] do |tasks, args|
args.with_defaults(:destination => 'lib')
args.with_defaults(:source => 'definitions')
args.with_defaults(:plugin => 'ruby')
args.with_defaults(:file_extension => '.pb.rb')
unless do_not_clean?
force_clean!
::Rake::Task[:clean].invoke(args[:package], args[:destination], args[:file_extension])
end
command = []
command << "protoc"
command << "--#{args[:plugin]}_out=#{args[:destination]}"
command << "-I #{args[:source]}"
command << "#{args[:source]}/#{args[:package]}/*.proto"
command << "#{args[:source]}/#{args[:package]}/**/*.proto"
full_command = command.join(' ')
puts full_command
exec(full_command)
end
desc 'Clean the generated *.pb.rb files from the destination package. Pass PB_FORCE_CLEAN=1 to skip confirmation step.'
task :clean, [ :package, :destination, :file_extension ] do |task, args|
args.with_defaults(:destination => 'lib')
args.with_defaults(:file_extension => '.pb.rb')
file_extension = args[:file_extension].sub(/\*?\.+/, '')
files_to_clean = ::File.join(args[:destination], args[:package], '**', "*.#{file_extension}")
if force_clean? || permission_to_clean?(files_to_clean)
::Dir.glob(files_to_clean).each do |file|
::FileUtils.rm(file)
end
end
end
def do_not_clean?
! ::ENV.key?('PB_NO_CLEAN')
end
def force_clean?
::ENV.key?('PB_FORCE_CLEAN')
end
def force_clean!
::ENV['PB_FORCE_CLEAN'] = '1'
end
def permission_to_clean?(files_to_clean)
puts "Do you really want to remove files matching pattern #{files_to_clean}? (y/n)"
::STDIN.gets.chomp =~ /y(es)?/i
end
end
|
iliff/knowledge-retriever
|
trainer/trainers.py
|
import os
import torch
from sklearn import metrics
from torch import nn, optim
class Trainer:
"""
A class for generalizing training process to parts of model.
Parameters
----------
model : A HuggingFace or PyTorch model
Needs to fit for a question-answering task.
tokenizer : A HuggingFace Fast tokenizer
For tokenizing model or submodel inputs.
dataloader : A dataloader.dataloaders (function) loader
For getting train datasets ready for batch training.
child_module_to_train : string
A submodule of the model that is an attribute of the model.
validation_dataloader : A dataloader.dataloaders (function) loader
For getting validation datasets ready for batch training.
criterion : A loss function from `torch.nn`
For calculating loss of model or submodule.
optimizer : A `torch.optim` optimizer
For optimizing the model or submodule.
val_metrics : dict of {name: sklearn metric function}
For calcuating validation metrics.
epochs : int
Number of epochs to train for.
lr : float
Learning rate to apply in optimizer.
batch_size : int
The number of samples per batch.
device : A `torch.device` object or a string representing such an object
For handling internal tokenization.
"""
def __init__(self,
model,
tokenizer,
dataloader,
submodule_to_train=None,
validation_dataloader=None,
criterion=nn.CrossEntropyLoss(),
optimizer=optim.AdamW,
val_metrics=['accuracy', 'f1', 'precision', 'recall'],
epochs=3,
lr=2e-5,
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
**optimizer_kwargs):
self.model = model.to(device)
self.module_to_train = getattr(model, submodule_to_train) if submodule_to_train else model
if self.module_to_train is not None:
self._focus_params_and_dropouts()
self.tokenizer = tokenizer
self.dataloader = dataloader
self.validation_dataloader = validation_dataloader
self.criterion = criterion
self.optimizer = optimizer(model.parameters(), lr=lr, **optimizer_kwargs)
self.epochs = epochs
self.metrics = val_metrics
self.device = device
self._current_epoch = 1
self._metric_functions = {
'accuracy': metrics.accuracy_score,
'f1': metrics.f1_score,
'precision': metrics.precision_score,
'recall': metrics.recall_score
}
def _focus_params_and_dropouts(self):
self.model.eval()
for param in self.model.parameters():
param.requires_grad = False
self.module_to_train.train()
for param in self.module_to_train.parameters():
param.requires_grad = True
def _run_validation(self):
self.module_to_train.eval()
running_loss = 0.
y_true, y_pred = [], []
# get all predictions for every batch in validation dataloader
for b, batch in enumerate(self.validation_dataloader):
with torch.no_grad():
argmax, loss, questions, targets, tokenized = self._run_batch(batch, y_pred, y_true)
running_loss += loss.item()
else:
# check to see if a prediction seems reasonable
print(questions[-1])
print('predicted answer:', self.tokenizer.decode(tokenized['input_ids'][-1][argmax[-1][0]:argmax[-1][1]]))
print('actual answer:', self.tokenizer.decode(tokenized['input_ids'][-1][targets[-1][0]:targets[-1][1]]))
# calculate metrics
y_true, y_pred = torch.tensor(y_true).numpy(), torch.tensor(y_pred).numpy()
metric_scores = {}
for metric in self.metrics:
if metric == 'accuracy':
metric_scores[metric] = self._metric_functions.get(metric, metric)(y_true, y_pred)
else:
metric_scores[metric] = self._metric_functions.get(metric, metric)(y_true, y_pred, average='macro')
print(f'VALIDATION Epoch: {self._current_epoch} Batch: {b + 1} '
f'Running Context Loss: {running_loss / (b + 1)} '
f'Context Loss: {loss.item()} Metrics: {metric_scores}')
return dict(loss=running_loss / (b + 1), **metric_scores)
def _run_batch(self, batch, y_pred, y_true):
questions, contexts, targets = batch
inputs = list(zip(questions, contexts))
targets = targets.to(self.device)
tokenized = self.tokenizer(inputs,
max_length=512,
padding=True,
return_tensors='pt',
).to(self.device)
outputs = self.module_to_train(**tokenized)
logits = outputs.get('logits', # high-level model
outputs.get('last_hidden_state', # bare model
# or traditional question-answer model
torch.stack([outputs.start_logits, outputs.end_logits], dim=-1)))
loss = self.criterion(logits, targets.to(self.device))
argmax = torch.argmax(logits, dim=-2) if logits.shape[-1] == 2 else torch.argmax(logits, dim=-1)
print(logits.shape)
y_pred.extend(argmax.flatten().cpu().detach().tolist())
y_true.extend(torch.tensor(targets).flatten().tolist())
return argmax, loss, questions, targets, tokenized
def _train_epoch(self):
self.module_to_train.train()
running_loss = 0.
y_true, y_pred = [], []
for b, batch in enumerate(self.dataloader):
argmax, loss, questions, targets, tokenized = self._run_batch(batch, y_pred, y_true)
running_loss += loss.item()
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
print(f'TRAIN Epoch: {self._current_epoch} Batch: {b + 1} '
f'Running Context Loss: {running_loss / (b + 1)} '
f'Context Loss: {loss.item()}')
def train(self):
for epoch in range(self.epochs):
self._train_epoch()
validation_results = self._run_validation()
filename_args = [f'valid_{k}={v:.4f}' for k, v in sorted(validation_results.items())]
if self._current_epoch % 4 == 0:
torch.save(self.model.to('cpu').state_dict(),
os.path.join(
'modeldata',
f'model_{self._current_epoch}_' + '_'.join(filename_args) + '.pt'
))
self.model = self.model.to(self.device)
self._current_epoch += 1
return validation_results
|
InnovativeOnlineIndustries/MatterOverdrive
|
src/main/java/com/hrznstudio/matteroverdrive/client/renderer/entity/MORenderers.java
|
package com.hrznstudio.matteroverdrive.client.renderer.entity;
import com.hrznstudio.matteroverdrive.block.MOBlocks;
import com.hrznstudio.matteroverdrive.client.renderer.entity.projectile.KunaiRenderer;
import com.hrznstudio.matteroverdrive.client.renderer.tile.RenderAndroidStation;
import com.hrznstudio.matteroverdrive.entity.MOEntities;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
public class MORenderers {
public static void register() {
RenderingRegistry.registerEntityRenderingHandler(MOEntities.KUNAI.get(), KunaiRenderer::new);
RenderTypeLookup.setRenderLayer(MOBlocks.ANDROID_STATION.get(), RenderType.getCutout());
ClientRegistry.bindTileEntityRenderer(MOBlocks.ANDROID_STATION_TILE.get(), RenderAndroidStation::new);
}
}
|
cifpfbmoll/proyecto-3a-evaluacion-monos_constructures
|
MCE/src/Ventanas/RecursosHumanos/MainPage/RrhhMainPageController.java
|
<filename>MCE/src/Ventanas/RecursosHumanos/MainPage/RrhhMainPageController.java
package Ventanas.RecursosHumanos.MainPage;
import ObjetosCrucero.Servicios.RecursosHumanos;
import Utils.Credentials;
import Utils.Mensajes;
import Utils.WindowUtils;
import Ventanas.Fx.Animation;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
public class RrhhMainPageController {
//Elementos graficos
@FXML
AnchorPane mainCard;
@FXML
Label fechaYHora;
@FXML
Label welcomeMessage;
@FXML
Label userInfo;
//Botones del Worktab
@FXML
VBox addUser;
@FXML
VBox listUser;
@FXML
VBox removeUser;
//Botones GUI
@FXML
ImageView logout;
@FXML
ScrollPane wtabScroll;
//Para cerrar la sesión
EventHandler<MouseEvent> logOut = event ->{
try {
Credentials.logOut(event);
} catch (IOException ioe) {
ioe.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
};
//Añadir un empleado
EventHandler<MouseEvent> crearEmpleado = event -> {
Animation.card_animation_EXIT_TO_LEFT(
mainCard,
"Añadir un empleado",
"/Ventanas/RecursosHumanos/AddStaff/rrhh_add_staff.fxml",
event
);
};
//Ver lista de empleados
EventHandler<MouseEvent> verListaEmpledos = event -> {
Animation.card_animation_EXIT_TO_LEFT(
mainCard,
"Lista de empleados",
"/Ventanas/RecursosHumanos/ViewStaff/rrhh_view_staff.fxml",
event
);
};
//Tramitar despido
EventHandler<MouseEvent> despedirEmpledo = event -> {
Animation.card_animation_EXIT_TO_LEFT(
mainCard,
"Lista de empleados",
"/Ventanas/RecursosHumanos/DeleteStaff/rrhh_delete_staff.fxml",
event
);
};
@FXML
private void initialize() throws InterruptedException {
// Ajustamos la opacidad de entrada
mainCard.setOpacity(0);
// Ajustando la velocidad de "Scroll" del ScrollPane
final double SPEED = 0.005;
wtabScroll.getContent().setOnScroll(scrollEvent -> {
double deltaY = scrollEvent.getDeltaY() * SPEED;
wtabScroll.setVvalue(wtabScroll.getVvalue() - deltaY);
});
// Generando el texto de la ventana
Animation.setFechaYHora(fechaYHora);
userInfo.setText(Mensajes.getUserInfo());
welcomeMessage.setText(Mensajes.getMensajeBienvenida());
// Asignando los eventos a los botones
addUser.addEventHandler(MouseEvent.MOUSE_CLICKED, crearEmpleado);
listUser.addEventHandler(MouseEvent.MOUSE_CLICKED, verListaEmpledos);
removeUser.addEventHandler(MouseEvent.MOUSE_CLICKED, despedirEmpledo);
logout.addEventHandler(MouseEvent.MOUSE_CLICKED, logOut);
Tooltip.install(logout, new Tooltip("Cerrar sesión")); //etiqueta del logout
//Creando la animación de entrada
Animation.card_animation_TOP_CENTER(mainCard);
}
}
|
nwashangai/open-school-system
|
application/routes/api/teacherRoutes.js
|
<reponame>nwashangai/open-school-system
import express from 'express';
import TeacherController from '../../controllers/TeacherController';
import auth from '../../middlewares/passport';
import { checkInput } from '../../middlewares/validate';
const router = express.Router();
// router.get('/', auth, StudentController.getStudents);
router.post('/create', auth, checkInput, TeacherController.setTeacher);
export default router;
|
dubiety/azure-sdk-for-python
|
sdk/ml/azure-ai-ml/azure/ai/ml/_schema/automl/automl_vertical.py
|
<reponame>dubiety/azure-sdk-for-python
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from azure.ai.ml._restclient.v2022_02_01_preview.models import (
LogVerbosity,
)
from azure.ai.ml._schema.automl.automl_job import AutoMLJobSchema
from azure.ai.ml._schema.core.fields import fields, StringTransformedEnum
from azure.ai.ml._schema.job.input_output_fields_provider import InputsField
from azure.ai.ml._utils.utils import camel_to_snake
class AutoMLVerticalSchema(AutoMLJobSchema):
log_verbosity = StringTransformedEnum(
allowed_values=[o.value for o in LogVerbosity],
casing_transform=camel_to_snake,
load_default=LogVerbosity.INFO,
)
training_data = InputsField()
|
leonchen83/jetty.project
|
jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationIntrospector.java
|
<reponame>leonchen83/jetty.project
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.annotations;
import java.io.File;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.Source;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.FragmentDescriptor;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebDescriptor;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestAnnotationIntrospector
{
@Test
public void testIsIntrospectable() throws Exception
{
try (StacklessLogging ignore = new StacklessLogging(AnnotationIntrospector.class))
{
WebAppContext wac = new WebAppContext();
AnnotationIntrospector introspector = new AnnotationIntrospector(wac);
//can't introspect nothing
assertFalse(introspector.isIntrospectable(null, null));
//can introspect if no metadata to say otherwise
assertTrue(introspector.isIntrospectable(new Object(), null));
//can introspect if metdata isn't a BaseHolder
assertTrue(introspector.isIntrospectable(new Object(), new Object()));
//an EMBEDDED sourced servlet can be introspected
ServletHolder holder = new ServletHolder();
holder.setHeldClass(ServletE.class);
assertTrue(introspector.isIntrospectable(new ServletE(), holder));
//a JAVAX API sourced servlet can be introspected
holder = new ServletHolder(Source.JAVAX_API);
holder.setHeldClass(ServletE.class);
assertTrue(introspector.isIntrospectable(new ServletE(), holder));
//an ANNOTATION sourced servlet can be introspected
holder = new ServletHolder(new Source(Source.Origin.ANNOTATION, ServletE.class.getName()));
holder.setHeldClass(ServletE.class);
assertTrue(introspector.isIntrospectable(new ServletE(), holder));
//a DESCRIPTOR sourced servlet can be introspected if web.xml metdata-complete==false
File file = MavenTestingUtils.getTestResourceFile("web31false.xml");
Resource resource = Resource.newResource(file);
wac.getMetaData().setWebDescriptor(new WebDescriptor(resource));
holder = new ServletHolder(new Source(Source.Origin.DESCRIPTOR, resource.toString()));
assertTrue(introspector.isIntrospectable(new ServletE(), holder));
//a DESCRIPTOR sourced servlet can be introspected if web-fragment.xml medata-complete==false && web.xml metadata-complete==false
file = MavenTestingUtils.getTestResourceFile("web-fragment4false.xml");
resource = Resource.newResource(file);
wac.getMetaData().addFragmentDescriptor(Resource.newResource(file.getParentFile()), new FragmentDescriptor(resource));
holder = new ServletHolder(new Source(Source.Origin.DESCRIPTOR, resource.toString()));
assertTrue(introspector.isIntrospectable(new ServletE(), holder));
//a DESCRIPTOR sourced servlet cannot be introspected if web-fragment.xml medata-complete==true (&& web.xml metadata-complete==false)
file = MavenTestingUtils.getTestResourceFile("web-fragment4true.xml");
resource = Resource.newResource(file);
wac.getMetaData().addFragmentDescriptor(Resource.newResource(file.getParentFile()), new FragmentDescriptor(resource));
holder = new ServletHolder(new Source(Source.Origin.DESCRIPTOR, resource.toString()));
assertFalse(introspector.isIntrospectable(new ServletE(), holder));
//a DESCRIPTOR sourced servlet cannot be introspected if web.xml medata-complete==true
file = MavenTestingUtils.getTestResourceFile("web31true.xml");
resource = Resource.newResource(file);
wac.getMetaData().setWebDescriptor(new WebDescriptor(resource));
holder = new ServletHolder(new Source(Source.Origin.DESCRIPTOR, resource.toString()));
assertFalse(introspector.isIntrospectable(new ServletE(), holder));
}
}
}
|
adligo/fabricate_tests.adligo.org
|
src/org/adligo/fabricate_tests/common/system/FabSystemTrial.java
|
package org.adligo.fabricate_tests.common.system;
import org.adligo.fabricate.common.en.FabricateEnConstants;
import org.adligo.fabricate.common.files.FabFileIO;
import org.adligo.fabricate.common.files.xml_io.FabXmlFileIO;
import org.adligo.fabricate.common.i18n.I_FabricateConstants;
import org.adligo.fabricate.common.log.DeferredLog;
import org.adligo.fabricate.common.log.I_FabLog;
import org.adligo.fabricate.common.system.BufferedInputStream;
import org.adligo.fabricate.common.system.ComputerInfoDiscovery;
import org.adligo.fabricate.common.system.ExecutingProcess;
import org.adligo.fabricate.common.system.FabSystem;
import org.adligo.fabricate.common.system.I_LocatableRunnable;
import org.adligo.fabricate.common.system.I_ProcessBuilderWrapper;
import org.adligo.fabricate.common.system.I_ProcessRunnable;
import org.adligo.fabricate.common.system.I_RunMonitor;
import org.adligo.tests4j.shared.asserts.reference.CircularDependencies;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_4mockito.MockitoSourceFileTrial;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
@SourceFileScope (sourceClass=FabSystem.class, minCoverage=70.0,
allowedCircularDependencies=CircularDependencies.AllowInnerOuterClasses)
public class FabSystemTrial extends MockitoSourceFileTrial {
@SuppressWarnings("boxing")
@Test
public void testMethodsGetsAndSets() throws Exception {
FabSystem fabSystem = new FabSystem();
I_FabLog log = mock(I_FabLog.class);
fabSystem.setLog(log);
assertNotSame(log, fabSystem.getLog());
assertSame(log, ((DeferredLog) fabSystem.getLog()).getDelegate());
fabSystem.setArgs(Collections.singletonMap("k",null));
assertEquals(" k", fabSystem.toScriptArgs());
assertEquals(0, fabSystem.getArgValues("k").size());
fabSystem.setArgs(Collections.singletonMap("k", "v"));
assertEquals("v", fabSystem.getArgValue("k"));
assertNull(fabSystem.getArgValue("v"));
assertTrue(fabSystem.hasArg("k"));
assertFalse(fabSystem.hasArg("v"));
List<String> vals = fabSystem.getArgValues("k");
assertContains(vals, "v");
assertEquals(1, vals.size());
assertEquals(" k=v", fabSystem.toScriptArgs());
fabSystem.setArgs(Collections.singletonMap("k2", "v1,v2,v3"));
vals = fabSystem.getArgValues("k2");
assertContains(vals, "v1");
assertContains(vals, "v2");
assertContains(vals, "v3");
assertEquals(3, vals.size());
assertEquals(" k2=v1,v2,v3", fabSystem.toScriptArgs());
assertEquals(Runtime.getRuntime().availableProcessors(), fabSystem.getAvailableProcessors());
assertEquals(System.getProperty("java.version", "Unknown"),
fabSystem.getProperty("java.version", "Unknown"));
assertEquals(File.pathSeparator, fabSystem.pathSeparator());
}
@SuppressWarnings("boxing")
@Test
public void testMethodsFactories() throws Exception {
FabSystem fabSystem = new FabSystem();
//array blocking queue
ArrayBlockingQueue<Boolean> queue = fabSystem.newArrayBlockingQueue(Boolean.class, 1);
assertNotNull(queue);
queue.put(true);
assertTrue(queue.take());
long ft = fabSystem.getCurrentTime();
long now = System.currentTimeMillis();
assertGreaterThanOrEquals(ft, now);
assertTrue(ft -1000 < now);
assertNull(fabSystem.getenv("nullvoid"));
assertEquals(System.lineSeparator(), fabSystem.lineSeparator());
assertEquals(Locale.getDefault().getLanguage(), fabSystem.getDefaultLanguage());
assertEquals(Locale.getDefault().getCountry(), fabSystem.getDefaultCountry());
assertEquals(FabFileIO.class.getName(), fabSystem.getFileIO().getClass().getName());
assertEquals(FabXmlFileIO.class.getName(), fabSystem.getXmlFileIO().getClass().getName());
assertSame(Thread.currentThread(), fabSystem.currentThread());
ByteArrayOutputStream baos = fabSystem.newByteArrayOutputStream();
assertNotNull(baos);
assertNotSame(baos, fabSystem.newByteArrayOutputStream());
I_ProcessBuilderWrapper pbw = fabSystem.newProcessBuilder(new String[] {""});
assertNotNull(pbw);
ProcessBuilder pb = pbw.getDelegate();
assertNotNull(pb);
I_ProcessBuilderWrapper pbw2 = fabSystem.newProcessBuilder(new String [] {""});
assertNotNull(pbw2);
ProcessBuilder pb2 = pbw2.getDelegate();
assertNotNull(pb2);
assertNotSame(pb, pb2);
InputStream in = mock(InputStream.class);
BufferedInputStream bis = fabSystem.newBufferedInputStream(in);
assertNotNull(bis);
assertSame(in, bis.getDelegate());
//run monitor
final AtomicBoolean ran = new AtomicBoolean(false);
I_LocatableRunnable r = new I_LocatableRunnable() {
@Override
public void run() {
ran.set(true);
}
@Override
public String getCurrentLocation() {
return "cl";
}
@Override
public String getAdditionalDetail() {
// TODO Auto-generated method stub
return null;
}
};
I_RunMonitor rm = fabSystem.newRunMonitor(r, 0);
assertEquals(0, rm.getSequence());
rm.run();
assertTrue(ran.get());
ran.set(false);
rm = fabSystem.newRunMonitor(r, 1);
assertEquals(1, rm.getSequence());
rm.run();
assertTrue(ran.get());
ExecutorService es = fabSystem.newFixedThreadPool(1);
assertEquals("java.util.concurrent.Executors$FinalizableDelegatedExecutorService", es.getClass().getName());
ExecutorService es2 = fabSystem.newFixedThreadPool(2);
assertEquals("java.util.concurrent.ThreadPoolExecutor", es2.getClass().getName());
Process proc = mock(Process.class);
I_ProcessRunnable pr = fabSystem.newProcessRunnable(proc);
assertNotNull(pr);
ExecutingProcess ep = fabSystem.newExecutingProcess(proc);
assertNotNull(ep);
I_FabricateConstants constants = fabSystem.newFabConstantsDiscovery("languageCode", "countryCode");
assertEquals(FabricateEnConstants.class.getName(), constants.getClass().getName());
}
@SuppressWarnings("boxing")
@Test
public void testMethodsGetComputerInfoDiscoveryDelegates() {
FabSystem sys = new FabSystem();
//yep mirror the asserts just to do the passthrough,
// the implementation is tested in ComputerInfoDiscoverTrial
assertEquals(ComputerInfoDiscovery.getJavaVersion(sys), sys.getJavaVersion());
String os = ComputerInfoDiscovery.getOperatingSystem(sys);
assertEquals(os, sys.getOperatingSystem());
assertEquals(ComputerInfoDiscovery.getOperatingSystemVersion(sys, os),
sys.getOperatingSystemVersion(os));
String [] cpuInfo = ComputerInfoDiscovery.getCpuInfo(sys, os);
String [] sysCpuInfo = sys.getCpuInfo(os);
assertEquals(cpuInfo[0], sysCpuInfo[0]);
assertEquals(cpuInfo[1], sysCpuInfo[1]);
assertEquals(cpuInfo.length, sysCpuInfo.length);
assertEquals(2, sysCpuInfo.length);
}
}
|
ggustin93/decide-showcase
|
packages/icons/src/line/CommentHeart.js
|
import React from 'react';
export default function CommentHeart(props) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={24} height={24} {...props}>
<path d="M12,8.35a3.07,3.07,0,0,0-3.54.53,3,3,0,0,0,0,4.24L11.29,16a1,1,0,0,0,1.42,0l2.83-2.83a3,3,0,0,0,0-4.24A3.07,3.07,0,0,0,12,8.35Zm2.12,3.36L12,13.83,9.88,11.71a1,1,0,0,1,0-1.42,1,1,0,0,1,1.41,0,1,1,0,0,0,1.42,0,1,1,0,0,1,1.41,0A1,1,0,0,1,14.12,11.71ZM12,2A10,10,0,0,0,2,12a9.89,9.89,0,0,0,2.26,6.33l-2,2a1,1,0,0,0-.21,1.09A1,1,0,0,0,3,22h9A10,10,0,0,0,12,2Zm0,18H5.41l.93-.93a1,1,0,0,0,0-1.41A8,8,0,1,1,12,20Z" />
</svg>
);
}
|
egormkn/Study-courses
|
Translation methods/4. Generator of parsers/src/main/java/ru/shemplo/mt/task4/TreeWalkListener.java
|
<reponame>egormkn/Study-courses
package ru.shemplo.mt.task4;
import java.util.LinkedList;
import java.util.List;
import ru.shemplo.dsau.stuctures.Trio;
import ru.shemplo.mt.task4.CodeGenerator.Repeat;
import ru.shemplo.mt.task4.antlr.GrammarBaseListener;
import ru.shemplo.mt.task4.antlr.GrammarParser.Code_expressionContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Code_operationContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Grammar_declarationContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Grammar_ruleContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Grammar_rule_entryContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Grammar_rule_operaionContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Local_variableContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Local_variablesContext;
import ru.shemplo.mt.task4.antlr.GrammarParser.Operation_unitContext;
import ru.shemplo.mt.task4.dmy.NonTerminal;
import ru.shemplo.mt.task4.dmy.Terminal;
public class TreeWalkListener extends GrammarBaseListener {
private final GrammarCollector COLLECTOR;
public TreeWalkListener (final GrammarCollector collector) {
this.COLLECTOR = collector;
}
@Override
public void enterGrammar_rule (Grammar_ruleContext ctx) {
String name = ctx.ident ().IDENT ().getText ();
System.out.println ("Enter to / " + name);
NonTerminal rule = new NonTerminal (name);
COLLECTOR.addNonTerminal (rule);
if (ctx.local_variables () != null) {
Local_variablesContext localVars = ctx.local_variables ();
System.out.println ("/ " + name + " has local variables:");
for (Local_variableContext localVar : localVars.local_variable ()) {
Code_expressionContext codeExpr = localVar.code_expression ();
String type = localVar.ident ().IDENT ().getText (),
varName = codeExpr.ident ().IDENT ().getText (),
value = codeExpr.operation_unit ().getText ();
Code_operationContext operation = codeExpr.code_operation ();
if (operation != null) { value += operation.getText (); }
value = CodeGenerator.replaceSnippets (value);
System.out.println ("~ " + type + " " + varName + " = " + value);
rule.addLocalVariable (type, varName, value);
}
}
List <Trio <String, Repeat, String>> branch = new LinkedList <> ();
for (Grammar_rule_entryContext ruleEntry : ctx.grammar_rule_entry ()) {
String dependRule = ruleEntry.ident ().IDENT ().getText ();
Repeat repeat = ruleEntry.repeat;
String action = "";
Grammar_rule_operaionContext operaion = ruleEntry.grammar_rule_operaion ();
if (operaion != null) {
List <Code_expressionContext> codes = operaion.code_expression ();
if (codes != null) {
StringBuilder sb = new StringBuilder ();
for (Code_expressionContext code : codes) {
String leftName = code.ident ().getText ();
sb.append ("((#) context).").append (leftName).append ("=");
Operation_unitContext unit = code.operation_unit ();
String unitStr = unit.getText ();
if (unitStr.charAt (0) == '$') {
unitStr = unitStr.replaceAll ("\\$(\\w|[.])+[.](\\w+)", "$2");
} else if (unitStr.charAt (0) != '"') {
sb.append ("((#) context).");
}
sb.append (unitStr);
Code_operationContext coc = code.code_operation ();
while (coc != null) {
sb.append (coc.PLUS ().getText ());
unit = coc.operation_unit ();
unitStr = unit.getText ();
if (unitStr.charAt (0) == '$') {
unitStr = unitStr.replaceAll ("\\$(\\w|[.])+[.](\\w+)", "$2");
} else if (unitStr.charAt (0) != '"') {
sb.append ("((#) context).");
}
sb.append (unitStr);
coc = coc.code_operation ();
}
}
action = sb.toString ().replace ("$space", "\" \"")
.replace ("$s", "\" \"").replace ("$dq", "\"\\\"\"");
}
}
branch.add (Trio.mt (dependRule, repeat, action));
if (ruleEntry.VLINE () != null) {
System.out.println ("/ " + name + " has alternative branch: ");
for (Trio <String, Repeat, String> entry : branch) {
System.out.println ("> " + entry);
}
rule.addAlternamtive (branch);
branch = new LinkedList <> ();
}
}
if (branch.size () > 0) {
System.out.println ("/ " + name + " has alternative branch: ");
for (Trio <String, Repeat, String> entry : branch) {
System.out.println ("> " + entry);
}
rule.addAlternamtive (branch);
}
System.out.println ();
}
@Override
public void enterGrammar_declaration (Grammar_declarationContext ctx) {
String name = ctx.ident ().IDENT ().getText ();
//System.out.println ("Enter to | " + name);
boolean isRegexp = false;
String pattern = "";
if (ctx.expand_ident () != null) {
pattern = ctx.expand_ident ().getText ();
isRegexp = false;
} else if (ctx.regular_expression () != null) {
pattern = ctx.regular_expression ().getText ().replace ("/", "");
isRegexp = true;
} else if (ctx.character () != null) {
pattern = ctx.character ().getText ().replace ("'", "");
isRegexp = false;
}
pattern = CodeGenerator.replaceSnippets (pattern);
Terminal rule = new Terminal (name, pattern, isRegexp);
COLLECTOR.addTerminal (rule);
}
}
|
guoshucan/mpaas
|
ghost.framework.context/src/main/java/ghost/framework/context/bean/factory/IClassAnnotationBeanFactory.java
|
<reponame>guoshucan/mpaas
package ghost.framework.context.bean.factory;
import ghost.framework.beans.annotation.application.Application;
import ghost.framework.beans.annotation.module.Module;
import ghost.framework.beans.annotation.module.ModuleArtifact;
import ghost.framework.context.application.IApplication;
import ghost.framework.context.base.ICoreInterface;
import ghost.framework.context.loader.ILoader;
import ghost.framework.context.module.IModuleContainer;
import ghost.framework.context.proxy.IMethodInvocationHandler;
import java.lang.annotation.Annotation;
/**
* package: ghost.framework.context.bean.factory
*
* @Author: 郭树灿{gsc-e590}
* @link: 手机:13715848993, QQ 27048384
* @Description:类型注释事件工厂接口
* @Date: 2020/1/8:18:47
* @param <O> 发起方核心接口
* @param <T> 目标对象类型
* @param <E> 类型事件目标处理类型
* @param <V> 返回类型
*/
public interface IClassAnnotationBeanFactory
<
O extends ICoreInterface,
T extends Class<?>,
E extends IClassAnnotationBeanTargetHandle<O, T, V, String, Object>,
V extends Object
>
extends IAnnotationBeanFactory<O, T, E>, ILoader<O, T, E> {
/**
* 获取注释对象
* 当在事件的Target目标处理对象获取不到注释类型原始对象时在注释链获取该注释原始对象
* 通过 {@link IAnnotationBeanFactory ::getAnnotationClass()} 该注释类型获取注释源对象
* @param event 事件对象
* @param <R>
* @return 返回Target目标注释类型,如果Target目标注释类型不存在将在注释执行链获取原始注释对象
*/
@Override
default <R extends Annotation> R getAnnotation(E event) {
//在目标对判断是否包含该注释,如果存在直接获取
if(event.getTarget().isAnnotationPresent(this.getAnnotationClass())){
return (R)event.getTarget().getAnnotation(this.getAnnotationClass());
}
//在目标没有当前类型注释,该注释存在域注释本身依赖注释
return (R)this.forEachAnnotation(event.getTarget().getDeclaredAnnotations());
}
/**
* 排除类型注释是否无效或已经加载
* @param event 事件对象
* @return 返回true表示注释无效或已经加载的注释,返回false表示注释存在,并且未加载过
*/
@Override
default boolean isLoader(E event) {
//判断注释是否对
return event.getExecutionAnnotationChain().containsKey(this.getAnnotationClass()) && event.getExecutionAnnotationChain().get(this.getAnnotationClass()).isExecute();
}
/**
* 创建实例
*
* @param event 事件对象
* @param handler 代理回调对象
*/
default void newCglibInstance(E event, IMethodInvocationHandler handler) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newCglibInstance(event, handler);
}
/**
* 创建实例
*
* @param event 事件对象
* @param i 实现代理构建对象继承的接口
* @param handler 代理回调对象
*/
default void newCglibInstance(E event, Class<?> i, IMethodInvocationHandler handler) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newCglibInstance(event, i, handler);
}
/**
* 创建实例
*
* @param event 事件对象
* @param interfaces 实现代理构建对象继承的接口
* @param handler 代理回调对象
*/
default void newCglibInstance(E event, Class<?>[] interfaces, IMethodInvocationHandler handler) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newCglibInstance(event, interfaces, handler);
}
/**
* 创建实例
*
* @param event 事件对象
* @param handler 代理回调对象
*/
default void newJavassistInstance(E event, IMethodInvocationHandler handler) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newJavassistInstance(event, handler);
}
/**
* 创建实例
*
* @param event 事件对象
* @param i 实现代理构建对象继承的接口
* @param handler 代理回调对象
*/
default void newJavassistInstance(E event, Class<?> i, IMethodInvocationHandler handler) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newJavassistInstance(event, i, handler);
}
/**
* 创建实例
*
* @param event 事件对象
* @param interfaces 实现代理构建对象继承的接口
* @param handler 代理回调对象
*/
default void newJavassistInstance(E event, Class<?>[] interfaces, IMethodInvocationHandler handler) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newJavassistInstance(event, interfaces, handler);
}
// /**
// * jdk创建代理对象
// * @param event
// * @param handler
// */
// default void newJdkInstance(E event, InvocationHandler handler){
// //构建类型实例
// event.getExecuteOwner().getBean(IClassAnnotationEventFactoryContainer.class).newJdkInstance(event, handler);
// }
/**
* 创建实例
*
* @param event 事件对象
*/
default void newInstance(E event) {
//构建类型实例
event.getExecuteOwner().getBean(IClassAnnotationBeanFactoryContainer.class).newInstance(event);
}
/**
* 获取类型模块注释
* 1、如果类型没有 {@link Module} 注释将对 {@code @param <O>} 发起方进行Bean。
* 2、如果类型有 {@link Module} 注释但是没有指定模块名称将对当前线程上线文模块进行Bean,
* 如果当前模块上线文没有模块对象将引发错误。
* 3、如果类型有 {@link Module} 注释并指定模块名称时,
* 将从 {@link IApplication} 应用的Bean容器中获取 {@link IModuleContainer} 模块容器接口中获取模块并使用此模块进行Bean,
* 如果没有找到模块对象将引发错误。
* @param event 事件对象
* @return
*/
@Override
default Module getModuleAnnotation(E event) {
if (event.getTarget().isAnnotationPresent(Module.class)) {
return this.getProxyAnnotationObject(event.getTarget().getAnnotation(Module.class));
}
return null;
}
/**
* 获取类型应用注释
* 1、如果类型没有 {@link Application} 注释将对 {@code @param <O>} 发起方进行Bean。
* 2、如果类型有 {@link Application} 注释将对应用 {@link IApplication} 应用的Bean进行绑定,
* @param event 事件对象
* @return
*/
@Override
default Application getApplicationAnnotation(E event) {
if (event.getTarget().isAnnotationPresent(Application.class)) {
return this.getProxyAnnotationObject(event.getTarget().getAnnotation(Application.class));
}
return null;
}
/**
*
* @param event 事件对象
* @return
*/
@Override
default ModuleArtifact getModuleArtifactAnnotation(E event) {
if (event.getTarget().isAnnotationPresent(ModuleArtifact.class)) {
return this.getProxyAnnotationObject(event.getTarget().getAnnotation(ModuleArtifact.class));
}
return null;
}
}
|
vivek12345/web-engineer-exercise
|
src/components/Pagination.js
|
<gh_stars>0
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
const Pagination = props => {
const { limit, onPageChanged, offset, items } = props;
const isPrevBtnDisabled = offset <= 0;
const isNextBtnDisabled = items.length < limit;
const onClick = type => {
if (isPrevBtnDisabled && type === 'prev') return false;
if (isNextBtnDisabled && type === 'next') return false;
let newOffset = type === 'prev' ? offset - limit : offset + limit;
onPageChanged(limit, newOffset);
};
const paginationItemStyleClasses = cx(
'block cursor-pointer hover:text-white hover:bg-blue-600 text-blue-600 border-r border-grey-light px-3 py-2'
);
let prevBtnClassName = `${paginationItemStyleClasses}`;
let nextBtnClassName = `${paginationItemStyleClasses}`;
if (isPrevBtnDisabled) {
prevBtnClassName = `${prevBtnClassName} previous opacity-50 cursor-not-allowed disabled`;
}
if (isNextBtnDisabled) {
nextBtnClassName = `${nextBtnClassName} next opacity-50 cursor-not-allowed disabled`;
}
return (
<ul className="nav flex list-reset border border-grey-light rounded overflow-hidden">
<li onClick={() => onClick('prev')}>
<span className={prevBtnClassName}>Previous</span>
</li>
<li onClick={() => onClick('next')}>
<span className={nextBtnClassName}>Next</span>
</li>
</ul>
);
};
Pagination.propTypes = {
offset: PropTypes.number,
limit: PropTypes.number,
items: PropTypes.array,
onPageChanged: PropTypes.func
};
Pagination.defaultProps = {
offset: 0,
limit: 25,
items: [],
onPageChanged: () => {}
};
export { Pagination };
|
PazerOP/DemoLib2
|
DemoLib2/net/netmessages/NetEntityMessage.cpp
|
<filename>DemoLib2/net/netmessages/NetEntityMessage.cpp
#include "NetEntityMessage.hpp"
#include "BitIO/BitIOReader.hpp"
#include "BitIO/BitIOWriter.hpp"
#include "misc/Exceptions.hpp"
#include "net/data/SourceConstants.hpp"
void NetEntityMessage::ReadElementInternal(BitIOReader& reader)
{
reader.Read(m_EntityIndex, MAX_EDICT_BITS);
reader.Read(m_ClassID, MAX_SERVER_CLASS_BITS);
const auto bitCount = reader.ReadInline<uint_fast32_t>(MAX_ENTITY_MSG_LENGTH_BITS);
m_Data = reader.TakeSpan(BitPosition::FromBits(bitCount));
}
void NetEntityMessage::WriteElementInternal(BitIOWriter& writer) const
{
writer.Write(m_EntityIndex, MAX_EDICT_BITS);
writer.Write(m_ClassID, MAX_SERVER_CLASS_BITS);
auto clone = m_Data;
clone.Seek(BitPosition::Zero(), Seek::Start);
writer.Write(clone.Length().TotalBits(), MAX_ENTITY_MSG_LENGTH_BITS);
writer.Write(clone);
}
void NetEntityMessage::GetDescription(std::ostream& description) const
{
description << "svc_EntityMessage: entity " << m_EntityIndex <<
", class " << m_ClassID << ", bytes " << m_Data.Length().TotalBytes();
}
void NetEntityMessage::ApplyWorldState(WorldState& world) const
{
// Like usermessages, we're ignoring these for now.
//throw NotImplementedException();
}
|
uc3m-aerospace/MOLTO-IT-UI
|
src/components/MoltoIt/CelestialBodies.js
|
<reponame>uc3m-aerospace/MOLTO-IT-UI<gh_stars>0
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { FORM_DATA } from '../../constants';
import Mars from '../../assets/images/Planets/1024/mars.png';
import Earth from '../../assets/images/Planets/1024/earth.png';
import Mercury from '../../assets/images/Planets/1024/mercury.png';
import Venus from '../../assets/images/Planets/1024/venus.png';
import Uranus from '../../assets/images/Planets/1024/uranus.png';
import Neptune from '../../assets/images/Planets/1024/neptune.png';
import Jupyter from '../../assets/images/Planets/1024/jupyter.png';
import Saturn from '../../assets/images/Planets/1024/saturn.png';
import { motion } from 'framer-motion';
import { Icon } from '@chakra-ui/core';
import { useWindowSize } from '../Hooks/useWindowSize';
const planets = [
{
index: 0,
name: 'Mercury',
value: '1',
image: Mercury,
position: 575,
position_mobile: 730
},
{
index: 1,
name: 'Earth',
value: '3',
image: Earth,
position: 410,
position_mobile: 540
},
{
index: 2,
name: 'Mars',
value: '4',
image: Mars,
position: 245,
position_mobile: 360
},
{
index: 3,
name: 'Venus',
value: '2',
image: Venus,
position: 80,
position_mobile: 175
},
{
index: 4,
name: 'Jupiter',
value: '5',
image: Jupyter,
position: -85,
position_mobile: -10
},
{
index: 5,
name: 'Saturn',
image: Saturn,
value: '6',
position: -250,
position_mobile: -280
},
{
index: 6,
name: 'Uranus',
image: Uranus,
value: '7',
position: -415,
position_mobile: -535
},
{
index: 7,
name: 'Neptune',
image: Neptune,
value: '8',
position: -580,
position_mobile: -722
}
];
const CelestialBodies = (props) => {
const size = useWindowSize();
const dispatch = useDispatch();
const data = useSelector((state) => state.moltoItConfig);
const toOrFrom = props.component === 'From' ? 'planet_dep' : 'planet_arr';
const [isSelected, setIsSelected] = useState();
const [planetSelected, setPlanetSelected] = useState(data[toOrFrom]);
const [positionX, setPositionX] = useState(
size.width <= 768
? planets.find((record) => record.name === data[toOrFrom]).position_mobile
: planets.find((record) => record.name === data[toOrFrom]).position
);
const _handleChange = (planet) => {
dispatch({
type: FORM_DATA,
payload: { [toOrFrom]: planet.name, type: 'CHANGE_PLANET' }
});
if (size.width >= 768) {
const distance = parseInt(planetSelected.index) - parseInt(planet.index);
if (parseInt(distance) >= 0) {
setPositionX(positionX + 165 * Math.abs(distance));
} else {
setPositionX(positionX - 165 * Math.abs(distance));
}
}
};
const planetVariant = {
closed: {
transition: { duration: 0.5, ease: [0.37, 0.04, 0.2, 1] },
scale: 1
},
open: {
transition: { duration: 0.5, ease: [0.37, 0.04, 0.2, 1] },
scale: 1.4
}
};
const _handleState = () => {
if (toOrFrom === 'planet_dep') {
planets.map((planet) => {
return planet.name === data.planet_dep
? setPlanetSelected(planet)
: null;
});
} else {
planets.map((planet) => {
return planet.name === data.planet_arr
? setPlanetSelected(planet)
: null;
});
}
};
useEffect(() => {
_handleState();
});
const handleArrow = (side) => {
if (side === 'left') {
const previousPlanet = planets[planetSelected.index - 1];
const lastPlanet = planets[7];
if (planetSelected.index === 0) {
setPlanetSelected(lastPlanet.name);
_handleChange(lastPlanet);
if (size.width <= 768) {
setPositionX(
planets.find((record) => record.name === lastPlanet.name)
.position_mobile
);
} else {
setPositionX(
planets.find((record) => record.name === lastPlanet.name).position
);
}
return;
}
if (size.width <= 768) {
console.log(
planets.find((record) => record.name === previousPlanet.name)
.position_mobile
);
setPositionX(
planets.find((record) => record.name === previousPlanet.name)
.position_mobile
);
} else {
setPositionX(
planets.find((record) => record.name === previousPlanet.name).position
);
}
setPlanetSelected(previousPlanet.name);
_handleChange(previousPlanet);
} else {
const nextPlanet = planets[planetSelected.index + 1];
const firstPlanet = planets[0];
if (planetSelected.index === 7) {
setPlanetSelected(firstPlanet.name);
_handleChange(firstPlanet);
if (size.width <= 768) {
setPositionX(
planets.find((record) => record.name === firstPlanet.name)
.position_mobile
);
} else {
setPositionX(
planets.find((record) => record.name === firstPlanet.name).position
);
}
return;
}
if (size.width <= 768) {
console.log(
planets.find((record) => record.name === nextPlanet.name)
.position_mobile
);
setPositionX(
planets.find((record) => record.name === nextPlanet.name)
.position_mobile
);
} else {
setPositionX(
planets.find((record) => record.name === nextPlanet.name).position
);
}
setPlanetSelected(nextPlanet.name);
_handleChange(nextPlanet);
}
};
return (
<div className="celestial__bodies__section">
<motion.div
onClick={() => handleArrow('left')}
className="celestial__body__arrow"
whileHover={{ scale: 1.4 }}
>
<Icon name="chevron-left" size="40px" color="white"></Icon>
</motion.div>
<motion.div
className="celestial__bodies__container"
animate={{ translateX: positionX }}
transition={{ duration: 1, ease: [0.37, 0.04, 0.2, 1] }}
>
{planets.map((planet, index) => (
<motion.div
variants={planetVariant}
onClick={() =>
isSelected ? setIsSelected(false) : setIsSelected(true)
}
initial="closed"
animate={planet.name === planetSelected.name ? 'open' : 'closed'}
whileHover={{ scale: 1.4, opacity: 1 }}
className="body__container"
id={planet.name}
>
<p>{planet.name}</p>
<div
onClick={() => _handleChange(planet)}
key={planet.name}
tabIndex={index}
style={{ outline: 'none', border: 'none', boxShadow: 'none' }}
role="menuitem"
>
<img
onClick={() => _handleChange(planet)}
src={planet.image}
alt={planet.name}
style={{
display: 'block',
width: planet.name === 'Saturn' ? '270px' : '120px'
}}
/>
</div>
</motion.div>
))}
</motion.div>
<motion.div
className="celestial__body__arrow"
onClick={() => handleArrow('right')}
whileHover={{ scale: 1.4 }}
>
<Icon name="chevron-right" size="40px" color="white"></Icon>
</motion.div>
</div>
);
};
export default CelestialBodies;
|
churuxu/codesnippets
|
generic_packet/generic_packet.c
|
<reponame>churuxu/codesnippets<filename>generic_packet/generic_packet.c
#include "generic_packet.h"
#include <string.h>
#include <stdio.h>
#define MAX_NAME 32
#define MAX_VALUE 32
static const uint8_t BCD_TO_HEX[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
10,11,12,13,14,15,16,17,18,19, 0, 0, 0, 0, 0, 0,
20,21,22,23,24,25,26,27,28,29, 0, 0, 0, 0, 0, 0,
30,31,32,33,34,35,36,37,38,39, 0, 0, 0, 0, 0, 0,
40,41,42,43,44,45,46,47,48,49, 0, 0, 0, 0, 0, 0,
50,51,52,53,54,55,56,57,58,59, 0, 0, 0, 0, 0, 0,
60,61,62,63,64,65,66,67,68,69, 0, 0, 0, 0, 0, 0,
70,71,72,73,74,75,76,77,78,79, 0, 0, 0, 0, 0, 0,
80,81,82,83,84,85,86,87,88,89, 0, 0, 0, 0, 0, 0,
90,91,92,93,94,95,96,97,98,99, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
//获取下一段字符串
//"u8 u16 u16" 获取到 u8, 返回剩余字符串
static const char* next_token(const char* str, char* value/*32*/, char* name/*32*/){
const char* ptr = str;
char ch,firstch;
int started;
int vallen, namelen;
int invalue;
if(!*ptr)return NULL;
started = 0;
firstch = 0;
invalue = 0;
vallen = 0;
namelen = 0;
while(*ptr){
ch = *ptr;
if(ch == ' '){
if(started){
break;
}
}else{
if(!firstch){
firstch = ch;
started = 1;
if(ch == '$'){
invalue = 0;
ptr ++; continue;
}else{
invalue = 1;
}
}
if(ch == '|'){
invalue = 1;
ptr ++; continue;
}
if(invalue){
if(vallen >= MAX_VALUE)return NULL;
value[vallen] = ch;
vallen ++;
}else{
if(namelen >= MAX_NAME)return NULL;
name[namelen] = ch;
namelen ++;
}
}
ptr ++;
}
if(vallen >= MAX_VALUE)return NULL;
if(namelen >= MAX_NAME)return NULL;
value[vallen] = 0;
name[namelen] = 0;
return ptr;
}
//用于转换大小端
static void reverse_memcpy(void* dst, void* src, int len){
uint8_t* pdst = (uint8_t*)dst;
uint8_t* psrc = (uint8_t*)src;
int i;
for(i = 0; i<len; i++){
pdst[i] = psrc[len-1-i];
}
}
//u\i开头,整数
static int convert_int_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
int ret = -1;
packet_integer_t v = 0;
uint16_t tempu16;
uint32_t tempu32;
uint64_t tempu64;
int16_t tempi16;
int32_t tempi32;
int64_t tempi64;
switch (fmt[0]){
case 'u':
switch (fmt[1]){
case '8': v = *(uint8_t*)buf; ret = 1; break;
case '1': v = *(uint16_t*)buf; ret = 2; break;
case '3': v = *(uint32_t*)buf; ret = 4; break;
case '6': v = *(uint64_t*)buf; ret = 8; break;
default:break;
}
break;
case 'U':
switch (fmt[1]){
case '8': v = *(uint8_t*)buf; ret = 1; break;
case '1': reverse_memcpy(&tempu16, buf, 2); v = tempu16; ret = 2; break;
case '3': reverse_memcpy(&tempu32, buf, 4); v = tempu32; ret = 4; break;
case '6': reverse_memcpy(&tempu64, buf, 8); v = tempu64; ret = 8; break;
default:break;
}
break;
case 'i':
switch (fmt[1]){
case '8': v = *(int8_t*)buf; ret = 1; break;
case '1': v = *(int16_t*)buf; ret = 2; break;
case '3': v = *(int32_t*)buf; ret = 4; break;
case '6': v = *(int64_t*)buf; ret = 8; break;
default:break;
}
break;
case 'I':
switch (fmt[1]){
case '8': v = *(int8_t*)buf; ret = 1; break;
case '1': reverse_memcpy(&tempi16, buf, 2); v = tempi16; ret = 2; break;
case '3': reverse_memcpy(&tempi32, buf, 4); v = tempi32; ret = 4; break;
case '6': reverse_memcpy(&tempi64, buf, 8); v = tempi64; ret = 8; break;
default:break;
}
break;
default:break;
}
if(ret>0){
val->type = PACKET_VALUE_INTEGER;
val->len = 0;
val->int_val = v;
}
return ret;
}
//f开头,浮点数
static int convert_f_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
int ret = -1;
packet_number_t v = 0;
float f;
double d;
if(fmt[0] == 'f'){
switch (fmt[1]){
case '3': v = (packet_number_t)*(float*)buf; ret = 4; break;
case '6': v = (packet_number_t)*(double*)buf; ret = 8; break;
default:break;
}
}else{
switch (fmt[1]){
case '3': reverse_memcpy(&f, buf, 4); v = f; ret = 4; break;
case '6': reverse_memcpy(&d, buf, 8); v = d; ret = 8; break;
default:break;
}
}
if(ret>0){
val->type = PACKET_VALUE_NUMBER;
val->len = 0;
val->num_val = v;
}
return ret;
}
//B开头,二进制
static int convert_b_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
int len = atoi(fmt + 1);
val->bin_val = buf;
val->len = len;
val->type = PACKET_VALUE_BINARY;
return len;
}
//bcd码
static int convert_bcd_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
int len = atoi(fmt + 1);
int i;
uint8_t data;
packet_integer_t v = 0;
for(i=0;i<len;i++){
if(fmt[0] == 'C'){
data = buf[i];
}else{
data = buf[len - i - 1];
}
v = v*100 + BCD_TO_HEX[data];
}
val->type = PACKET_VALUE_INTEGER;
val->len = 0;
val->int_val = v;
return len;
}
//D H开头,字符串形式数字
static int convert_n_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
packet_integer_t v = 0;
int radix = (fmt[0] == 'H')?16:10;
char temp[32];
char* end = NULL;
char* start = temp;
int len = -1;
int minlen;
int ret = -1;
if(fmt[1] == '*'){ //非固定长度字符串
minlen = (buflen >= 31)?31:buflen;
}else{ //固定长度
len = atoi(fmt + 1);
if(len>31)return -1;
minlen = (buflen >= len)?len:buflen;
}
memcpy(temp, buf, minlen);
temp[minlen] = 0;
v = strtol(temp, &end, radix);
if(fmt[1] == '*'){ //非固定长度
ret = end - start;
if(!ret)ret = -1;
}else{ //固定长度
ret = len;
}
val->type = PACKET_VALUE_INTEGER;
val->len = 0;
val->int_val = v;
return ret;
}
//将数据转换成实际所需的值, 返回用掉的buf长度,失败返回<=0
static int convert_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
switch(fmt[0]){
case 'u':
case 'U':
case 'i':
case 'I':
return convert_int_data(fmt, buf, buflen, val);
case 'f':
case 'F':
return convert_f_data(fmt, buf, buflen, val);
case 'D':
case 'H':
return convert_n_data(fmt, buf, buflen, val);
case 'B':
return convert_b_data(fmt, buf, buflen, val);
case 'C':
case 'c':
return convert_bcd_data(fmt, buf, buflen, val);
default:
break;
}
return -1;
}
//解析
int packet_parse(const char* format, void* buf, int buflen, packet_callback cb, void* udata){
char name[MAX_NAME];
char fmt[MAX_VALUE];
int ret, remainlen, err;
uint8_t* pbuf = (uint8_t*) buf;
packet_value val;
const char* ptr = format;
remainlen = buflen;
while(remainlen > 0){
ptr = next_token(ptr, fmt, name);
if(!ptr)break;
ret = convert_data(fmt, pbuf, remainlen, &val);
if(ret<=0)return ret;
if(name[0]){ //需要回调
err = cb(udata, name, &val);
if(err)return err;
}
remainlen -= ret;
pbuf += ret;
}
return 0;
}
//写入整数数据
static int write_int_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
packet_integer_t v;
uint16_t tempu16;
uint32_t tempu32;
uint64_t tempu64;
int16_t tempi16;
int32_t tempi32;
int64_t tempi64;
if(val->type == PACKET_VALUE_INTEGER){
v = val->int_val;
}else if(val->type == PACKET_VALUE_NUMBER){
v = (packet_integer_t)val->num_val;
}else{
return -1;
}
switch (fmt[0]){
case 'u':
switch (fmt[1]){
case '8': if(buflen<1)return -1; *(uint8_t*)buf = (uint8_t)v; return 1;
case '1': if(buflen<2)return -1; *(uint16_t*)buf = (uint16_t)v; return 2;
case '3': if(buflen<4)return -1; *(uint32_t*)buf = (uint32_t)v; return 4;
case '6': if(buflen<8)return -1; *(uint64_t*)buf = (uint64_t)v; return 8;
default:break;
}
break;
case 'U':
switch (fmt[1]){
case '8': if(buflen<1)return -1; *(uint8_t*)buf = (uint8_t)v; return 1;
case '1': if(buflen<2)return -1; tempu16 = (uint16_t)v; reverse_memcpy(buf, &tempu16, 2); return 2;
case '3': if(buflen<4)return -1; tempu32 = (uint32_t)v; reverse_memcpy(buf, &tempu32, 4); return 4;
case '6': if(buflen<8)return -1; tempu64 = (uint64_t)v; reverse_memcpy(buf, &tempu64, 8); return 8;
default:break;
}
break;
case 'i':
switch (fmt[1]){
case '8': if(buflen<1)return -1; *(int8_t*)buf = (int8_t)v; return 1;
case '1': if(buflen<2)return -1; *(int16_t*)buf = (int16_t)v; return 2;
case '3': if(buflen<4)return -1; *(int32_t*)buf = (int32_t)v; return 4;
case '6': if(buflen<8)return -1; *(int64_t*)buf = (int64_t)v; return 8;
default:break;
}
break;
case 'I':
switch (fmt[1]){
case '8': if(buflen<1)return -1; *(int8_t*)buf = (int8_t)v; return 1;
case '1': if(buflen<2)return -1; tempi16 = (int16_t)v; reverse_memcpy(buf, &tempi16, 2); return 2;
case '3': if(buflen<4)return -1; tempi32 = (int32_t)v; reverse_memcpy(buf, &tempi32, 4); return 4;
case '6': if(buflen<8)return -1; tempi64 = (int64_t)v; reverse_memcpy(buf, &tempi64, 8); return 8;
default:break;
}
break;
default:break;
}
return -1;
}
//写入实数数据
static int write_f_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
packet_number_t v;
float f;
double d;
if(val->type == PACKET_VALUE_INTEGER){
v = (packet_number_t)val->int_val;
}else if(val->type == PACKET_VALUE_NUMBER){
v = val->num_val;
}else{
return -1;
}
if(fmt[1] == 'f'){
switch (fmt[1]){
case '3': if(buflen<4)return -1; *(float*)buf = (float)v; return 4;
case '6': if(buflen<8)return -1; *(double*)buf = (double)v; return 8;
default:break;
}
}else{
switch (fmt[1]){
case '3': if(buflen<4)return -1; f = (float)v; reverse_memcpy(buf, &f, 4); return 4;
case '6': if(buflen<8)return -1; d = (double)v; reverse_memcpy(buf, &d, 8);return 8;
default:break;
}
}
return -1;
}
//写入二进制数据
static int write_bin_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
//packet_number_t v;
if(val->type != PACKET_VALUE_BINARY){
return -1;
}
if(buflen <= val->len)return -1;
memcpy(buf, val->bin_val, val->len);
return val->len;
}
//写入字符串形式整数
static int write_n_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
packet_integer_t v = 0;
const char* pfmt = (fmt[0] == 'H')?"%X":"%d";
char temp[32];
int len = -1;
if(val->type == PACKET_VALUE_INTEGER){
v = val->int_val;
}else if(val->type == PACKET_VALUE_NUMBER){
v = (packet_integer_t)val->num_val;
}else{
return -1;
}
if(fmt[1] == '*'){ //非固定长度字符串
len = snprintf((char*)buf, buflen, pfmt, v);
/*
if(fmt[0] == 'H'){
return snprintf((char*)buf, buflen, pfmt, v);
}else{
return snprintf((char*)buf, buflen, "%d", v);
} */
}else{ //固定长度
len = atoi(fmt + 1);
if(len>31)return -1;
snprintf(temp,32,"%%0%d%s", len, ((fmt[0] == 'H')?"X":"d"));
len = snprintf((char*)buf, buflen, temp, v);
}
return len-1;
}
//写入bcd形式整数
static int write_bcd_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
return -1;
}
//将值写入到buf, 返回写入的长度
static int write_data(const char* fmt, uint8_t* buf, int buflen, packet_value* val){
switch(fmt[0]){
case 'u':
case 'U':
case 'i':
case 'I':
return write_int_data(fmt, buf, buflen, val);
case 'f':
case 'F':
return write_f_data(fmt, buf, buflen, val);
case 'D':
case 'H':
return write_n_data(fmt, buf, buflen, val);
case 'B':
return write_bin_data(fmt, buf, buflen, val);
case 'C':
case 'c':
return write_bcd_data(fmt, buf, buflen, val);
default:
break;
}
return -1;
}
//组装报文
int packet_build(const char* format, void* buf, int buflen, packet_callback cb, void* udata){
char name[MAX_NAME];
char fmt[MAX_VALUE];
int ret, remainlen, err;
uint8_t* pbuf = (uint8_t*) buf;
packet_value val;
const char* ptr = format;
uint8_t b;
remainlen = buflen;
ret = 0;
while(remainlen > 0){
ptr = next_token(ptr, fmt, name);
if(!ptr)break;
if(name[0]){ //需要从变量获取
//从变量获取
val.len = ret;
val.bin_val = buf;
err = cb(udata, name, &val);
if(err)return -1;
//转换成指定格式
ret = write_data(fmt, pbuf, remainlen, &val);
if(ret<=0)return -1;
}else{ //直接是报文值
b = strtol(fmt, NULL, 16);
*pbuf = b;
ret = 1;
}
pbuf += ret;
remainlen -= ret;
}
return pbuf - (uint8_t*)buf;
}
|
wanglong1008/LeetCode
|
src/Question106.java
|
<filename>src/Question106.java
public class Question106 {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return tree(postorder,inorder,0,inorder.length-1,postorder.length-1);
}
public TreeNode tree(int[] postorder, int[] inorder,int left,int right,int head){
if(left>right||head<0){
return null;
}
TreeNode root=new TreeNode(postorder[head]);
int i=0;
for(;i<right-left;i++){
if(inorder[right-i]==postorder[head]) break;
}
root.right=tree(postorder,inorder,right-i+1,right,head-1);
root.left=tree(postorder,inorder,left,right-i-1,head-i-1);
return root;
}
}
|
Pyknic/mutable-stream
|
src/main/java/com/speedment/common/mutablestream/internal/terminate/IteratorTerminatorImpl.java
|
<filename>src/main/java/com/speedment/common/mutablestream/internal/terminate/IteratorTerminatorImpl.java<gh_stars>1-10
package com.speedment.common.mutablestream.internal.terminate;
import com.speedment.common.mutablestream.HasNext;
import com.speedment.common.mutablestream.terminate.IteratorTerminator;
import java.util.Iterator;
import java.util.stream.Stream;
/**
*
* @param <T> the streamed type
*
* @author <NAME>
* @since 1.0.0
*/
public final class IteratorTerminatorImpl<T>
extends AbstractTerminator<T, Stream<T>, Iterator<T>>
implements IteratorTerminator<T> {
public IteratorTerminatorImpl(HasNext<T, Stream<T>> previous, boolean parallel) {
super(previous, parallel);
}
@Override
public Iterator<T> execute() {
try (final Stream<T> stream = buildPrevious()) {
return stream.iterator();
}
}
}
|
duchaojie/Ant-dva-
|
src/services/userManage.js
|
import qs from 'qs';
import request from '../utils/request';
// 新增用户
export async function addUser(params) {
return request({
url: '/system/user/add.json',
method: 'POST',
body: params,
});
}
// 编辑用户
export async function editUser(params) {
return request({
url: '/system/user/edit.json',
method: 'POST',
body: params,
});
}
// 用户列表
export async function fetchUserList(params) {
return request({
url: `/system/user/page.json?${qs.stringify(params)}`,
});
}
// 角色列表
export async function getRoleList(params) {
return request({
url: `/system/role/tree.json?${qs.stringify(params)}`,
});
}
// 用户详情
export async function getUserDetail(params) {
return request({
url: `/system/user/detail.json?${qs.stringify(params)}`,
});
}
// 删除用户
export async function deleteUser(params) {
return request({
url: `/system/user/remove.json?${qs.stringify(params)}`,
method: 'DELETE',
});
}
// 停用用户
export async function stopUser(params) {
return request({
url: `/system/user/disable.json?${qs.stringify(params)}`,
});
}
// 启用用户
export async function startUser(params) {
return request({
url: `/system/user/enable.json?${qs.stringify(params)}`,
});
}
// 重置密码
export async function resetPwd(params) {
return request({
url: `/system/user/reset.json?${qs.stringify(params)}`,
})
}
|
PolySync/core-python-api
|
features/steps/sbp_msg_observation_observations.py
|
# WARNING: Auto-generated file. Any changes are subject to being overwritten
# by setup.py build script.
#!/usr/bin/python
import time
from behave import given
from behave import when
from behave import then
from hamcrest import assert_that, equal_to
try:
import polysync.node as ps_node
from polysync.data_model.types import Py_sbp_msg_observation_observations
from polysync.data_model._internal.compare import sbp_msg_observation_observations_type_convert_testable, Py_sbp_msg_observation_observations_initialize_random
from polysync.data_model.message_support.sbp_msg_observation_observations import publish, subscribe
except ImportError:
raise ImportError(
'Py_sbp_msg_observation_observations module dependencies \
missing for tests, is the project built?')
@given('I have a Py_sbp_msg_observation_observations object')
def step_impl(context):
pass
@when('I convert it to its C API equivalent a sbp_msg_observation_observations')
def step_impl(context):
pass
@when('I convert the sbp_msg_observation_observations back to a Py_sbp_msg_observation_observations')
def step_impl(context):
pass
@then('the sbp_msg_observation_observations values are equivalent to each Py_sbp_msg_observation_observations value')
def step_impl(context):
msg = Py_sbp_msg_observation_observations_initialize_random()
result = sbp_msg_observation_observations_type_convert_testable(msg)
assert not result, result
@given('a sbp_msg_observation_observations.publish function exists')
def step_impl(context):
assert callable(publish)
@when('I try to publish something that is not of type Py_sbp_msg_observation_observations')
def step_impl(context):
bad_obj = "not the right type of object!"
context.exception = None
try:
publish(bad_obj)
except Exception as e:
context.exception = e
@then('a {exeption} indicates the type was not Py_sbp_msg_observation_observations')
def step_impl(context, exeption):
assert isinstance(context.exception, eval(exeption)), \
"Invalid exception %s - expected %s" \
% (type(context.exception).__name__, exeption)
GLOBAL_TIMESTAMP = None
GLOBAL_GUID = None
def Py_sbp_msg_observation_observations_handler(msg):
if msg.header.src_guid == GLOBAL_GUID:
global GLOBAL_TIMESTAMP
GLOBAL_TIMESTAMP = msg.header.timestamp
@given(u'I have a licensed PsNode for publishing Py_sbp_msg_observation_observations')
def step_impl(context):
assert context.node_ref
global GLOBAL_GUID
GLOBAL_GUID = context.my_guid
@given(u'I have a Py_sbp_msg_observation_observations')
def step_impl(context):
context.msg = Py_sbp_msg_observation_observations()
context.msg.header.timestamp = 0xFFFF
@given(u'I have a handler for Py_sbp_msg_observation_observations subscription')
def step_impl(context):
assert Py_sbp_msg_observation_observations_handler
subscribe(handler=Py_sbp_msg_observation_observations_handler)
@when(u'I publish my Py_sbp_msg_observation_observations')
def step_impl(context):
publish(context.msg)
@then(u'I receive the corresponding Py_sbp_msg_observation_observations in my handler')
def step_impl(context):
global GLOBAL_TIMESTAMP
while not GLOBAL_TIMESTAMP:
time.sleep(1)
assert_that(context.msg.header.timestamp, equal_to(GLOBAL_TIMESTAMP))
|
patil215/v8
|
fuzzer_output/interesting/sample_1554139355242.js
|
function main() {
const v2 = [1337,1337,1337,1337,1337];
const v6 = Promise * 13.37;
const v7 = [13.37,13.37];
const v9 = [Promise,"log1p",v2,v7];
const v10 = {shift:v9,round:1337,isSealed:1337,rightContext:"log1p",source:"log1p",getUint16:"log1p"};
function v11(v12,v13,v14,v15) {
for (let v19 = 0; v19 < 5; v19++) {
const v20 = v15[v19];
}
}
const v25 = v11(v6,v10,v9,v9);
const v26 = [-2277210505];
const v37 = [1337];
const v39 = [1337];
for (let v45 = 0; v45 < 100; v45++) {
const v46 = v11(10,Function,1337,v26,Function);
}
}
%NeverOptimizeFunction(main);
main();
|
Nyadist/lightnovel-crawler
|
sources/en/t/travistranslations.py
|
# -*- coding: utf-8 -*-
import logging
from bs4.element import Tag
from lncrawl.core.crawler import Crawler
logger = logging.getLogger(__name__)
class TravisTranslations(Crawler):
base_url = 'https://travistranslations.com/'
def read_novel_info(self):
soup = self.get_soup(self.novel_url)
possible_title = soup.select_one('.novel-info h1[title]')
assert isinstance(possible_title, Tag)
self.novel_title = possible_title['title']
logger.info('Novel title: %s', self.novel_title)
possible_image = soup.select_one('meta[property="og:image"]')
if isinstance(possible_image, Tag):
self.novel_cover = self.absolute_url(possible_image['content'])
# end if
logger.info('Novel cover: %s', self.novel_cover)
possible_author = soup.select_one('.novel-info .author')
if isinstance(possible_author, Tag):
self.novel_author = possible_author.text.strip()
# end if
logger.info('Novel author: %s', self.novel_author)
for a in soup.select('ul.releases li a'):
chap_id = 1 + len(self.chapters)
vol_id = 1 + len(self.chapters) // 100
if chap_id % 100 == 1:
self.volumes.append({'id': vol_id})
# end if
title = None
possible_chapter_title = a.select_one('span')
if isinstance(possible_chapter_title, Tag):
title = possible_chapter_title.text.strip()
# end if
self.chapters.append({
'id': chap_id,
'volume': vol_id,
'title': title,
'url': self.absolute_url(a['href']),
})
# end for
# end def
def download_chapter_body(self, chapter):
soup = self.get_soup(chapter['url'])
para = []
for span in soup.select('p > span[style="font-weight: 400;"]'):
text = span.text.strip()
if text:
para.append(f'<p>{text}</p>')
# end if
# end for
return '\n'.join(para)
# end def
# end class
|
Learning-and-Intelligent-Systems/predicators
|
third_party/fast_downward_translator/sas_tasks.py
|
SAS_FILE_VERSION = 3
DEBUG = False
class SASTask:
"""Planning task in finite-domain representation.
The user is responsible for making sure that the data fits a number
of structural restrictions. For example, conditions should generally
be sorted and mention each variable at most once. See the validate
methods for details.
"""
def __init__(self, variables, mutexes, init, goal, operators, axioms,
metric):
self.variables = variables
self.mutexes = mutexes
self.init = init
self.goal = goal
self.operators = sorted(operators,
key=lambda op:
(op.name, op.prevail, op.pre_post))
self.axioms = sorted(axioms,
key=lambda axiom: (axiom.condition, axiom.effect))
self.metric = metric
if DEBUG:
self.validate()
def validate(self):
"""Fail an assertion if the task is invalid.
A task is valid if all its components are valid. Valid tasks
are almost in a kind of "canonical form", but not quite. For
example, operators and axioms are permitted to be listed in
any order, even though it would be possible to require some
kind of canonical sorting.
Note that we require that all derived variables are binary.
This is stricter than what later parts of the planner are
supposed to handle, but some parts of the translator rely on
this. We might want to consider making this a general
requirement throughout the planner.
Note also that there is *no* general rule on what the init (=
fallback) value of a derived variable is. For example, in
PSR-Large #1, it can be either 0 or 1. While it is "usually"
1, code should not rely on this.
"""
self.variables.validate()
for mutex in self.mutexes:
mutex.validate(self.variables)
self.init.validate(self.variables)
self.goal.validate(self.variables)
for op in self.operators:
op.validate(self.variables)
for axiom in self.axioms:
axiom.validate(self.variables, self.init)
assert self.metric is False or self.metric is True, self.metric
def dump(self):
print("variables:")
self.variables.dump()
print("%d mutex groups:" % len(self.mutexes))
for mutex in self.mutexes:
print("group:")
mutex.dump()
print("init:")
self.init.dump()
print("goal:")
self.goal.dump()
print("%d operators:" % len(self.operators))
for operator in self.operators:
operator.dump()
print("%d axioms:" % len(self.axioms))
for axiom in self.axioms:
axiom.dump()
print("metric: %s" % self.metric)
def output(self, stream):
print("begin_version", file=stream)
print(SAS_FILE_VERSION, file=stream)
print("end_version", file=stream)
print("begin_metric", file=stream)
print(int(self.metric), file=stream)
print("end_metric", file=stream)
self.variables.output(stream)
print(len(self.mutexes), file=stream)
for mutex in self.mutexes:
mutex.output(stream)
self.init.output(stream)
self.goal.output(stream)
print(len(self.operators), file=stream)
for op in self.operators:
op.output(stream)
print(len(self.axioms), file=stream)
for axiom in self.axioms:
axiom.output(stream)
def get_encoding_size(self):
task_size = 0
task_size += self.variables.get_encoding_size()
for mutex in self.mutexes:
task_size += mutex.get_encoding_size()
task_size += self.goal.get_encoding_size()
for op in self.operators:
task_size += op.get_encoding_size()
for axiom in self.axioms:
task_size += axiom.get_encoding_size()
return task_size
class SASVariables:
def __init__(self, ranges, axiom_layers, value_names):
self.ranges = ranges
self.axiom_layers = axiom_layers
self.value_names = value_names
def validate(self):
"""Validate variables.
All variables must have range at least 2, and derived variables
must have range exactly 2. See comment on derived variables in
the docstring of SASTask.validate.
"""
assert len(self.ranges) == len(self.axiom_layers) == len(
self.value_names)
for (var_range, layer, var_value_names) in zip(self.ranges,
self.axiom_layers,
self.value_names):
assert var_range == len(var_value_names)
assert var_range >= 2
assert layer == -1 or layer >= 0
if layer != -1:
assert var_range == 2
def validate_fact(self, fact):
"""Assert that fact is a valid (var, value) pair."""
var, value = fact
assert 0 <= var < len(self.ranges)
assert 0 <= value < self.ranges[var]
def validate_condition(self, condition):
"""Assert that the condition (list of facts) is sorted, mentions each
variable at most once, and only consists of valid facts."""
last_var = -1
for (var, value) in condition:
self.validate_fact((var, value))
assert var > last_var
last_var = var
def dump(self):
for var, (rang,
axiom_layer) in enumerate(zip(self.ranges,
self.axiom_layers)):
if axiom_layer != -1:
axiom_str = " [axiom layer %d]" % axiom_layer
else:
axiom_str = ""
print("v%d in {%s}%s" % (var, list(range(rang)), axiom_str))
def output(self, stream):
print(len(self.ranges), file=stream)
for var, (rang, axiom_layer, values) in enumerate(
zip(self.ranges, self.axiom_layers, self.value_names)):
print("begin_variable", file=stream)
print("var%d" % var, file=stream)
print(axiom_layer, file=stream)
print(rang, file=stream)
assert rang == len(values), (rang, values)
for value in values:
print(value, file=stream)
print("end_variable", file=stream)
def get_encoding_size(self):
# A variable with range k has encoding size k + 1 to also give the
# variable itself some weight.
return len(self.ranges) + sum(self.ranges)
class SASMutexGroup:
def __init__(self, facts):
self.facts = sorted(facts)
def validate(self, variables):
"""Assert that the facts in the mutex group are sorted and unique and
that they are all valid."""
for fact in self.facts:
variables.validate_fact(fact)
assert self.facts == sorted(set(self.facts))
def dump(self):
for var, val in self.facts:
print("v%d: %d" % (var, val))
def output(self, stream):
print("begin_mutex_group", file=stream)
print(len(self.facts), file=stream)
for var, val in self.facts:
print(var, val, file=stream)
print("end_mutex_group", file=stream)
def get_encoding_size(self):
return len(self.facts)
class SASInit:
def __init__(self, values):
self.values = values
def validate(self, variables):
"""Validate initial state.
Assert that the initial state contains the correct number of
values and that all values are in range.
"""
assert len(self.values) == len(variables.ranges)
for fact in enumerate(self.values):
variables.validate_fact(fact)
def dump(self):
for var, val in enumerate(self.values):
print("v%d: %d" % (var, val))
def output(self, stream):
print("begin_state", file=stream)
for val in self.values:
print(val, file=stream)
print("end_state", file=stream)
class SASGoal:
def __init__(self, pairs):
self.pairs = sorted(pairs)
def validate(self, variables):
"""Assert that the goal is nonempty and a valid condition."""
assert self.pairs
variables.validate_condition(self.pairs)
def dump(self):
for var, val in self.pairs:
print("v%d: %d" % (var, val))
def output(self, stream):
print("begin_goal", file=stream)
print(len(self.pairs), file=stream)
for var, val in self.pairs:
print(var, val, file=stream)
print("end_goal", file=stream)
def get_encoding_size(self):
return len(self.pairs)
class SASOperator:
def __init__(self, name, prevail, pre_post, cost):
self.name = name
self.prevail = sorted(prevail)
self.pre_post = self._canonical_pre_post(pre_post)
self.cost = cost
def _canonical_pre_post(self, pre_post):
# Return a sorted and uniquified version of pre_post. We would
# like to just use sorted(set(pre_post)), but this fails because
# the effect conditions are a list and hence not hashable.
def tuplify(entry):
var, pre, post, cond = entry
return var, pre, post, tuple(cond)
def listify(entry):
var, pre, post, cond = entry
return var, pre, post, list(cond)
pre_post = map(tuplify, pre_post)
pre_post = sorted(set(pre_post))
pre_post = list(map(listify, pre_post))
return pre_post
def validate(self, variables):
"""Validate the operator.
Assert that
1. Prevail conditions are valid conditions (i.e., sorted and
all referring to different variables)
2. The pre_post list is sorted by (var, pre, post, cond), and the
same (var, pre, post, cond) 4-tuple is not repeated.
3. Effect conditions are valid conditions and do not contain variables
from the pre- or prevail conditions.
4. Variables occurring in pre_post rules do not have a prevail
condition.
5. Preconditions in pre_post are -1 or valid facts.
6. Effects are valid facts.
7. Effect variables are non-derived.
8. If a variable has multiple pre_post rules, then pre is
identical in all these rules.
9. There is at least one effect.
10. Costs are non-negative integers.
Odd things that are *not* illegal:
- The effect in a pre_post rule may be identical to the
precondition or to an effect condition of that effect.
TODO/open question:
- It is currently not very clear what the semantics of operators
should be when effects "conflict", i.e., when multiple effects
trigger and want to set a given variable to two different
values. In the case where both are unconditional effects, we
should make sure that our representation doesn't actually
contain two such effects, but when at least one of them is
conditional, things are not so easy.
To make our life simpler when generating SAS+ tasks from
PDDL tasks, it probably makes most sense to generalize the
PDDL rule in this case: there is a value order where certain
values "win" over others in this situation. It probably
makes sense to say the "highest" values should win in this
case, because that's consistent with the PDDL rules if we
say false = 0 and true = 1, and also with our sort order of
effects it means we get the right result if we just apply
effects in sequence.
But whatever we end up deciding, we need to be clear about it,
document it and make sure that all of our code knows the rules
and follows them.
"""
variables.validate_condition(self.prevail)
assert self.pre_post == self._canonical_pre_post(self.pre_post)
prevail_vars = {var for (var, value) in self.prevail}
pre_values = {}
for var, pre, post, cond in self.pre_post:
variables.validate_condition(cond)
assert var not in prevail_vars
if pre != -1:
variables.validate_fact((var, pre))
variables.validate_fact((var, post))
assert variables.axiom_layers[var] == -1
if var in pre_values:
assert pre_values[var] == pre
else:
pre_values[var] = pre
for var, pre, post, cond in self.pre_post:
for cvar, cval in cond:
assert (cvar not in pre_values or pre_values[cvar] == -1)
assert (cvar not in prevail_vars)
assert self.pre_post
assert self.cost >= 0 and self.cost == int(self.cost)
def dump(self):
print(self.name)
print("Prevail:")
for var, val in self.prevail:
print(" v%d: %d" % (var, val))
print("Pre/Post:")
for var, pre, post, cond in self.pre_post:
if cond:
cond_str = " [%s]" % ", ".join(
["%d: %d" % tuple(c) for c in cond])
else:
cond_str = ""
print(" v%d: %d -> %d%s" % (var, pre, post, cond_str))
def output(self, stream):
print("begin_operator", file=stream)
print(self.name[1:-1], file=stream)
print(len(self.prevail), file=stream)
for var, val in self.prevail:
print(var, val, file=stream)
print(len(self.pre_post), file=stream)
for var, pre, post, cond in self.pre_post:
print(len(cond), end=' ', file=stream)
for cvar, cval in cond:
print(cvar, cval, end=' ', file=stream)
print(var, pre, post, file=stream)
print(self.cost, file=stream)
print("end_operator", file=stream)
def get_encoding_size(self):
size = 1 + len(self.prevail)
for var, pre, post, cond in self.pre_post:
size += 1 + len(cond)
if pre != -1:
size += 1
return size
def get_applicability_conditions(self):
"""Return the combined applicability conditions (prevail conditions and
preconditions) of the operator.
Returns a sorted list of (var, value) pairs. This is guaranteed
to contain at most one fact per variable and must hence be non-
contradictory.
"""
conditions = {}
for var, val in self.prevail:
assert var not in conditions
conditions[var] = val
for var, pre, post, cond in self.pre_post:
if pre != -1:
assert var not in conditions or conditions[var] == pre
conditions[var] = pre
return sorted(conditions.items())
class SASAxiom:
def __init__(self, condition, effect):
self.condition = sorted(condition)
self.effect = effect
assert self.effect[1] in (0, 1)
for _, val in condition:
assert val >= 0, condition
def validate(self, variables, init):
"""Validate the axiom.
Assert that the axiom condition is a valid condition, that the
effect is a valid fact, that the effect variable is a derived
variable, and that the layering condition is satisfied.
See the docstring of SASTask.validate for information on the
restriction on derived variables. The layering condition boils
down to:
1. Axioms always set the "non-init" value of the derived
variable.
2. Derived variables in the condition must have a lower of
equal layer to derived variables appearing in the effect.
3. Conditions with equal layer are only allowed when the
condition uses the "non-init" value of that variable.
TODO/bug: rule #1 is currently disabled because we currently
have axioms that violate it. This is likely due to the
"extended domain transition graphs" described in the Fast
Downward paper, Section 5.1. However, we want to eventually
changes this. See issue454. For cases where rule #1 is violated,
"non-init" should be "init" in rule #3.
"""
variables.validate_condition(self.condition)
variables.validate_fact(self.effect)
eff_var, eff_value = self.effect
eff_layer = variables.axiom_layers[eff_var]
assert eff_layer >= 0
eff_init_value = init.values[eff_var]
## The following rule is currently commented out because of
## the TODO/bug mentioned in the docstring.
# assert eff_value != eff_init_value
for cond_var, cond_value in self.condition:
cond_layer = variables.axiom_layers[cond_var]
if cond_layer != -1:
assert cond_layer <= eff_layer
if cond_layer == eff_layer:
cond_init_value = init.values[cond_var]
## Once the TODO/bug above is addressed, the
## following four lines can be simplified because
## we are guaranteed to land in the "if" branch.
if eff_value != eff_init_value:
assert cond_value != cond_init_value
else:
assert cond_value == cond_init_value
def dump(self):
print("Condition:")
for var, val in self.condition:
print(" v%d: %d" % (var, val))
print("Effect:")
var, val = self.effect
print(" v%d: %d" % (var, val))
def output(self, stream):
print("begin_rule", file=stream)
print(len(self.condition), file=stream)
for var, val in self.condition:
print(var, val, file=stream)
var, val = self.effect
print(var, 1 - val, val, file=stream)
print("end_rule", file=stream)
def get_encoding_size(self):
return 1 + len(self.condition)
|
mitre-icarus/ICArUS-Challenge-Problem-Software-and-Data
|
src/main/java/org/mitre/icarus/cps/app/widgets/map/phase_1/objects/Annotation.java
|
<gh_stars>0
/*
* NOTICE
* This software was produced for the office of the Director of National Intelligence (ODNI)
* Intelligence Advanced Research Projects Activity (IARPA) ICArUS program,
* BAA number IARPA-BAA-10-04, under contract 2009-0917826-016, and is subject
* to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007).
*
* This software and data is provided strictly to support demonstrations of ICArUS challenge problems
* and to assist in the development of cognitive-neuroscience architectures. It is not intended to be used
* in operational systems or environments.
*
* Copyright (C) 2015 The MITRE Corporation. All Rights Reserved.
*
*/
package org.mitre.icarus.cps.app.widgets.map.phase_1.objects;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import org.mitre.icarus.cps.app.widgets.map.LineStyle;
import org.mitre.icarus.cps.app.widgets.map.phase_1.MapConstants_Phase1;
import org.mitre.icarus.cps.app.widgets.map.phase_1.RenderProperties;
import org.mitre.icarus.cps.app.widgets.map.phase_1.layers.ILayer_Phase1;
import org.mitre.icarus.cps.app.widgets.map.phase_1.objects.IAnnotationMapObject.AnnotationOrientation;
import org.mitre.icarus.cps.feature_vector.phase_1.GridLocation2D;
/**
* @author CBONACETO
*
*/
public class Annotation extends AbstractMapObject_Phase1 {
/** The parent map object that is being annotated */
protected final IAnnotatableMapObject parent;
/** The Map object that is the annotation */
protected final IAnnotationMapObject annotation;
/** The orientation of the annotation relative to its parent map object */
protected final AnnotationOrientation orientation;
/** Whether to show the annotation line */
protected boolean showAnnotationLine = true;
/** The annotation line color */
protected Color annotationLineColor = MapConstants_Phase1.ANNOTATION_LINE_COLOR;
/** The annotation line style */
protected LineStyle annotationLineStyle = MapConstants_Phase1.ANNOTATION_LINE_STYLE;
/** The number of pixels to offset the annotation from its parent */
protected int offset_pixels = MapConstants_Phase1.ANNOTATION_OFFSET_PIXELS;
/** whether or not the map object is selectable */
private boolean selectable = false;
/** The layer this annotation is contained in */
protected ILayer_Phase1<? super Annotation> layer;
protected Double parentXLocation;
protected Double parentYLocation;
public Annotation(IAnnotatableMapObject parent, final IAnnotationMapObject annotation,
final AnnotationOrientation orientation) {
this.parent = parent;
this.annotation = annotation;
this.orientation = orientation;
setId(annotation.getId());
}
@Override
public ILayer_Phase1<? super Annotation> getLayer() {
return layer;
}
@SuppressWarnings("unchecked")
public void setLayer(ILayer_Phase1<? extends IMapObject_Phase1> layer) {
super.setLayer(layer);
try {
this.layer = (ILayer_Phase1<? super Annotation>) layer;
} catch(Exception ex) {
throw new IllegalArgumentException("Error, the annotation must be contained in an annotation layer");
}
}
public IAnnotatableMapObject getParent() {
return parent;
}
public IAnnotationMapObject getAnnotation() {
return annotation;
}
public AnnotationOrientation getOrientation() {
return orientation;
}
public boolean isShowAnnotationLine() {
return showAnnotationLine;
}
public void setShowAnnotationLine(boolean showAnnotationLine) {
this.showAnnotationLine = showAnnotationLine;
}
public Color getAnnotationLineColor() {
return annotationLineColor;
}
public void setAnnotationLineColor(Color annotationLineColore) {
this.annotationLineColor = annotationLineColore;
}
public LineStyle getAnnotationLineStyle() {
return annotationLineStyle;
}
public void setAnnotationLineStyle(LineStyle annotationLineStyle) {
this.annotationLineStyle = annotationLineStyle;
}
/**
* @return the offest_gridUnits
*/
public int getOffset_pixels() {
return this.offset_pixels;
}
/**
* @param offest_gridUnits the offest_gridUnits to set
*/
public void setOffset_pixels(int offset_pixels) {
this.offset_pixels = offset_pixels;
}
@Override
public boolean contains(Point point) {
return contains(point.x, point.y);
}
@Override
public boolean contains(Point2D point) {
return contains(point.getX(), point.getY());
}
@Override
public boolean contains(double x, double y) {
if(annotation != null) {
return annotation.contains(x, y);
}
return false;
}
public static double getHeadingRadians(AnnotationOrientation orientation) {
double angle;
if(orientation == AnnotationOrientation.East) {
angle = 0.0;
}
else if(orientation == AnnotationOrientation.NorthEast) {
angle = Math.PI / 4.0;
}
else if(orientation == AnnotationOrientation.North) {
angle = Math.PI / 2.0;
}
else if(orientation == AnnotationOrientation.NorthWest) {
angle = 3.0 * Math.PI / 4.0;
}
else if(orientation == AnnotationOrientation.West) {
angle = Math.PI;
}
else if(orientation == AnnotationOrientation.SouthWest) {
angle = 5.0 * Math.PI / 4.0;
}
else if(orientation == AnnotationOrientation.South) {
angle = 3.0 * Math.PI / 2.0;
}
else {
angle = 7.0 * Math.PI / 4.0;
}
return angle;
}
@Override
public boolean isSelectable() {
return selectable;
}
@Override
public void setSelectable(boolean selectable) {
this.selectable = selectable;
}
@Override
public void setMouseOverState(boolean mouseOver, MouseEvent event) {
}
@Override
public void render(Graphics2D g2d, RenderProperties renderData, boolean renderPropertiesChanged) {
//Don't render the annotation if its parent isn't visible
if(!parent.isVisible() || (parent.getLayer() != null && !parent.getLayer().isVisible())) {
return;
}
Color origColor = g2d.getColor();
Stroke origStroke = g2d.getStroke();
Double parentXLocation = parent.getCenterLocation().getX();
Double parentYLocation = parent.getCenterLocation().getY();
if(renderPropertiesChanged || this.parentXLocation == null || this.parentYLocation == null ||
parentXLocation != this.parentXLocation || parentYLocation != this.parentYLocation) {
//Update the annotation center location
this.parentXLocation = parentXLocation;
this.parentYLocation = parentYLocation;
if(orientation == AnnotationOrientation.Center || orientation == AnnotationOrientation.Center_1) {
// case where the annotation orientation is that the center
annotation.setCenterLocation(new GridLocation2D(parentXLocation, parentYLocation));
} else {
// case where the annotation orientation is not at the center
double angle = getHeadingRadians(orientation);
double offset_gridUnits = renderData.translateToGridUnits(offset_pixels);
double annotationXLocation = parent.getCenterLocation().getX()
+ offset_gridUnits * Math.cos(angle);
double annotationYLocation = parent.getCenterLocation().getY()
+ offset_gridUnits * Math.sin(angle);
annotation.setCenterLocation(new GridLocation2D(annotationXLocation, annotationYLocation));
}
}
//Render the annotation
annotation.render(g2d, renderData, renderPropertiesChanged);
//Render the annotation line if the annotation is not at the center orientation
if(showAnnotationLine && orientation != AnnotationOrientation.Center && orientation != AnnotationOrientation.Center_1) {
Point2D startLocationPixels = renderData.translateToPixel(annotation.getAnnotationLineStartLocation(orientation));
Point2D endLocationPixels = renderData.translateToPixel(parent.getAnnotationLineEndLocation(orientation));
Line2D line = new Line2D.Double(startLocationPixels, endLocationPixels);
if(getAnnotationLineStyle() != null) {
g2d.setStroke(getAnnotationLineStyle().getLineStroke());
}
if(annotationLineColor == null) {
annotationLineColor = Color.black;
}
g2d.setColor(annotationLineColor);
g2d.draw(line);
}
g2d.setColor(origColor);
g2d.setStroke(origStroke);
}
}
|
Olde-Skuul/burgerlib
|
source/commandline/brcommandparameterstring.cpp
|
/***************************************
Class for a string command parameter
Copyright (c) 1995-2020 by <NAME> <<EMAIL>>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brcommandparameterstring.h"
/*! ************************************
\class Burger::CommandParameterString
\brief Class for a string command line parameter
Sets a string if one is present
\sa Burger::CommandParameter or Burger::CommandParameterWordPtr
***************************************/
/*! ************************************
\fn Burger::CommandParameterString::CommandParameterString(
const char *pHelp, const char *const *ppParameterName,
uintptr_t uParameterCount,const char*pDefault)
\brief Constructor for multiple valid commands
In cases there multiple commands can trigger this command, pass a pointer to
an array of "C" strings and the array size in entries to construct this
parameter parser
\note Do not set the count to 0, it will cause this class to treat the array
pointer as a direct pointer which may not be desired behavior
\param pHelp Pointer to "C" string for usage
\param ppParameterName Pointer to an array of "C" strings for valid inputs
\param uParameterCount Number of entries in the array (1-XX).
\param pDefault Pointer to "C" string for default value or nullptr for
empty string
***************************************/
/*! ************************************
\fn Burger::CommandParameterString::CommandParameterString(
const char *pHelp,const char *pParameterName,
const char *pDefault)
\brief Constructor for a single valid command
The default value is set to \ref FALSE.
\param pHelp Pointer to "C" string for usage.
\param pParameterName Pointer to a "C" string to match to trigger this
parameter.
\param pDefault Pointer to "C" string for default value or nullptr
for empty string
***************************************/
/*! ************************************
\brief Sets the value to a passed string
Parse a parameter if present and copy it as is into the string buffer
\param argc Number of parameters in argv
\param argv Array of "C" strings
\return Returns 2 or -1 if no string was present (Or empty)
***************************************/
int Burger::CommandParameterString::Action(int argc, const char** argv)
{
if (!argc) {
return -1;
}
m_Value.Set(argv[0]);
return 2;
}
/*! ************************************
\fn const char *Burger::CommandParameterString::GetValue(void) const
\brief Returns the string value
Returns the contained string. Will not be nullptr
\return Returns pointer to the string (Can be an empty string)
***************************************/
|
google-ar/chromium
|
third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/clients-matchall-worker.js
|
<filename>third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/clients-matchall-worker.js
self.onmessage = function(e) {
var port = e.data.port;
var options = e.data.options;
e.waitUntil(self.clients.matchAll(options).then(function(clients) {
var message = [];
clients.forEach(function(client) {
message.push([client.visibilityState,
client.focused,
client.url,
client.frameType]);
});
port.postMessage(message);
}));
};
|
boost-entropy-repos-org/metasfresh
|
backend/de.metas.elasticsearch.server/src/main/java/de/metas/elasticsearch/ESServer.java
|
<gh_stars>0
package de.metas.elasticsearch;
import de.metas.elasticsearch.config.ESModelIndexerConfigBuilder;
import de.metas.elasticsearch.indexer.impl.ESModelIndexersRegistry;
import de.metas.logging.LogManager;
import de.metas.util.Services;
import lombok.NonNull;
import org.compiere.SpringContextHolder;
import org.slf4j.Logger;
/*
* #%L
* de.metas.elasticsearch.server
* %%
* Copyright (C) 2016 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public class ESServer
{
private final static transient Logger logger = LogManager.getLogger(ESServer.class);
public void installConfig(@NonNull final ESModelIndexerConfigBuilder config)
{
final IESSystem esSystem = Services.get(IESSystem.class);
if(!esSystem.isEnabled())
{
logger.info("installConfig - IESSystem.isEnabled() returned false; -> do nothing");
return;
}
final ESModelIndexersRegistry esModelIndexersRegistry = SpringContextHolder.instance.getBean(ESModelIndexersRegistry.class);
esModelIndexersRegistry.addModelIndexer(config);
}
}
|
alex-dsouza777/Python-Basics
|
Chapter 7 - Loops in Python/Example.py
|
i = 0
while i < 5:
print("root")
i = i + 1
|
cseelye/sfauto
|
vmhost_vswitch_create.py
|
<reponame>cseelye/sfauto<filename>vmhost_vswitch_create.py<gh_stars>0
#!/usr/bin/env python
"""
This action will create a vswitch on a hypervisor
"""
from libsf.apputil import PythonApp
from libsf.argutil import SFArgumentParser, GetFirstLine, SFArgFormatter
from libsf.logutil import GetLogger, logargs
from libsf.virtutil import VMHost
from libsf.util import ValidateAndDefault, IPv4AddressType, OptionalValueType, StrType, PositiveNonZeroIntegerType, ItemList
from libsf import sfdefaults
from libsf import SolidFireError
@logargs
@ValidateAndDefault({
# "arg_name" : (arg_type, arg_default)
"vmhost_ip" : (IPv4AddressType, sfdefaults.vm_names),
"vswitch_name" : (StrType, None),
"vswitch_mtu" : (PositiveNonZeroIntegerType, 1500),
"vswitch_pnics" : (ItemList(StrType), None),
"vm_mgmt_server" : (OptionalValueType(IPv4AddressType), sfdefaults.vmware_mgmt_server),
"vm_mgmt_user" : (OptionalValueType(StrType), sfdefaults.vmware_mgmt_user),
"vm_mgmt_pass" : (OptionalValueType(StrType), sfdefaults.vmware_mgmt_pass),
})
def VmhostVswitchCreate(vmhost_ip,
vswitch_name,
vswitch_mtu,
vswitch_pnics,
vm_mgmt_server,
vm_mgmt_user,
vm_mgmt_pass):
"""
Create a vswitch
Args:
vmhost_ip: the hypervisor IP address
include_internal: create datastores on internal drives (like satadimm/dom)
include_slots: create datastores on external drives in chassis slots
vm_mgmt_server: the management server for the VMs (vSphere for VMware, hypervisor for KVM)
vm_mgmt_user: the management user for the VMs
vm_mgmt_pass: the management password for the VMs
"""
log = GetLogger()
log.info("Connecting to {}".format(vm_mgmt_server))
try:
host = VMHost.Attach(vmhost_ip, vm_mgmt_server, vm_mgmt_user, vm_mgmt_pass)
except SolidFireError as ex:
log.error("Could not connect to hypervisor: {}".format(str(ex)))
return False
log.info("Creating vswitch")
try:
host.CreateVswitch(vswitch_name, vswitch_pnics, vswitch_mtu)
except SolidFireError as ex:
log.error("Could not create vswitch: {}".format(str(ex)))
return False
log.passed("Successfully created vswitch {}".format(vswitch_name))
return True
if __name__ == '__main__':
parser = SFArgumentParser(description=GetFirstLine(__doc__), formatter_class=SFArgFormatter)
parser.add_argument("--vmhost-ip", type=IPv4AddressType, required=True, metavar="IP", help="the IP address of the hypervisor")
parser.add_argument("--vswitch-name", type=StrType, required=True, metavar="NAME", help="the name of the switch to create")
parser.add_argument("--vswitch-mtu", type=PositiveNonZeroIntegerType, default=1500, required=True, metavar="MTU", help="the MTU of the switch")
parser.add_argument("--vswitch-pnics", type=ItemList(StrType), metavar="NIC1,NIC2,...", help="the physical NICs to attach to the vswitch")
parser.add_vm_mgmt_args()
args = parser.parse_args_to_dict()
app = PythonApp(VmhostVswitchCreate, args)
app.Run(**args)
|
KenWoo/Algorithm
|
Algorithms/Medium/120. Triangle/answer.py
|
from typing import List
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if not triangle or not triangle[0]:
return triangle
N = len(triangle)
res = []
for n in triangle[N-1]:
res.append(n)
for i in range(N-2, -1, -1):
for j in range(i+1):
res[j] = triangle[i][j] + min(res[j], res[j+1])
return res[0]
if __name__ == "__main__":
s = Solution()
result = s.minimumTotal([
[2],
[3, 4],
[6, 5, 7],
[4, 1, 8, 3]
])
print(result)
|
ani03sha/Leetcoding
|
december-2020-leetcoding-challenge/src/main/java/org/redquark/leetcode/challenge/Problem31_LargestRectangleInHistogram.java
|
<reponame>ani03sha/Leetcoding
package org.redquark.leetcode.challenge;
import java.util.Arrays;
import java.util.Stack;
/**
* @author <NAME>
* <p>
* Given n non-negative integers representing the histogram's bar height where the width of each bar is 1,
* find the area of largest rectangle in the histogram.
*/
public class Problem31_LargestRectangleInHistogram {
/**
* @param heights - heights of the histogram
* @return area of largest rectangle
*/
public int largestRectangleArea(int[] heights) {
// Base condition
if (heights == null || heights.length == 0) {
return 0;
}
if (heights.length == 1) {
return heights[0];
}
// Stack to store values
Stack<Integer> stack = new Stack<>();
// Copy array
int[] copy = Arrays.copyOf(heights, heights.length + 1);
// This variable will score the max area
int maxArea = 0;
// Index to iterate array
int index = 0;
// Loop through the copy array
while (index < copy.length) {
if (stack.isEmpty() || copy[index] > copy[stack.peek()]) {
stack.push(index);
index++;
} else {
int i = stack.pop();
int localArea = copy[i] * (stack.isEmpty() ? index : index - stack.peek() - 1);
maxArea = Math.max(maxArea, localArea);
}
}
return maxArea;
}
}
|
johntellsall/shotglass
|
shotglass/shotglass/urls.py
|
<gh_stars>1-10
# shotglass.urls
from django.conf.urls import include, re_path
urlpatterns = [
re_path(r"^app/", include("app.urls")),
]
|
impedimentToProgress/UCI-BlueChip
|
snapgear_linux/user/e2fsprogs/misc/mke2fs.c
|
<filename>snapgear_linux/user/e2fsprogs/misc/mke2fs.c
/*
* mke2fs.c - Make a ext2fs filesystem.
*
* Copyright (C) 1994, 1995, 1996, 1997 <NAME>.
*
* %Begin-Header%
* This file may be redistributed under the terms of the GNU Public
* License.
* %End-Header%
*/
/* Usage: mke2fs [options] device
*
* The device may be a block device or a image of one, but this isn't
* enforced (but it's not much fun on a character device :-).
*/
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <time.h>
#ifdef linux
#include <sys/utsname.h>
#endif
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#else
extern char *optarg;
extern int optind;
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_MNTENT_H
#include <mntent.h>
#endif
#include <sys/ioctl.h>
#include <sys/types.h>
#include "ext2fs/ext2_fs.h"
#include "et/com_err.h"
#include "uuid/uuid.h"
#include "e2p/e2p.h"
#include "ext2fs/ext2fs.h"
#include "util.h"
#include "../version.h"
#include "nls-enable.h"
#define STRIDE_LENGTH 8
#ifndef __sparc__
#define ZAP_BOOTBLOCK
#endif
extern int isatty(int);
extern FILE *fpopen(const char *cmd, const char *mode);
const char * program_name = "mke2fs";
const char * device_name /* = NULL */;
/* Command line options */
int cflag;
int verbose;
int quiet;
int super_only;
int force;
int noaction;
int journal_size;
int journal_flags;
char *bad_blocks_filename;
__u32 fs_stride;
struct ext2_super_block param;
char *creator_os;
char *volume_label;
char *mount_dir;
char *journal_device;
int sync_kludge; /* Set using the MKE2FS_SYNC env. option */
static void usage(void)
{
fprintf(stderr, _("Usage: %s [-c|-t|-l filename] [-b block-size] "
"[-f fragment-size]\n\t[-i bytes-per-inode] [-j] [-J journal-options]"
" [-N number-of-inodes]\n\t[-m reserved-blocks-percentage] "
"[-o creator-os] [-g blocks-per-group]\n\t[-L volume-label] "
"[-M last-mounted-directory] [-O feature[,...]]\n\t"
"[-r fs-revision] [-R raid_opts] [-qvSV] device [blocks-count]\n"),
program_name);
exit(1);
}
static int int_log2(int arg)
{
int l = 0;
arg >>= 1;
while (arg) {
l++;
arg >>= 1;
}
return l;
}
static int int_log10(unsigned int arg)
{
int l;
for (l=0; arg ; l++)
arg = arg / 10;
return l;
}
/*
* This function sets the default parameters for a filesystem
*
* The type is specified by the user. The size is the maximum size
* (in megabytes) for which a set of parameters applies, with a size
* of zero meaning that it is the default parameter for the type.
* Note that order is important in the table below.
*/
static char default_str[] = "default";
struct mke2fs_defaults {
const char *type;
int size;
int blocksize;
int inode_ratio;
} settings[] = {
{ default_str, 0, 4096, 8192 },
{ default_str, 512, 1024, 4096 },
{ default_str, 3, 1024, 8192 },
{ "journal", 0, 4096, 8192 },
{ "news", 0, 4096, 4096 },
{ "largefile", 0, 4096, 1024 * 1024 },
{ "largefile4", 0, 4096, 4096 * 1024 },
{ 0, 0, 0, 0},
};
static void set_fs_defaults(char *fs_type, struct ext2_super_block *super,
int blocksize, int *inode_ratio)
{
int megs;
int ratio = 0;
struct mke2fs_defaults *p;
megs = (super->s_blocks_count * (EXT2_BLOCK_SIZE(super) / 1024) /
1024);
if (inode_ratio)
ratio = *inode_ratio;
if (!fs_type)
fs_type = default_str;
for (p = settings; p->type; p++) {
if ((strcmp(p->type, fs_type) != 0) &&
(strcmp(p->type, default_str) != 0))
continue;
if ((p->size != 0) &&
(megs > p->size))
continue;
if (ratio == 0)
*inode_ratio = p->inode_ratio;
if (blocksize == 0) {
super->s_log_frag_size = super->s_log_block_size =
int_log2(p->blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
}
}
if (blocksize == 0)
super->s_blocks_count /= EXT2_BLOCK_SIZE(super) / 1024;
}
/*
* Helper function for read_bb_file and test_disk
*/
static void invalid_block(ext2_filsys fs, blk_t blk)
{
printf(_("Bad block %u out of range; ignored.\n"), blk);
return;
}
/*
* Reads the bad blocks list from a file
*/
static void read_bb_file(ext2_filsys fs, badblocks_list *bb_list,
const char *bad_blocks_file)
{
FILE *f;
errcode_t retval;
f = fopen(bad_blocks_file, "r");
if (!f) {
com_err("read_bad_blocks_file", errno,
_("while trying to open %s"), bad_blocks_file);
exit(1);
}
retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
fclose (f);
if (retval) {
com_err("ext2fs_read_bb_FILE", retval,
_("while reading in list of bad blocks from file"));
exit(1);
}
}
/*
* Runs the badblocks program to test the disk
*/
static void test_disk(ext2_filsys fs, badblocks_list *bb_list)
{
FILE *f;
errcode_t retval;
char buf[1024];
sprintf(buf, "badblocks -b %d %s%s %d", fs->blocksize,
quiet ? "" : "-s ", fs->device_name,
fs->super->s_blocks_count);
if (verbose)
printf(_("Running command: %s\n"), buf);
f = popen(buf, "r");
if (!f) {
com_err("popen", errno,
_("while trying run '%s'"), buf);
exit(1);
}
retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
pclose(f);
if (retval) {
com_err("ext2fs_read_bb_FILE", retval,
_("while processing list of bad blocks from program"));
exit(1);
}
}
static void handle_bad_blocks(ext2_filsys fs, badblocks_list bb_list)
{
int i, j;
int must_be_good;
blk_t blk;
badblocks_iterate bb_iter;
errcode_t retval;
blk_t group_block;
int group;
int group_bad;
if (!bb_list)
return;
/*
* The primary superblock and group descriptors *must* be
* good; if not, abort.
*/
must_be_good = fs->super->s_first_data_block + 1 + fs->desc_blocks;
for (i = fs->super->s_first_data_block; i <= must_be_good; i++) {
if (ext2fs_badblocks_list_test(bb_list, i)) {
fprintf(stderr, _("Block %d in primary "
"superblock/group descriptor area bad.\n"), i);
fprintf(stderr, _("Blocks %d through %d must be good "
"in order to build a filesystem.\n"),
fs->super->s_first_data_block, must_be_good);
fprintf(stderr, _("Aborting....\n"));
exit(1);
}
}
/*
* See if any of the bad blocks are showing up in the backup
* superblocks and/or group descriptors. If so, issue a
* warning and adjust the block counts appropriately.
*/
group_block = fs->super->s_first_data_block +
fs->super->s_blocks_per_group;
for (i = 1; i < fs->group_desc_count; i++) {
group_bad = 0;
for (j=0; j < fs->desc_blocks+1; j++) {
if (ext2fs_badblocks_list_test(bb_list,
group_block + j)) {
if (!group_bad)
fprintf(stderr,
_("Warning: the backup superblock/group descriptors at block %d contain\n"
" bad blocks.\n\n"),
group_block);
group_bad++;
group = ext2fs_group_of_blk(fs, group_block+j);
fs->group_desc[group].bg_free_blocks_count++;
fs->super->s_free_blocks_count++;
}
}
group_block += fs->super->s_blocks_per_group;
}
/*
* Mark all the bad blocks as used...
*/
retval = ext2fs_badblocks_list_iterate_begin(bb_list, &bb_iter);
if (retval) {
com_err("ext2fs_badblocks_list_iterate_begin", retval,
_("while marking bad blocks as used"));
exit(1);
}
while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
ext2fs_mark_block_bitmap(fs->block_map, blk);
ext2fs_badblocks_list_iterate_end(bb_iter);
}
/*
* These functions implement a generalized progress meter.
*/
struct progress_struct {
char format[20];
char backup[80];
__u32 max;
};
static void progress_init(struct progress_struct *progress,
char *label,__u32 max)
{
int i;
memset(progress, 0, sizeof(struct progress_struct));
if (quiet)
return;
/*
* Figure out how many digits we need
*/
i = int_log10(max);
sprintf(progress->format, "%%%dd/%%%dld", i, i);
memset(progress->backup, '\b', sizeof(progress->backup)-1);
progress->backup[sizeof(progress->backup)-1] = 0;
if ((2*i)+1 < sizeof(progress->backup))
progress->backup[(2*i)+1] = 0;
progress->max = max;
fputs(label, stdout);
fflush(stdout);
}
static void progress_update(struct progress_struct *progress, __u32 val)
{
if (progress->format[0] == 0)
return;
printf(progress->format, val, progress->max);
fputs(progress->backup, stdout);
}
static void progress_close(struct progress_struct *progress)
{
if (progress->format[0] == 0)
return;
fputs(_("done \n"), stdout);
}
/*
* Helper function which zeros out _num_ blocks starting at _blk_. In
* case of an error, the details of the error is returned via _ret_blk_
* and _ret_count_ if they are non-NULL pointers. Returns 0 on
* success, and an error code on an error.
*
* As a special case, if the first argument is NULL, then it will
* attempt to free the static zeroizing buffer. (This is to keep
* programs that check for memory leaks happy.)
*/
static errcode_t zero_blocks(ext2_filsys fs, blk_t blk, int num,
struct progress_struct *progress,
blk_t *ret_blk, int *ret_count)
{
int j, count, next_update, next_update_incr;
static char *buf;
errcode_t retval;
/* If fs is null, clean up the static buffer and return */
if (!fs) {
if (buf) {
free(buf);
buf = 0;
}
return 0;
}
/* Allocate the zeroizing buffer if necessary */
if (!buf) {
buf = malloc(fs->blocksize * STRIDE_LENGTH);
if (!buf) {
com_err("malloc", ENOMEM,
_("while allocating zeroizing buffer"));
exit(1);
}
memset(buf, 0, fs->blocksize * STRIDE_LENGTH);
}
/* OK, do the write loop */
next_update = 0;
next_update_incr = num / 100;
if (next_update_incr < 1)
next_update_incr = 1;
for (j=0; j < num; j += STRIDE_LENGTH, blk += STRIDE_LENGTH) {
if (num-j > STRIDE_LENGTH)
count = STRIDE_LENGTH;
else
count = num - j;
retval = io_channel_write_blk(fs->io, blk, count, buf);
if (retval) {
if (ret_count)
*ret_count = count;
if (ret_blk)
*ret_blk = blk;
return retval;
}
if (progress && j > next_update) {
next_update += num / 100;
progress_update(progress, blk);
}
}
return 0;
}
static void write_inode_tables(ext2_filsys fs)
{
errcode_t retval;
blk_t blk;
int i, num;
struct progress_struct progress;
if (quiet)
memset(&progress, 0, sizeof(progress));
else
progress_init(&progress, _("Writing inode tables: "),
fs->group_desc_count);
for (i = 0; i < fs->group_desc_count; i++) {
progress_update(&progress, i);
blk = fs->group_desc[i].bg_inode_table;
num = fs->inode_blocks_per_group;
retval = zero_blocks(fs, blk, num, 0, &blk, &num);
if (retval) {
printf(_("\nCould not write %d blocks "
"in inode table starting at %d: %s\n"),
num, blk, error_message(retval));
exit(1);
}
if (sync_kludge) {
if (sync_kludge == 1)
sync();
else if ((i % sync_kludge) == 0)
sync();
}
}
zero_blocks(0, 0, 0, 0, 0, 0);
progress_close(&progress);
}
static void create_root_dir(ext2_filsys fs)
{
errcode_t retval;
struct ext2_inode inode;
retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, EXT2_ROOT_INO, 0);
if (retval) {
com_err("ext2fs_mkdir", retval, _("while creating root dir"));
exit(1);
}
if (geteuid()) {
retval = ext2fs_read_inode(fs, EXT2_ROOT_INO, &inode);
if (retval) {
com_err("ext2fs_read_inode", retval,
_("while reading root inode"));
exit(1);
}
inode.i_uid = getuid();
if (inode.i_uid)
inode.i_gid = getgid();
retval = ext2fs_write_inode(fs, EXT2_ROOT_INO, &inode);
if (retval) {
com_err("ext2fs_write_inode", retval,
_("while setting root inode ownership"));
exit(1);
}
}
}
static void create_lost_and_found(ext2_filsys fs)
{
errcode_t retval;
ext2_ino_t ino;
const char *name = "lost+found";
int i;
int lpf_size = 0;
retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, 0, name);
if (retval) {
com_err("ext2fs_mkdir", retval,
_("while creating /lost+found"));
exit(1);
}
retval = ext2fs_lookup(fs, EXT2_ROOT_INO, name, strlen(name), 0, &ino);
if (retval) {
com_err("ext2_lookup", retval,
_("while looking up /lost+found"));
exit(1);
}
for (i=1; i < EXT2_NDIR_BLOCKS; i++) {
if ((lpf_size += fs->blocksize) >= 16*1024)
break;
retval = ext2fs_expand_dir(fs, ino);
if (retval) {
com_err("ext2fs_expand_dir", retval,
_("while expanding /lost+found"));
exit(1);
}
}
}
static void create_bad_block_inode(ext2_filsys fs, badblocks_list bb_list)
{
errcode_t retval;
ext2fs_mark_inode_bitmap(fs->inode_map, EXT2_BAD_INO);
fs->group_desc[0].bg_free_inodes_count--;
fs->super->s_free_inodes_count--;
retval = ext2fs_update_bb_inode(fs, bb_list);
if (retval) {
com_err("ext2fs_update_bb_inode", retval,
_("while setting bad block inode"));
exit(1);
}
}
static void reserve_inodes(ext2_filsys fs)
{
ext2_ino_t i;
int group;
for (i = EXT2_ROOT_INO + 1; i < EXT2_FIRST_INODE(fs->super); i++) {
ext2fs_mark_inode_bitmap(fs->inode_map, i);
group = ext2fs_group_of_ino(fs, i);
fs->group_desc[group].bg_free_inodes_count--;
fs->super->s_free_inodes_count--;
}
ext2fs_mark_ib_dirty(fs);
}
static void zap_sector(ext2_filsys fs, int sect, int nsect)
{
char *buf;
int retval;
buf = malloc(512*nsect);
memset(buf, 0, 512*nsect);
io_channel_set_blksize(fs->io, 512);
retval = io_channel_write_blk(fs->io, sect, -512*nsect, buf);
io_channel_set_blksize(fs->io, fs->blocksize);
free(buf);
if (retval)
printf(_("Warning: could not erase sector %d: %s\n"), sect,
error_message(retval));
}
static void create_journal_dev(ext2_filsys fs)
{
struct progress_struct progress;
errcode_t retval;
char *buf;
blk_t blk;
int count;
retval = ext2fs_create_journal_superblock(fs,
fs->super->s_blocks_count, 0, &buf);
if (retval) {
com_err("create_journal_dev", retval,
_("while initializing journal superblock"));
exit(1);
}
if (quiet)
memset(&progress, 0, sizeof(progress));
else
progress_init(&progress, _("Zeroing journal device: "),
fs->super->s_blocks_count);
retval = zero_blocks(fs, 0, fs->super->s_blocks_count,
&progress, &blk, &count);
if (retval) {
com_err("create_journal_dev", retval,
_("while zeroing journal device (block %u, count %d)"),
blk, count);
exit(1);
}
zero_blocks(0, 0, 0, 0, 0, 0);
retval = io_channel_write_blk(fs->io,
fs->super->s_first_data_block+1,
1, buf);
if (retval) {
com_err("create_journal_dev", retval,
_("while writing journal superblock"));
exit(1);
}
progress_close(&progress);
}
static void show_stats(ext2_filsys fs)
{
struct ext2_super_block *s = fs->super;
char buf[80];
blk_t group_block;
int i, need, col_left;
if (param.s_blocks_count != s->s_blocks_count)
printf(_("warning: %d blocks unused.\n\n"),
param.s_blocks_count - s->s_blocks_count);
memset(buf, 0, sizeof(buf));
strncpy(buf, s->s_volume_name, sizeof(s->s_volume_name));
printf(_("Filesystem label=%s\n"), buf);
printf(_("OS type: "));
switch (fs->super->s_creator_os) {
case EXT2_OS_LINUX: printf ("Linux"); break;
case EXT2_OS_HURD: printf ("GNU/Hurd"); break;
case EXT2_OS_MASIX: printf ("Masix"); break;
default: printf (_("(unknown os)"));
}
printf("\n");
printf(_("Block size=%u (log=%u)\n"), fs->blocksize,
s->s_log_block_size);
printf(_("Fragment size=%u (log=%u)\n"), fs->fragsize,
s->s_log_frag_size);
printf(_("%u inodes, %u blocks\n"), s->s_inodes_count,
s->s_blocks_count);
#ifdef EMBED
printf(_("%u blocks (%d%%) reserved for the super user\n"),
s->s_r_blocks_count,
100 * s->s_r_blocks_count / s->s_blocks_count);
#else
printf(_("%u blocks (%2.2f%%) reserved for the super user\n"),
s->s_r_blocks_count,
100.0 * s->s_r_blocks_count / s->s_blocks_count);
#endif
printf(_("First data block=%u\n"), s->s_first_data_block);
if (fs->group_desc_count > 1)
printf(_("%u block groups\n"), fs->group_desc_count);
else
printf(_("%u block group\n"), fs->group_desc_count);
printf(_("%u blocks per group, %u fragments per group\n"),
s->s_blocks_per_group, s->s_frags_per_group);
printf(_("%u inodes per group\n"), s->s_inodes_per_group);
if (fs->group_desc_count == 1) {
printf("\n");
return;
}
printf(_("Superblock backups stored on blocks: "));
group_block = s->s_first_data_block;
col_left = 0;
for (i = 1; i < fs->group_desc_count; i++) {
group_block += s->s_blocks_per_group;
if (!ext2fs_bg_has_super(fs, i))
continue;
if (i != 1)
printf(", ");
need = int_log10(group_block) + 2;
if (need > col_left) {
printf("\n\t");
col_left = 72;
}
col_left -= need;
printf("%u", group_block);
}
printf("\n\n");
}
/*
* Set the S_CREATOR_OS field. Return true if OS is known,
* otherwise, 0.
*/
static int set_os(struct ext2_super_block *sb, char *os)
{
if (isdigit (*os))
sb->s_creator_os = atoi (os);
else if (strcasecmp(os, "linux") == 0)
sb->s_creator_os = EXT2_OS_LINUX;
else if (strcasecmp(os, "GNU") == 0 || strcasecmp(os, "hurd") == 0)
sb->s_creator_os = EXT2_OS_HURD;
else if (strcasecmp(os, "masix") == 0)
sb->s_creator_os = EXT2_OS_MASIX;
else
return 0;
return 1;
}
#define PATH_SET "PATH=/sbin"
static void parse_raid_opts(const char *opts)
{
char *buf, *token, *next, *p, *arg;
int len;
int raid_usage = 0;
len = strlen(opts);
buf = malloc(len+1);
if (!buf) {
fprintf(stderr, _("Couldn't allocate memory to parse "
"raid options!\n"));
exit(1);
}
strcpy(buf, opts);
for (token = buf; token && *token; token = next) {
p = strchr(token, ',');
next = 0;
if (p) {
*p = 0;
next = p+1;
}
arg = strchr(token, '=');
if (arg) {
*arg = 0;
arg++;
}
if (strcmp(token, "stride") == 0) {
if (!arg) {
raid_usage++;
continue;
}
fs_stride = strtoul(arg, &p, 0);
if (*p || (fs_stride == 0)) {
fprintf(stderr,
_("Invalid stride parameter.\n"));
raid_usage++;
continue;
}
} else
raid_usage++;
}
if (raid_usage) {
fprintf(stderr, _("\nBad raid options specified.\n\n"
"Raid options are separated by commas, "
"and may take an argument which\n"
"\tis set off by an equals ('=') sign.\n\n"
"Valid raid options are:\n"
"\tstride=<stride length in blocks>\n\n"));
exit(1);
}
}
static __u32 ok_features[3] = {
EXT3_FEATURE_COMPAT_HAS_JOURNAL, /* Compat */
EXT2_FEATURE_INCOMPAT_FILETYPE| /* Incompat */
EXT3_FEATURE_INCOMPAT_JOURNAL_DEV,
EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER /* R/O compat */
};
static void PRS(int argc, char *argv[])
{
int c;
int size;
char * tmp;
blk_t group_blk_max = 8192;
int blocksize = 0;
int inode_ratio = 0;
int reserved_ratio = 5;
ext2_ino_t num_inodes = 0;
errcode_t retval;
char * oldpath = getenv("PATH");
char * raid_opts = 0;
char * fs_type = 0;
int default_features = 1;
blk_t dev_size;
#ifdef linux
struct utsname ut;
#endif
/* Update our PATH to include /sbin */
if (oldpath) {
char *newpath;
newpath = malloc(sizeof (PATH_SET) + 1 + strlen (oldpath));
strcpy (newpath, PATH_SET);
strcat (newpath, ":");
strcat (newpath, oldpath);
putenv (newpath);
} else
putenv (PATH_SET);
tmp = getenv("MKE2FS_SYNC");
if (tmp)
sync_kludge = atoi(tmp);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
initialize_ext2_error_table();
memset(¶m, 0, sizeof(struct ext2_super_block));
param.s_rev_level = 1; /* Create revision 1 filesystems now */
param.s_feature_incompat |= EXT2_FEATURE_INCOMPAT_FILETYPE;
param.s_feature_ro_compat |= EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
#ifdef linux
if (uname(&ut)) {
perror("uname");
exit(1);
}
if ((ut.release[0] == '1') ||
(ut.release[0] == '2' && ut.release[1] == '.' &&
ut.release[2] < '2' && ut.release[3] == '.')) {
param.s_rev_level = 0;
param.s_feature_incompat = 0;
param.s_feature_compat = 0;
param.s_feature_ro_compat = 0;
}
#endif
fprintf (stderr, "mke2fs %s (%s)\n",
E2FSPROGS_VERSION, E2FSPROGS_DATE);
if (argc && *argv)
program_name = *argv;
while ((c = getopt (argc, argv,
"b:cf:g:i:jl:m:no:qr:R:s:tvI:J:ST:FL:M:N:O:V")) != EOF)
switch (c) {
case 'b':
blocksize = strtoul(optarg, &tmp, 0);
if (blocksize < 1024 || blocksize > 4096 || *tmp) {
com_err(program_name, 0,
_("bad block size - %s"), optarg);
exit(1);
}
param.s_log_block_size =
int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
group_blk_max = blocksize * 8;
break;
case 'c': /* Check for bad blocks */
case 't': /* deprecated */
cflag = 1;
break;
case 'f':
size = strtoul(optarg, &tmp, 0);
if (size < 1024 || size > 4096 || *tmp) {
com_err(program_name, 0,
_("bad fragment size - %s"),
optarg);
exit(1);
}
param.s_log_frag_size =
int_log2(size >> EXT2_MIN_BLOCK_LOG_SIZE);
printf(_("Warning: fragments not supported. "
"Ignoring -f option\n"));
break;
case 'g':
param.s_blocks_per_group = strtoul(optarg, &tmp, 0);
if (*tmp) {
com_err(program_name, 0,
_("Illegal number for blocks per group"));
exit(1);
}
if ((param.s_blocks_per_group % 8) != 0) {
com_err(program_name, 0,
_("blocks per group must be multiple of 8"));
exit(1);
}
break;
case 'i':
inode_ratio = strtoul(optarg, &tmp, 0);
if (inode_ratio < 1024 || inode_ratio > 4096 * 1024 ||
*tmp) {
com_err(program_name, 0,
_("bad inode ratio - %s"), optarg);
exit(1);
}
break;
case 'J':
parse_journal_opts(optarg);
break;
case 'j':
param.s_feature_compat |=
EXT3_FEATURE_COMPAT_HAS_JOURNAL;
if (!journal_size)
journal_size = -1;
break;
case 'l':
bad_blocks_filename = malloc(strlen(optarg)+1);
if (!bad_blocks_filename) {
com_err(program_name, ENOMEM,
_("in malloc for bad_blocks_filename"));
exit(1);
}
strcpy(bad_blocks_filename, optarg);
break;
case 'm':
reserved_ratio = strtoul(optarg, &tmp, 0);
if (reserved_ratio > 50 || *tmp) {
com_err(program_name, 0,
_("bad reserved blocks percent - %s"),
optarg);
exit(1);
}
break;
case 'n':
noaction++;
break;
case 'o':
creator_os = optarg;
break;
case 'r':
param.s_rev_level = atoi(optarg);
if (param.s_rev_level == EXT2_GOOD_OLD_REV) {
param.s_feature_incompat = 0;
param.s_feature_compat = 0;
param.s_feature_ro_compat = 0;
}
break;
case 's': /* deprecated */
if (atoi(optarg))
param.s_feature_ro_compat |=
EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
else
param.s_feature_ro_compat &=
~EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
break;
#ifdef EXT2_DYNAMIC_REV
case 'I':
param.s_inode_size = atoi(optarg);
break;
#endif
case 'N':
num_inodes = atoi(optarg);
break;
case 'v':
verbose = 1;
break;
case 'q':
quiet = 1;
break;
case 'F':
force = 1;
break;
case 'L':
volume_label = optarg;
break;
case 'M':
mount_dir = optarg;
break;
case 'O':
if (!strcmp(optarg, "none") || default_features) {
param.s_feature_compat = 0;
param.s_feature_incompat = 0;
param.s_feature_ro_compat = 0;
default_features = 0;
}
if (!strcmp(optarg, "none"))
break;
if (e2p_edit_feature(optarg,
¶m.s_feature_compat,
ok_features)) {
fprintf(stderr,
_("Invalid filesystem option set: %s\n"), optarg);
exit(1);
}
break;
case 'R':
raid_opts = optarg;
break;
case 'S':
super_only = 1;
break;
case 'T':
fs_type = optarg;
break;
case 'V':
/* Print version number and exit */
fprintf(stderr, _("\tUsing %s\n"),
error_message(EXT2_ET_BASE));
exit(0);
default:
usage();
}
if (optind == argc)
usage();
device_name = argv[optind];
optind++;
if (optind < argc) {
unsigned long tmp2 = strtoul(argv[optind++], &tmp, 0);
if ((*tmp) || (tmp2 > 0xfffffffful)) {
com_err(program_name, 0, _("bad blocks count - %s"),
argv[optind - 1]);
exit(1);
}
param.s_blocks_count = tmp2;
}
if (optind < argc)
usage();
if (raid_opts)
parse_raid_opts(raid_opts);
/*
* If there's no blocksize specified and there is a journal
* device, use it to figure out the blocksize
*/
if (blocksize == 0 && journal_device) {
ext2_filsys jfs;
retval = ext2fs_open(journal_device,
EXT2_FLAG_JOURNAL_DEV_OK, 0,
0, unix_io_manager, &jfs);
if (retval) {
com_err(program_name, retval,
_("while trying to open journal device %s\n"),
journal_device);
exit(1);
}
blocksize = jfs->blocksize;
param.s_log_block_size =
int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
ext2fs_close(jfs);
}
if (param.s_feature_incompat & EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
if (!fs_type)
fs_type = "journal";
reserved_ratio = 0;
param.s_feature_incompat = EXT3_FEATURE_INCOMPAT_JOURNAL_DEV;
param.s_feature_compat = 0;
param.s_feature_ro_compat = 0;
}
if (param.s_rev_level == EXT2_GOOD_OLD_REV &&
(param.s_feature_compat || param.s_feature_ro_compat ||
param.s_feature_incompat))
param.s_rev_level = 1; /* Create a revision 1 filesystem */
if (!force)
check_plausibility(device_name);
check_mount(device_name, force, _("filesystem"));
param.s_log_frag_size = param.s_log_block_size;
if (noaction && param.s_blocks_count) {
dev_size = param.s_blocks_count;
retval = 0;
} else
retval = ext2fs_get_device_size(device_name,
EXT2_BLOCK_SIZE(¶m),
&dev_size);
if (retval && (retval != EXT2_ET_UNIMPLEMENTED)) {
com_err(program_name, retval,
_("while trying to determine filesystem size"));
exit(1);
}
if (!param.s_blocks_count) {
if (retval == EXT2_ET_UNIMPLEMENTED) {
com_err(program_name, 0,
_("Couldn't determine device size; you "
"must specify\nthe size of the "
"filesystem\n"));
exit(1);
} else {
if (dev_size == 0) {
com_err(program_name, 0,
_("Device size reported to be zero. "
"Invalid partition specified, or\n\t"
"partition table wasn't reread "
"after running fdisk, due to\n\t"
"a modified partition being busy "
"and in use. You may need to reboot\n\t"
"to re-read your partition table.\n"
));
exit(1);
}
param.s_blocks_count = dev_size;
}
} else if (!force && (param.s_blocks_count > dev_size)) {
com_err(program_name, 0,
_("Filesystem larger than apparent filesystem size."));
proceed_question();
}
/*
* If the user asked for HAS_JOURNAL, then make sure a journal
* gets created.
*/
if ((param.s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL) &&
!journal_size)
journal_size = -1;
set_fs_defaults(fs_type, ¶m, blocksize, &inode_ratio);
if (param.s_blocks_per_group) {
if (param.s_blocks_per_group < 256 ||
param.s_blocks_per_group > group_blk_max || *tmp) {
com_err(program_name, 0,
_("blocks per group count out of range"));
exit(1);
}
}
/*
* Calculate number of inodes based on the inode ratio
*/
param.s_inodes_count = num_inodes ? num_inodes :
((__u64) param.s_blocks_count * EXT2_BLOCK_SIZE(¶m))
/ inode_ratio;
/*
* Calculate number of blocks to reserve
*/
param.s_r_blocks_count = (param.s_blocks_count * reserved_ratio) / 100;
}
int main (int argc, char *argv[])
{
errcode_t retval = 0;
ext2_filsys fs;
badblocks_list bb_list = 0;
int journal_blocks;
int i, val;
#ifdef ENABLE_NLS
setlocale(LC_MESSAGES, "");
bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
textdomain(NLS_CAT_NAME);
#endif
PRS(argc, argv);
/*
* Initialize the superblock....
*/
retval = ext2fs_initialize(device_name, 0, ¶m,
unix_io_manager, &fs);
if (retval) {
com_err(device_name, retval, _("while setting up superblock"));
exit(1);
}
/*
* Wipe out the old on-disk superblock
*/
if (!noaction)
zap_sector(fs, 2, 6);
/*
* Generate a UUID for it...
*/
uuid_generate(fs->super->s_uuid);
/*
* Add "jitter" to the superblock's check interval so that we
* don't check all the filesystems at the same time. We use a
* kludgy hack of using the UUID to derive a random jitter value.
*/
for (i = 0, val = 0 ; i < sizeof(fs->super->s_uuid); i++)
val += fs->super->s_uuid[i];
fs->super->s_max_mnt_count += val % EXT2_DFL_MAX_MNT_COUNT;
/*
* Override the creator OS, if applicable
*/
if (creator_os && !set_os(fs->super, creator_os)) {
com_err (program_name, 0, _("unknown os - %s"), creator_os);
exit(1);
}
/*
* For the Hurd, we will turn off filetype since it doesn't
* support it.
*/
if (fs->super->s_creator_os == EXT2_OS_HURD)
fs->super->s_feature_incompat &=
~EXT2_FEATURE_INCOMPAT_FILETYPE;
/*
* Set the volume label...
*/
if (volume_label) {
memset(fs->super->s_volume_name, 0,
sizeof(fs->super->s_volume_name));
strncpy(fs->super->s_volume_name, volume_label,
sizeof(fs->super->s_volume_name));
}
/*
* Set the last mount directory
*/
if (mount_dir) {
memset(fs->super->s_last_mounted, 0,
sizeof(fs->super->s_last_mounted));
strncpy(fs->super->s_last_mounted, mount_dir,
sizeof(fs->super->s_last_mounted));
}
if (!quiet || noaction)
show_stats(fs);
if (noaction)
exit(0);
if (fs->super->s_feature_incompat &
EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
create_journal_dev(fs);
ext2fs_close(fs);
exit(0);
}
if (bad_blocks_filename)
read_bb_file(fs, &bb_list, bad_blocks_filename);
if (cflag)
test_disk(fs, &bb_list);
handle_bad_blocks(fs, bb_list);
fs->stride = fs_stride;
retval = ext2fs_allocate_tables(fs);
if (retval) {
com_err(program_name, retval,
_("while trying to allocate filesystem tables"));
exit(1);
}
if (super_only) {
fs->super->s_state |= EXT2_ERROR_FS;
fs->flags &= ~(EXT2_FLAG_IB_DIRTY|EXT2_FLAG_BB_DIRTY);
} else {
/* rsv must be a power of two (64kB is MD RAID sb alignment) */
int rsv = 65536 / fs->blocksize;
unsigned long blocks = fs->super->s_blocks_count;
unsigned long start;
blk_t ret_blk;
#ifdef ZAP_BOOTBLOCK
zap_sector(fs, 0, 2);
#endif
/*
* Wipe out any old MD RAID (or other) metadata at the end
* of the device. This will also verify that the device is
* as large as we think. Be careful with very small devices.
*/
start = (blocks & ~(rsv - 1));
if (start > rsv)
start -= rsv;
if (start > 0)
retval = zero_blocks(fs, start, blocks - start,
NULL, &ret_blk, NULL);
if (retval) {
com_err(program_name, retval,
_("zeroing block %u at end of filesystem"),
ret_blk);
exit(1);
}
write_inode_tables(fs);
create_root_dir(fs);
create_lost_and_found(fs);
reserve_inodes(fs);
create_bad_block_inode(fs, bb_list);
}
if (journal_device) {
ext2_filsys jfs;
if (!force)
check_plausibility(journal_device);
check_mount(journal_device, force, _("journal"));
retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
EXT2_FLAG_JOURNAL_DEV_OK, 0,
fs->blocksize, unix_io_manager, &jfs);
if (retval) {
com_err(program_name, retval,
_("while trying to open journal device %s\n"),
journal_device);
exit(1);
}
if (!quiet) {
printf(_("Adding journal to device %s: "),
journal_device);
fflush(stdout);
}
retval = ext2fs_add_journal_device(fs, jfs);
if(retval) {
com_err (program_name, retval,
_("\n\twhile trying to add journal to device %s"),
journal_device);
exit(1);
}
if (!quiet)
printf(_("done\n"));
ext2fs_close(jfs);
free(journal_device);
} else if (journal_size) {
journal_blocks = figure_journal_size(journal_size, fs);
if (!journal_blocks) {
fs->super->s_feature_compat &=
~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
goto no_journal;
}
if (!quiet) {
printf(_("Creating journal (%d blocks): "),
journal_blocks);
fflush(stdout);
}
retval = ext2fs_add_journal_inode(fs, journal_blocks,
journal_flags);
if (retval) {
com_err (program_name, retval,
_("\n\twhile trying to create journal"));
exit(1);
}
if (!quiet)
printf(_("done\n"));
}
no_journal:
if (!quiet)
printf(_("Writing superblocks and "
"filesystem accounting information: "));
retval = ext2fs_flush(fs);
if (retval) {
printf(_("\nWarning, had trouble writing out superblocks."));
}
if (!quiet) {
printf(_("done\n\n"));
print_check_message(fs);
}
ext2fs_close(fs);
return 0;
}
|
balupton/exo
|
cmd/spin/main.go
|
<reponame>balupton/exo
// Test program that pegs a core and ignores interrupts.
package main
import (
"os"
"os/signal"
)
func main() {
signal.Ignore(os.Interrupt, os.Kill)
for {
}
}
|
slajerek/RetroDebugger
|
src/Emulators/vice/root/c64basic.h
|
<reponame>slajerek/RetroDebugger
/* Autogenerated file, DO NOT EDIT !!! */
BYTE c64memrom_basic64_rom[C64_BASIC_ROM_SIZE] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
|
keera-studios/hsQt
|
Qtc/include/gui/qtc_hs_QStyleOptionFrame.h
|
/////////////////////////////////////////////////////////////////////////////
//
// File : qtc_hs_QStyleOptionFrame.h
// Copyright : (c) <NAME> 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:02:41
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
void* qtc_QStyleOptionFrame();
void* qtc_QStyleOptionFrame1(void*);
int qtc_QStyleOptionFrame_lineWidth(void*);
int qtc_QStyleOptionFrame_midLineWidth(void*);
void qtc_QStyleOptionFrame_setLineWidth(void*,int);
void qtc_QStyleOptionFrame_setMidLineWidth(void*,int);
void qtc_QStyleOptionFrame_finalizer(void*);
void* qtc_QStyleOptionFrame_getFinalizer();
void qtc_QStyleOptionFrame_delete(void*);
|
mbarbon/aqua
|
src/main/java/aqua/recommend/ScoredRated.java
|
<gh_stars>1-10
package aqua.recommend;
import java.util.Comparator;
public class ScoredRated implements ScoredAnime {
public static final Comparator<ScoredRated> SORT_SCORE = new Comparator<ScoredRated>() {
@Override
public int compare(ScoredRated a, ScoredRated b) {
return Float.compare(a.score, b.score);
}
};
public CFRated rated;
public float score;
public clojure.lang.Keyword tags;
public ScoredRated(CFRated rated, float score) {
this.rated = rated;
this.score = score;
}
@Override
public int animedbId() {
return rated.animedbId;
}
@Override
public clojure.lang.Keyword tags() {
return tags;
}
@Override
public void setTags(clojure.lang.Keyword tags) {
this.tags = tags;
}
@Override
public int hashCode() {
return rated.animedbId;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ScoredRated))
return false;
return equals((ScoredRated) o);
}
public boolean equals(ScoredRated other) {
return rated.animedbId == other.rated.animedbId;
}
}
|
cbarnson/UVa
|
archives/codelibraries/CompetitiveProgramming-master/code/strings/eertree.test.cpp
|
<reponame>cbarnson/UVa
/* Field testing: Timus 2040, Timus 1960 */
void test() {
}
// vim: cc=60 ts=2 sts=2 sw=2:
|
sailxjx/DI-engine
|
dizoo/classic_control/bitflip/envs/bitflip_env.py
|
<reponame>sailxjx/DI-engine
import copy
import random
import numpy as np
from typing import Any, Dict, Optional, Union, List
from ding.envs import BaseEnv, BaseEnvInfo, BaseEnvTimestep
from ding.envs.common.env_element import EnvElement, EnvElementInfo
from ding.utils import ENV_REGISTRY
@ENV_REGISTRY.register('bitflip')
class BitFlipEnv(BaseEnv):
def __init__(self, cfg: dict) -> None:
self._cfg = cfg
self._n_bits = cfg.n_bits
self._state = np.zeros(self._n_bits)
self._goal = np.zeros(self._n_bits)
self._curr_step = 0
self._maxsize = self._n_bits
self._final_eval_reward = 0
def reset(self) -> np.ndarray:
self._curr_step = 0
self._final_eval_reward = 0
if hasattr(self, '_seed') and hasattr(self, '_dynamic_seed') and self._dynamic_seed:
random_seed = 100 * random.randint(1, 1000)
np.random.seed(self._seed + random_seed)
elif hasattr(self, '_seed'):
np.random.seed(self._seed)
self._state = np.random.randint(0, 2, size=(self._n_bits, )).astype(np.float32)
self._goal = np.random.randint(0, 2, size=(self._n_bits, )).astype(np.float32)
while (self._state == self._goal).all():
self._goal = np.random.randint(0, 2, size=(self._n_bits, )).astype(np.float32)
obs = np.concatenate([self._state, self._goal], axis=0)
return obs
def close(self) -> None:
pass
def check_success(self, state: np.ndarray, goal: np.ndarray) -> bool:
return (self._state == self._goal).all()
def seed(self, seed: int, dynamic_seed: bool = True) -> None:
self._seed = seed
self._dynamic_seed = dynamic_seed
random.seed(self._seed)
def step(self, action: np.ndarray) -> BaseEnvTimestep:
self._state[action] = 1 - self._state[action]
if self.check_success(self._state, self._goal):
rew = np.array([1]).astype(np.float32)
done = True
else:
rew = np.array([0]).astype(np.float32)
done = False
self._final_eval_reward += float(rew)
if self._curr_step >= self._maxsize - 1:
done = True
info = {}
if done:
info['final_eval_reward'] = self._final_eval_reward
self._curr_step += 1
obs = np.concatenate([self._state, self._goal], axis=0)
return BaseEnvTimestep(obs, rew, done, info)
def info(self) -> BaseEnvInfo:
T = EnvElementInfo
return BaseEnvInfo(
agent_num=1,
obs_space=T(
(2 * self._n_bits, ),
{
'min': [0 for _ in range(self._n_bits)],
'max': [1 for _ in range(self._n_bits)],
'dtype': float,
},
),
# [min, max)
act_space=T(
(self._n_bits, ),
{
'min': 0,
'max': self._n_bits,
'dtype': int,
},
),
rew_space=T(
(1, ),
{
'min': 0.0,
'max': 1.0
},
),
use_wrappers=None,
)
def __repr__(self) -> str:
return "DI-engine BitFlip Env({})".format('bitflip')
|
Wangqge/PowerLog_ae
|
src/java/socialite/functions/Dmin.java
|
<filename>src/java/socialite/functions/Dmin.java<gh_stars>0
package socialite.functions;
public class Dmin extends AbstractAggregation {
static Dmin inst = new Dmin();
public static Dmin get() { return inst; }
public int apply(int a, int b) { throw new AssertionError("can't call this method directly"); }
public long apply(long a, long b) { throw new AssertionError("can't call this method directly"); }
public float apply(float a, float b) { throw new AssertionError("can't call this method directly"); }
public double apply(double a, double b) { throw new AssertionError("can't call this method directly"); }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.