repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
chenzhenyong1/Kaka
|
KaKa/KaKa/ViewController/Albums/AlbumsMapPaopaoImageVIew.h
|
//
// AlbumsMapPaopaoImageVIew.h
// KaKa
//
// Created by 深圳市 秀软科技有限公司 on 16/9/2.
// Copyright © 2016年 深圳市秀软科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AlbumsMapPaopaoImageVIew : UIView
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *imageCountLabel;
@end
|
bgerxx/woodpecker
|
integrationtest/vm/virtualrouter/novlan/test_reinit_vm_snapshot.py
|
'''
New Integration Test for reinit VM with snapshot.
@author: MengLai
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()
def test():
vm = test_stub.create_user_vlan_vm()
test_obj_dict.add_vm(vm)
vm.check()
vm_inv = vm.get_vm()
vm_ip = vm_inv.vmNics[0].ip
test_util.test_dsc('create test-file-1, test-file-2, test-file-3 and create snapshot1')
num = 1
while num <= 3:
cmd = 'touch /root/test-file-%s' % num
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('Fail to create test-file-%s in VM' % num)
num = num + 1
root_volume_uuid = test_lib.lib_get_root_volume_uuid(vm.get_vm())
snapshots = test_obj_dict.get_volume_snapshot(root_volume_uuid)
snapshots.set_utility_vm(vm)
vm.check()
snapshots.create_snapshot('create_root_snapshot1')
test_util.test_dsc('delete test-file-1, create test-file-4, test-file-5 and create snapshot2')
cmd = 'rm /root/test-file-1 || echo y'
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('Fail to delete test-file-1 in VM')
num = 4
while num <= 5:
cmd = 'touch /root/test-file-%s' % num
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('Fail to create test-file-%s in VM' % num)
num = num + 1
root_volume_uuid = test_lib.lib_get_root_volume_uuid(vm.get_vm())
snapshots2 = test_obj_dict.get_volume_snapshot(root_volume_uuid)
snapshots2.set_utility_vm(vm)
vm.check()
snapshots2.create_snapshot('create_root_snapshot2')
test_util.test_dsc('delete test-file-2, test-file-4, create test-file-6 and create snapshot3')
num_arr = [2, 4]
for i in num_arr:
cmd = 'rm /root/test-file-%s || echo y' % i
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('Fail to delete test-file-%s in VM' % i)
cmd = 'touch /root/test-file-6'
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('Fail to create test-file-6 in VM')
root_volume_uuid = test_lib.lib_get_root_volume_uuid(vm.get_vm())
snapshots3 = test_obj_dict.get_volume_snapshot(root_volume_uuid)
snapshots3.set_utility_vm(vm)
vm.check()
snapshots3.create_snapshot('create_root_snapshot3')
test_util.test_dsc('VM reinit')
vm.stop()
vm.reinit()
vm.update()
vm.check()
vm.start()
vm.check()
num = 1
while num <= 6:
cmd = '[ -e /root/test-file-%s ] && echo yes || echo no' % num
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('test-file-%s should not exist' % num)
num = num + 1
test_util.test_dsc('VM return to snapshot3')
vm.stop()
snapshots3.use_snapshot(snapshots.get_current_snapshot())
vm.start()
vm.check()
num_arr = [1, 2, 4]
for i in num_arr:
cmd = '[ -e /root/test-file-%s ] && echo yes || echo no' % i
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('test-file-%s should not exist' % i)
num_arr = [3, 5, 6]
for i in num_arr:
cmd = '[ -e /root/test-file-%s ] && echo yes || echo no' % i
rsp = test_lib.lib_execute_ssh_cmd(vm_ip, 'root', 'password', cmd, 180)
if rsp == False:
test_util.test_fail('test-file-%s should exist' % i)
vm.destroy()
test_util.test_pass('Re-init VM Test Success')
#Will be called only if exception happens in test().
def error_cleanup():
test_lib.lib_error_cleanup(test_obj_dict)
|
knocknote/libhtml5
|
include/webgl_texture.h
|
#pragma once
#include "webgl_object.h"
NAMESPACE_HTML5_BEGIN;
class WebGLTexture : public WebGLObject {
public:
WebGLTexture(emscripten::val v);
virtual ~WebGLTexture();
static WebGLTexture *create(emscripten::val v);
};
NAMESPACE_HTML5_END;
|
prot3ct/WorkIt
|
WorkIt/app/src/main/java/prot3ct/workit/views/list_dialogs/ListDialogsFragment.java
|
package prot3ct.workit.views.list_dialogs;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.stfalcon.chatkit.commons.ImageLoader;
import com.stfalcon.chatkit.dialogs.DialogsList;
import com.stfalcon.chatkit.dialogs.DialogsListAdapter;
import java.lang.reflect.Array;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import prot3ct.workit.R;
import prot3ct.workit.models.Dialog;
import prot3ct.workit.models.Message;
import prot3ct.workit.models.User;
import prot3ct.workit.utils.WorkItProgressDialog;
import prot3ct.workit.view_models.DialogsListViewModel;
import prot3ct.workit.view_models.TaskDetailViewModel;
import prot3ct.workit.views.chat.ChatActivity;
import prot3ct.workit.views.list_dialogs.base.ListDialogsContract;
import prot3ct.workit.views.list_tasks.ListTasksActivity;
import prot3ct.workit.views.navigation.DrawerUtil;
public class ListDialogsFragment extends Fragment implements ListDialogsContract.View {
private ListDialogsContract.Presenter presenter;
private Context context;
private WorkItProgressDialog dialog;
private Toolbar toolbar;
private DialogsList dialogsListView;
private ArrayList<Dialog> dialogsToBeAdded;
public ListDialogsFragment() {
// Required empty public constructor
}
private ArrayList<Dialog> dialogs = new ArrayList<Dialog>();
public static ListDialogsFragment newInstance() {
return new ListDialogsFragment();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
@Override
public void setPresenter(ListDialogsContract.Presenter presenter) {
this.presenter = presenter;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_dialogs, container, false);
this.toolbar = view.findViewById(R.id.id_drawer_toolbar);
this.dialog = new WorkItProgressDialog(context);
this.dialogsToBeAdded = new ArrayList<>();
this.dialogsListView = view.findViewById(R.id.dialogsList);
DrawerUtil drawer = new DrawerUtil(this.getActivity(), this.toolbar);
drawer.getDrawer();
presenter.getDialogs();
return view;
}
@Override
public void notifyError(String errorMessage) {
Toast.makeText(getContext(), errorMessage, Toast.LENGTH_LONG).show();
}
@Override
public void notifySuccessful() {
Toast.makeText(getContext(), "Task updated successfully", Toast.LENGTH_SHORT).show();
}
@Override
public void showDialogforLoading() {
this.dialog.showProgress("Creating task...");
}
@Override
public void dismissDialog() {
this.dialog.dismissProgress();
}
@Override
public void updateDialogs(List<DialogsListViewModel> dialogs) {
for (DialogsListViewModel dialog: dialogs) {
User lastMessageUser = new User(1+"", "", null, false);
Message lastMessage;
if (dialog.getLastMessageText() == null) {
lastMessage = new Message(1+"", lastMessageUser, "", new Date());
}
else {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.ENGLISH);
Date lastMessageDate = null;
try {
lastMessageDate = format.parse(dialog.getLastMessageCreatedAt());
} catch (ParseException e) {
e.printStackTrace();
}
lastMessage = new Message(1+"", lastMessageUser, dialog.getLastMessageText(), lastMessageDate);
}
String dialogName;
String picture;
User userChattingWith;
if (presenter.getLoggedInUserId() == dialog.getUser1Id()) {
dialogName = dialog.getUser2Name();
picture = dialog.getUser2Picture();
userChattingWith = new User(dialog.getUser2Id()+"", dialog.getUser2Name(), null, false);
}
else {
dialogName = dialog.getUser1Name();
picture = dialog.getUser1Picture();
userChattingWith = new User(dialog.getUser1Id()+"", dialog.getUser1Name(), null, false);
}
ArrayList<User> users = new ArrayList<>();
users.add(userChattingWith);
Dialog dialogToBeAdded = new Dialog(dialog.getDialogId()+"", dialogName, picture, users, lastMessage, 0);
dialogsToBeAdded.add(dialogToBeAdded);
}
DialogsListAdapter dialogsListAdapter = new DialogsListAdapter<>(new ImageLoader() {
@Override
public void loadImage(ImageView imageView, String url) {
if(url == null) {
imageView.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.blank_profile_picture));
}
else {
byte[] decodedString = Base64.decode(url, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(bmp);
}
}
});
dialogsListAdapter.setItems(dialogsToBeAdded);
dialogsListAdapter.setOnDialogClickListener(new DialogsListAdapter.OnDialogClickListener<Dialog>() {
@Override
public void onDialogClick(Dialog dialog) {
showChatActivity(Integer.parseInt(dialog.getId()));
}
});
dialogsListView.setAdapter(dialogsListAdapter);
}
public void showChatActivity(int dialogId) {
Intent intent = new Intent(this.context, ChatActivity.class);
intent.putExtra("dialogId", dialogId);
startActivity(intent);
}
}
|
rzuckerm/pylama
|
pylama/lint/pylama_vulture.py
|
<filename>pylama/lint/pylama_vulture.py
"""Support Vulture."""
from argparse import ArgumentParser
from vulture.core import ERROR_CODES, Vulture, make_config
from pylama.context import RunContext
from pylama.lint import LinterV2 as BaseLinter
class Linter(BaseLinter):
"""vulture runner."""
name = "vulture"
@classmethod
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
parser.add_argument(
"--vulture-min-confidence",
type=int,
help="Minimum confidence (between 0 and 100) for code to be reported as unused.",
)
parser.add_argument(
"--vulture-ignore-names",
help="Comma-separated list of names to ignore",
)
parser.add_argument(
"--vulture-ignore-decorators",
help="Comma-separated list of decorators to ignore",
)
def run_check(self, ctx: RunContext): # noqa
"""Check code with vulture."""
params = ctx.get_params("vulture")
options = ctx.options
if options:
params.setdefault("min-confidence", options.vulture_min_confidence)
params.setdefault("ignore-names", options.vulture_ignore_names)
params.setdefault("ignore-decorators", options.vulture_ignore_decorators)
config = make_config(parse_params(ctx.filename, params))
vulture = Vulture(
verbose=config["verbose"],
ignore_names=config["ignore_names"],
ignore_decorators=config["ignore_decorators"],
)
vulture.scan(ctx.source, filename=ctx.filename)
unused_code_items = vulture.get_unused_code(
min_confidence=config["min_confidence"], sort_by_size=config["sort_by_size"]
)
for item in unused_code_items:
error_code = ERROR_CODES[item.typ]
ctx.push(
source="vulture",
type="R",
lnum=item.first_lineno,
number=error_code,
text=f"{item.message} ({item.confidence}% confidence)",
)
def parse_params(path, params=None):
"""Convert params from pylama."""
return [f"--{key}={value}" for key, value in params.items() if value] + [path]
|
npocmaka/Windows-Server-2003
|
base/ntos/verifier/vfbugcheck.h
|
/*++
Copyright (c) 2000 Microsoft Corporation
Module Name:
vfbugcheck.h
Abstract:
This header defines the prototypes and constants required for verifier
bugchecks.
Author:
<NAME> (adriao) 20-Apr-1998
Revision History:
AdriaO 02/21/2000 - Moved from ntos\io\ioassert.h
--*/
#ifndef _VFBUGCHECK_H_
#define _VFBUGCHECK_H_
extern LONG IovpInitCalled;
#define KDASSERT(x) { if (KdDebuggerEnabled) { ASSERT(x) ; } }
#define ASSERT_SPINLOCK_HELD(x)
#define DCPARAM_ROUTINE 0x00000001
#define DCPARAM_IRP 0x00000008
#define DCPARAM_IRPSNAP 0x00000040
#define DCPARAM_DEVOBJ 0x00000200
#define DCPARAM_STATUS 0x00001000
#define DCPARAM_ULONG 0x00008000
#define DCPARAM_PVOID 0x00040000
#define WDM_FAIL_ROUTINE(ParenWrappedParamList) \
{ \
if (IovpInitCalled) { \
VfBugcheckThrowIoException##ParenWrappedParamList;\
} \
}
VOID
FASTCALL
VfBugcheckInit(
VOID
);
NTSTATUS
VfBugcheckThrowIoException(
IN DCERROR_ID MessageIndex,
IN ULONG MessageParameterMask,
...
);
NTSTATUS
VfBugcheckThrowException(
IN PVFMESSAGE_TEMPLATE_TABLE MessageTable OPTIONAL,
IN VFMESSAGE_ERRORID MessageID,
IN PCSTR MessageParamFormat,
IN va_list * MessageParameters
);
#endif // _VFBUGCHECK_H_
|
mtsamis/dyn4j
|
src/main/java/org/dyn4j/geometry/hull/MonotoneChain.java
|
/*
* Copyright (c) 2010-2020 <NAME> http://www.dyn4j.org/
* 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 the copyright holder nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dyn4j.geometry.hull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.dyn4j.geometry.RobustGeometry;
import org.dyn4j.geometry.Vector2;
import org.dyn4j.resources.Messages;
/**
* Implementation of the Andrew's Monotone Chain convex hull algorithm.
* <p>
* This implementation is not sensitive to colinear points and returns only
* the points of the convex hull.
* <p>
* This algorithm is O(n log n) worst case where n is the number of points.
* @author <NAME>
* @version 3.4.0
* @since 2.2.0
*/
public class MonotoneChain implements HullGenerator {
/* (non-Javadoc)
* @see org.dyn4j.geometry.hull.HullGenerator#generate(org.dyn4j.geometry.Vector2[])
*/
@Override
public Vector2[] generate(Vector2... points) {
// check for a null array
if (points == null) throw new NullPointerException(Messages.getString("geometry.hull.nullArray"));
// get the size
int size = points.length;
// check the size
if (size <= 2) return points;
try {
// sort the points
Arrays.sort(points, new MinXYPointComparator());
} catch (NullPointerException e) {
// if any comparison generates a null pointer exception
// throw a null pointer exception with a good message
throw new NullPointerException(Messages.getString("geometry.hull.nullPoints"));
}
// This algorithm is very resilient to errors even with the vastly imprecise
// Segment#getLocation. But we still implement it with RobustGeometry#getLocation
// in order to provide better coincident point removal and consistent results
// with the rest algorithms; the added overhead is quite small
// find the points whose x values are the smallest and largest
int minmin = 0, minmax = 0, maxmin = 0, maxmax = 0;
// minmin == minmax if there exists only one point who has the smallest
// x coordinate, likewise, maxmin == maxmax if there exists only one point
// who has the largest x coordinate
for (int i = 1; i < size; i++) {
// get the current values
Vector2 minxminy = points[minmin];
Vector2 minxmaxy = points[minmax];
Vector2 maxxminy = points[maxmin];
Vector2 maxxmaxy = points[maxmax];
// get the current point
Vector2 p = points[i];
// check against the minimum x
if (p.x < minxminy.x) {
// its the new minimum
minmin = i;
minmax = i;
} else if (p.x == minxminy.x) {
// if they are equal then we need to
// check the y coordinate
if (p.y > minxmaxy.y) {
minmax = i;
} else if (p.y < minxminy.y) {
minmin = i;
}
}
// check against the maximum x
if (p.x > maxxminy.x) {
// its the new maximum
maxmin = i;
maxmax = i;
} else if (p.x == maxxminy.x) {
// if they are equall then we need to
// check the y coordinate
if (p.y > maxxmaxy.y) {
maxmax = i;
} else if (p.y < maxxminy.y) {
maxmin = i;
}
}
}
// build the lower convex hull
List<Vector2> lower = new ArrayList<Vector2>();
Vector2 lp1 = points[maxmin];
Vector2 lp2 = points[minmin];
// push
lower.add(points[minmin]);
// loop over the points between the min and max
for (int i = minmax + 1; i <= maxmin; i++) {
// get the current point
Vector2 p = points[i];
// where is it relative to the dividing line?
if (RobustGeometry.getLocation(p, lp1, lp2) >= 0.0) {
// if its on or to the left of the dividing line
// check if this invalidates any points currently
// in the convex hull
int lSize = lower.size();
while (lSize >= 2) {
Vector2 p1 = lower.get(lSize - 1);
Vector2 p2 = lower.get(lSize - 2);
// check if the point is to the left of the
// last edge in the current convex hull
if (RobustGeometry.getLocation(p, p2, p1) > 0.0) {
// if so, we can safely add the new point and
// maintain convexity
break;
}
// otherwise we need to remove the top point because
// it creates a concavity
// pop
lower.remove(lSize - 1);
lSize--;
}
// when we are done always add the point
// (it will be removed later if it creates a concavity)
// push
lower.add(p);
}
}
// build the upper convex hull
List<Vector2> upper = new ArrayList<Vector2>();
Vector2 up1 = points[minmax];
Vector2 up2 = points[maxmax];
// push
upper.add(points[maxmax]);
// loop over the points between the min and max
for (int i = maxmax - 1; i >= minmax; i--) {
// get the current point
Vector2 p = points[i];
// where is it relative to the dividing line?
if (RobustGeometry.getLocation(p, up1, up2) >= 0.0) {
// if its on or to the left of the dividing line
// check if this invalidates any points currently
// in the convex hull
int uSize = upper.size();
while (uSize >= 2) {
Vector2 p1 = upper.get(uSize - 1);
Vector2 p2 = upper.get(uSize - 2);
// check if the point is to the left of the
// last edge in the current convex hull
if (RobustGeometry.getLocation(p, p2, p1) > 0.0) {
// if so, we can safely add the new point and
// maintain convexity
break;
}
// otherwise we need to remove the top point because
// it creates a concavity
// pop
upper.remove(uSize - 1);
uSize--;
}
// when we are done always add the point
// (it will be removed later if it creates a concavity)
// push
upper.add(p);
}
}
// check if the first element of the upper hull is the same as
// the last element of the lower hull
if (upper.get(0) == lower.get(lower.size() - 1)) {
upper.remove(0);
}
// likewise check the first element of the lower hull with the
// last element of the upper hull
if (lower.get(0) == upper.get(upper.size() - 1)) {
lower.remove(0);
}
// append all the upper hull points to the lower hull
// creating the complete convex hull
lower.addAll(upper);
// create and fill an array with the hull points
Vector2[] hull = new Vector2[lower.size()];
lower.toArray(hull);
// return the hull
return hull;
}
}
|
CrackerCat/iWeChat
|
header6.6.1/VoIPTokenRegisterObject.h
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
#import "PBMessageObserverDelegate-Protocol.h"
@class NSData;
@protocol VoIPTokenRegisterObjectDelegate;
@interface VoIPTokenRegisterObject : NSObject <PBMessageObserverDelegate>
{
NSData *m_token;
id <VoIPTokenRegisterObjectDelegate> _m_delegate;
}
@property(nonatomic) __weak id <VoIPTokenRegisterObjectDelegate> m_delegate; // @synthesize m_delegate=_m_delegate;
@property(retain, nonatomic) NSData *m_token; // @synthesize m_token;
- (void).cxx_destruct;
- (void)callOkDelegate;
- (void)callErrorDelegate;
- (void)MessageReturn:(id)arg1 Event:(unsigned int)arg2;
- (void)startRequest;
- (id)initWithToken:(id)arg1;
@end
|
zeusdeux/node
|
test/parallel/test-repl-tab-complete-crash.js
|
'use strict';
const common = require('../common');
const assert = require('assert');
const repl = require('repl');
var referenceErrorCount = 0;
common.ArrayStream.prototype.write = function(msg) {
if (msg.startsWith('ReferenceError: ')) {
referenceErrorCount++;
}
};
const putIn = new common.ArrayStream();
const testMe = repl.start('', putIn);
// https://github.com/nodejs/node/issues/3346
// Tab-completion for an undefined variable inside a function should report a
// ReferenceError.
putIn.run(['.clear']);
putIn.run(['function () {']);
testMe.complete('arguments.');
process.on('exit', function() {
assert.strictEqual(referenceErrorCount, 1);
});
|
LegacyManagement/gopherbot
|
bot/signal.go
|
// +build !test
package bot
import (
"log"
"os"
"os/signal"
"runtime"
"time"
"github.com/lnxjedi/robot"
"golang.org/x/sys/unix"
)
func sigHandle(sigBreak chan struct{}) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, unix.SIGINT, unix.SIGTERM, unix.SIGUSR1, unix.SIGUSR2)
loop:
for {
select {
case sig := <-sigs:
switch sig {
case unix.SIGINT, unix.SIGTERM:
state.Lock()
if state.shuttingDown {
Log(robot.Warn, "Received SIGINT/SIGTERM while shutdown in progress")
state.Unlock()
} else {
state.shuttingDown = true
state.Unlock()
signal.Stop(sigs)
Log(robot.Info, "Exiting on signal: %s", sig)
stop()
}
case unix.SIGUSR1:
buf := make([]byte, 32768)
runtime.Stack(buf, true)
log.Printf("%s", buf)
time.Sleep(2 * time.Second)
panic("SIGUSR1 received")
case unix.SIGUSR2:
Log(robot.Info, "Restarting logfile")
logRotate("")
Log(robot.Info, "Log rotated")
}
// done declared globally at top of this file
case <-sigBreak:
Log(robot.Info, "Stopping signal handler")
break loop
}
}
}
// sigHandler for pid 1
func initSigHandle(c *os.Process) {
Log(robot.Info, "Starting pid 1 signal handler")
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, unix.SIGINT, unix.SIGTERM)
for {
select {
case sig := <-sigs:
signal.Stop(sigs)
Log(robot.Info, "Caught signal '%s', propagating to child pid %d", sig, c.Pid)
c.Signal(sig)
}
}
}
|
HiAwesome/dive-into-python3-practice
|
c09/p232_set_remove_duplicate_values.py
|
<filename>c09/p232_set_remove_duplicate_values.py
a_list = ['The', 'sixth', 'sick', "sheik's", 'sixth', "sheep's", 'sick']
print(a_list)
print(set(a_list))
print()
a_string = 'EAST IS EAST'
print(a_string)
print(set(a_string))
print()
words = ['SEND', 'MORE', 'MONEY']
print(''.join(words))
print(set(''.join(words)))
"""
['The', 'sixth', 'sick', "sheik's", 'sixth', "sheep's", 'sick']
{"sheik's", "sheep's", 'sixth', 'sick', 'The'}
EAST IS EAST
{'T', ' ', 'I', 'A', 'S', 'E'}
SENDMOREMONEY
{'Y', 'O', 'N', 'R', 'S', 'D', 'M', 'E'}
"""
|
etdev/algorithms
|
0_code_wars/noonerize.rb
|
# http://www.codewars.com/kata/56dbed3a13c2f61ae3000bcd
# --- iteration 1 ---
def noonerize(numbers)
return "invalid array" unless numbers.all? { |num| num.is_a?(Fixnum) }
nums_spoonerized = numbers.map(&:to_s).tap{ |(a, b)| a[0], b[0] = b[0], a[0] }.map(&:to_i)
nums_spoonerized.reduce(:-).abs
end
|
harunpehlivan/streamhub-sdk
|
src/content/views/content-view.js
|
<gh_stars>0
define([
'streamhub-sdk/jquery',
'streamhub-sdk/view',
'hgn!streamhub-sdk/content/templates/content',
'streamhub-sdk/util',
'inherits',
'streamhub-sdk/debug'
], function ($, View, ContentTemplate, util, inherits, debug) {
'use strict';
var log = debug('streamhub-sdk/content/views/content-view');
/**
* Defines the base class for all content-views. Handles updates to attachments
* and loading of images.
*
* @param opts {Object} The set of options to configure this view with.
* @param opts.content {Content} The content object to use when rendering.
* @param opts.el {?HTMLElement} The element to render this object in.
* @fires ContentView#removeContentView.hub
* @exports streamhub-sdk/content/views/content-view
* @constructor
*/
var ContentView = function ContentView (opts) {
opts = opts || {};
this.content = opts.content;
// store construction time to use for ordering if this.content has no dates
this.createdAt = new Date();
this.template = opts.template || this.template;
this.attachmentsView = opts.attachmentsView;
this._controls = {
'left': [],
'right': []
};
View.call(this, opts);
if (this.content) {
this.content.on("reply", function(content) {
this.render();
}.bind(this));
this.content.on("change:visibility", function(newVis, oldVis) {
this._handleVisibilityChange(newVis, oldVis);
}.bind(this));
// TODO: Re-render on change.
// Removed for now because re-rendering a ContentView and
// AttachmentsListView can unbind handlers important for modal
}
};
inherits(ContentView, View);
ContentView.prototype.elTag = 'article';
ContentView.prototype.elClass = 'content';
ContentView.prototype.contentWithImageClass = 'content-with-image';
ContentView.prototype.imageLoadingClass = 'hub-content-image-loading';
ContentView.prototype.tooltipElSelector = '.hub-tooltip-link';
ContentView.prototype.attachmentsElSelector = '.content-attachments';
ContentView.prototype.tiledAttachmentsElSelector = '.content-attachments-tiled';
ContentView.prototype.headerElSelector = '.content-header';
ContentView.prototype.avatarSelector = '.content-author-avatar';
ContentView.prototype.attachmentFrameElSelector = '.content-attachment-frame';
ContentView.prototype.footerLeftSelector = '.content-footer-left > .content-control-list';
ContentView.prototype.template = ContentTemplate;
ContentView.prototype.formatDate = util.formatDate;
ContentView.prototype.events = View.prototype.events.extended({
'imageLoaded.hub': function(e) {
this.$el.addClass(this.contentWithImageClass);
this.$el.removeClass(this.imageLoadingClass);
e.stopPropagation();
this.$el.parent().trigger('imageLoaded.hub', { contentView: this });
},
'imageError.hub': function(e, oembed) {
this.content.removeAttachment(oembed);
if (this.attachmentsView && this.attachmentsView.tileableCount && !this.attachmentsView.tileableCount()) {
this.$el.removeClass(this.contentWithImageClass);
this.$el.removeClass(this.imageLoadingClass);
}
e.stopPropagation();
this.$el.parent().trigger('imageError.hub', { oembed: oembed, contentView: this });
}
}, function (events) {
events['click ' + this.headerElSelector] = function(e) {
if (! this.$el.hasClass(this.contentWithImageClass)) {
// Only do this when there is an image
return;
}
var headerEl = $(e.currentTarget);
var frameEl = this.$el.find('.content-attachments-tiled ' + this.attachmentFrameElSelector);
headerEl.hide();
frameEl.hide();
var targetEl = document.elementFromPoint(e.clientX, e.clientY);
frameEl.show();
headerEl.show();
$(targetEl).trigger('click');
};
events['mouseenter ' + this.tooltipElSelector] = function (e) {
var target = e.target;
var title = $(target).attr('title');
var position = $(target).position();
var positionWidth = $(target).width();
var $currentTooltip = $("<div class=\"hub-current-tooltip content-action-tooltip\"><div class=\"content-action-tooltip-bubble\">" + title + "</div><div class=\"content-action-tooltip-tail\"></div></div>");
$(target).parent().append($currentTooltip);
var tooltipWidth = $currentTooltip.outerWidth();
var tooltipHeight = $currentTooltip.outerHeight();
$currentTooltip.css({
"left": position.left + (positionWidth / 2) - (tooltipWidth / 2),
"top": position.top - tooltipHeight - 2
});
if ($(target).hasClass(this.tooltipElSelector)){
var currentLeft = parseInt($currentTooltip.css('left'), 10);
$currentTooltip.css('left', currentLeft + 7);
}
$currentTooltip.fadeIn();
};
events['mouseleave ' + this.tooltipElSelector] = function (e) {
var $current = this.$el.find('.hub-current-tooltip');
$current.removeClass('hub-current-tooltip').fadeOut(200, function(){
$current.remove();
});
};
});
/**
* Set the .el DOMElement that the ContentView should render to
* @param el {DOMElement} The new element the ContentView should render to
* @returns {ContentView}
*/
ContentView.prototype.setElement = function (el) {
View.prototype.setElement.apply(this, arguments);
if (this.attachmentsView && this.attachmentsView.tileableCount && this.attachmentsView.tileableCount()) {
this.$el.addClass(this.imageLoadingClass);
}
if (this.content && this.content.id) {
this.$el.attr('data-content-id', this.content.id);
}
this.attachHandlers();
return this;
};
/**
* Render the content inside of the ContentView's element.
* @returns {ContentView}
*/
ContentView.prototype.render = function () {
var context = this.getTemplateContext();
if (this.content.createdAt) {
context.formattedCreatedAt = this.formatDate(this.content.createdAt);
}
this.el.innerHTML = this.template(context);
// If avatar fails to load, hide it
// Error events don't bubble, so we have to bind here
// http://bit.ly/JWp86R
this.$(this.avatarSelector+' img')
.on('error', $.proxy(this._handleAvatarError, this));
if (this.attachmentsView) {
this.attachmentsView.setElement(this.$el.find(this.attachmentsElSelector)[0]);
this.attachmentsView.render();
}
return this;
};
/**
* Binds event handlers on this.el
* This is deprecated now that View provides .delegateEvents, but retained
* in v2 for public interface consistency
* It should be removed in v3
* @deprecated
* @returns {ContentView}
*/
ContentView.prototype.attachHandlers = function () {
return this;
};
/**
* Gets the template rendering context. By default, returns "this.content".
* @returns {Content} The content object this view was instantiated with.
*/
ContentView.prototype.getTemplateContext = function () {
var context = $.extend({}, this.content);
// Ensure that content.body has a p tag
var isHtml = /^\s*<(p|div)/;
if ( ! isHtml.test(context.body)) {
context.body = '<p>'+context.body+'</p>';
}
return context;
};
/**
* Removes the content view element, and triggers 'removeContentView.hub'
* event for the instance to be removed from its associated ListView.
*/
ContentView.prototype.remove = function() {
/**
* removeContentView.hub
* @event ContentView#removeContentView.hub
* @type {{contentView: ContentView}}
*/
this.$el.trigger('removeContentView.hub', { contentView: this });
this.$el.detach();
};
/**
* Handles changes to the model's visibility.
* @param ev
* @param oldVis {string} Content.enum.visibility
* @param newVis {string} Content.enum.visibility
*/
ContentView.prototype._handleVisibilityChange = function(newVis, oldVis) {
if (newVis !== 'EVERYONE') {
this.remove();
}
};
/**
* Handle an error loading the avatar by removing the avatar element
* @private
*/
ContentView.prototype._handleAvatarError = function (e) {
log('avatar error, hiding it', e);
this.$(this.avatarSelector).remove();
};
ContentView.prototype.destroy = function () {
View.prototype.destroy.call(this);
this.content = null;
};
ContentView.prototype.addButton = function (button) {
this._controls.left.push(button);
var footerLeft = this.$el.find(this.footerLeftSelector);
var buttonContainerEl = $('<div></div>');
footerLeft.append(buttonContainerEl);
button.setElement(buttonContainerEl);
button.render();
};
ContentView.prototype.removeButton = function (button) {
button.destroy();
};
return ContentView;
});
|
Limmen/AgentProgramming
|
hw1/src/main/java/kth/se/id2209/limmen/tourguide/TourItem.java
|
package kth.se.id2209.limmen.tourguide;
import jade.core.AID;
import java.io.Serializable;
/**
*
* Class representing an item in a virtual tour
*
* @author <NAME> on 2016-11-10.
*/
public class TourItem implements Serializable{
private String title;
private AID curator;
public TourItem(String title, AID curator) {
this.title = title;
this.curator = curator;
}
@Override
public String toString(){
return "Artifact Name: " + title + " | Art-Gallery Curator: " + curator.getName();
}
@Override
public boolean equals(Object object){
if(((TourItem) object).getTitle().equals(title))
return true;
else
return false;
}
public String getTitle() {
return title;
}
public AID getCurator() {
return curator;
}
}
|
brightestC/docsdk-java
|
src/main/java/com/docsdk/dto/result/AsyncResult.java
|
package com.docsdk.dto.result;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public abstract class AsyncResult<T> extends AbstractResult<T> {
public abstract Result<T> get() throws InterruptedException, ExecutionException, IOException;
public abstract Result<T> get(
final long timeout, final TimeUnit timeUnit
) throws InterruptedException, ExecutionException, TimeoutException, IOException;
}
|
cshtdd/hb-api
|
src/main/java/com/tddapps/model/heartbeats/internal/RequestHandlerHelperCurrentRegion.java
|
<reponame>cshtdd/hb-api
package com.tddapps.model.heartbeats.internal;
import com.tddapps.model.heartbeats.HeartBeat;
import com.tddapps.model.heartbeats.RequestHandlerHelper;
import com.tddapps.model.infrastructure.Settings;
import com.tddapps.model.infrastructure.SettingsReader;
import lombok.extern.log4j.Log4j2;
import java.util.Arrays;
@Log4j2
public class RequestHandlerHelperCurrentRegion implements RequestHandlerHelper {
private final SettingsReader settingsReader;
public RequestHandlerHelperCurrentRegion(SettingsReader settingsReader) {
this.settingsReader = settingsReader;
}
@Override
public HeartBeat[] filter(HeartBeat[] heartBeats) {
return Arrays.stream(heartBeats)
.filter(HeartBeat::isNotTest)
.filter(this::heartBeatLastUpdatedInCurrentRegion)
.distinct()
.toArray(HeartBeat[]::new);
}
private boolean heartBeatLastUpdatedInCurrentRegion(HeartBeat hb){
return ReadRegion().equals(hb.getRegion());
}
private String ReadRegion() {
return settingsReader.ReadString(Settings.AWS_REGION);
}
}
|
Fernal73/LearnCpp
|
Boost/array/array.cpp
|
<reponame>Fernal73/LearnCpp
#include <algorithm>
#include <boost/array.hpp>
#include <iostream>
#include <string>
using namespace std;
int main() {
typedef boost::array<string, 3> array;
array a;
a[0] = "cat";
a.at(1) = "zebra";
*a.rbegin() = "spider";
sort(a.begin(), a.end());
for (const string &s: a)
cout << s << endl;
cout << a.size() << endl;
cout << a.max_size() << endl;
}
|
locoframework/loco-rails
|
lib/loco/version.rb
|
<filename>lib/loco/version.rb
# frozen_string_literal: true
module Loco
VERSION = '5.0.0'
end
|
ayushmxn/piskel
|
src/js/rendering/OnionSkinRenderer.js
|
<reponame>ayushmxn/piskel
(function () {
var ns = $.namespace("pskl.rendering");
ns.OnionSkinRenderer = function (renderer, piskelController) {
pskl.rendering.CompositeRenderer.call(this);
this.piskelController = piskelController;
this.renderer = renderer;
this.add(this.renderer);
this.hash = "";
};
ns.OnionSkinRenderer.createInContainer = function (
container,
renderingOptions,
piskelController,
) {
// Do not use CachedFrameRenderers here, caching is performed in the render method
var renderer = new pskl.rendering.frame.FrameRenderer(
container,
renderingOptions,
["onion-skin-canvas"],
);
return new ns.OnionSkinRenderer(renderer, piskelController);
};
pskl.utils.inherit(
pskl.rendering.OnionSkinRenderer,
pskl.rendering.CompositeRenderer,
);
ns.OnionSkinRenderer.prototype.render = function () {
var frames = this.getOnionFrames_();
var hash = this.computeHash_(frames);
if (this.hash != hash) {
this.hash = hash;
this.clear();
if (frames.length > 0) {
var mergedFrame = pskl.utils.FrameUtils.merge(frames);
this.renderer.render(mergedFrame);
}
}
};
ns.OnionSkinRenderer.prototype.getOnionFrames_ = function () {
var frames = [];
var currentFrameIndex = this.piskelController.getCurrentFrameIndex();
var layer = this.piskelController.getCurrentLayer();
var previousIndex = currentFrameIndex - 1;
var previousFrame = layer.getFrameAt(previousIndex);
if (previousFrame) {
frames.push(previousFrame);
}
var nextIndex = currentFrameIndex + 1;
var nextFrame = layer.getFrameAt(nextIndex);
if (nextFrame) {
frames.push(nextFrame);
}
return frames;
};
ns.OnionSkinRenderer.prototype.computeHash_ = function (frames) {
var offset = this.getOffset();
var size = this.getDisplaySize();
var layers = this.piskelController.getLayers();
return [
this.getZoom(),
this.getGridWidth(),
offset.x,
offset.y,
size.width,
size.height,
frames
.map(function (f) {
return f.getHash();
})
.join("-"),
layers.length,
].join("-");
};
/**
* See @pskl.rendering.frame.CachedFrameRenderer
* Same issue : FrameRenderer setDisplaySize destroys the canvas
* @param {Number} width
* @param {Number} height
*/
ns.OnionSkinRenderer.prototype.setDisplaySize = function (width, height) {
var size = this.getDisplaySize();
if (size.width !== width || size.height !== height) {
this.superclass.setDisplaySize.call(this, width, height);
}
};
ns.OnionSkinRenderer.prototype.flush = function () {
this.hash = "";
};
})();
|
lumengbit1/LLG
|
src/components/RoadMaps/RoadMap6.js
|
import React, {Component} from 'react';
import { withStyles } from '@material-ui/core/styles';
import RoadMapLeftColumn from './RoadMapLeftColumn';
const styles = theme => ({
imgNumSpan: {
display: 'block',
lineHeight: 1,
fontSize: '1rem',
fontWeight: 700,
}
})
const splitName = (imgStr) => {
//let tSplit = imgStr.split('*')
let color = imgStr ? imgStr[0] : '';
let ties = imgStr ? imgStr[1] : null;
let imgName = color ? `C-${color === 'P' ? 'B' : 'R'}${ties ? 'G' : ''}-O` : '';//
let imgNum = ties || '';
return {imgName, imgNum}
}
const compressMaps = (roadmap,size=60) => {
const fullLength = roadmap ? roadmap.map(rd => rd.concat(Array(size-rd.length).fill(null))) : Array(6).fill(Array(size).fill(null));
let rows = [];
for(let i = 0; i < 3; i++) {
let cells = [];
for(let j = 0; j < size/2; j++) {
let mini = [fullLength[i*2][j*2],fullLength[i*2][j*2+1],fullLength[i*2+1][j*2],fullLength[i*2+1][j*2+1]];
cells.push(mini);
}
rows.push(cells);
}
return rows
}
class RoadMap6 extends Component {
constructor(props) {
super(props);
}
componentDidUpdate(prevProps,prevState) {
}
render() {
const {classes,rowData} = this.props;
if(rowData.BigEye.length === 6) compressMaps(rowData.BigEye);
const blank = (<img src={require(`../../images/blank.png`)} width="6" />)
const tblrw1 = (trData,i) => {
let fullWidth = trData.concat(Array(60-trData.length).fill(''));
return (
<tr key={i}>
{fullWidth.map((t,k) => (
<td key={k} width="13" align="center">
{splitName(t).imgName !== '' ? (<div style={{padding: 2, width: 13, height: 13, margin: '0 auto', backgroundSize: '100%', backgroundImage: `url(${require(`../../images/${splitName(t).imgName}.png`)})`}} >
{splitName(t).imgNum !== '' ? (<span className={classes.imgNumSpan} >{splitName(t).imgNum}</span>) : (<span></span>)}
</div>
) : (<div>
</div>)}
</td>
))
}
</tr>
)
};
const tblrw2 = (trData) => {
return (
<React.Fragment>
{trData.map((t,i) => (
(t !== '') ?
(<td key={i} className="roadmap3">
<div className={(t.length < 4) ? 'four-img-box text-left' : 'four-img-box text-right'}>
<p>
{(t[0]) ? (<img src={require(`../../images/C-${t[0]}-B.png`)} width="6" />) : (blank)}
{(t[1]) ? (<img src={require(`../../images/C-${t[1]}-B.png`)} width="6" />) : (blank)}
</p>
<p>
{(t[2]) ? (<img src={require(`../../images/C-${t[2]}-B.png`)} width="6" />) : (blank)}
{(t[3]) ? (<img src={require(`../../images/C-${t[3]}-B.png`)} width="6" />) : (blank)}
</p>
</div>
</td>)
:
(<td key={i}></td>)
))
}
</React.Fragment>
)
};
const tblrw3 = (trData) => {
return (
<React.Fragment>
{trData.map((t,i) => (
(t !== '') ?
(<td key={i} className="roadmap3">
<div className={(t.length < 4) ? 'four-img-box text-left' : 'four-img-box text-right'}>
<p>
{(t[0]) ? (<img src={require(`../../images/C-${t[0]}.png`)} width="6" />) : (blank)}
{(t[1]) ? (<img src={require(`../../images/C-${t[1]}.png`)} width="6" />) : (blank)}
</p>
<p>
{(t[2]) ? (<img src={require(`../../images/C-${t[2]}.png`)} width="6" />) : (blank)}
{(t[3]) ? (<img src={require(`../../images/C-${t[3]}.png`)} width="6" />) : (blank)}
</p>
</div>
</td>)
:
(<td key={i}></td>)
))
}
</React.Fragment>
)
};
const tblrw4 = (trData) => {
return (
<React.Fragment>
{trData.map((t,i) => (
(t !== '') ?
(<td key={i} className={(i === 0) ? 'lb-line' : ''}>
<div className={(t.length < 4) ? 'four-img-box text-left' : 'four-img-box text-right'}>
<p>
{(t[0]) ? (<img src={require(`../../images/sm-${t[0] === 'R' ? 'red' : 'blue'}-line.png`)} width="6" />) : (blank)}
{(t[1]) ? (<img src={require(`../../images/sm-${t[1] === 'R' ? 'red' : 'blue'}-line.png`)} width="6" />) : (blank)}
</p>
<p>
{(t[2]) ? (<img src={require(`../../images/sm-${t[2] === 'R' ? 'red' : 'blue'}-line.png`)} width="6" />) : (blank)}
{(t[3]) ? (<img src={require(`../../images/sm-${t[3] === 'R' ? 'red' : 'blue'}-line.png`)} width="6" />) : (blank)}
</p>
</div>
</td>)
:
(<td key={i}></td>)
))
}
</React.Fragment>
)
};
if(document.body.clientWidth>460){
return (
<table cellPadding="0" cellSpacing="0" className="main-tbl">
<tbody>
<tr>
<td className="firdt-td" valign="top">
<RoadMapLeftColumn predictor={rowData.Predictor} />
</td>
<td>
<table cellPadding="0" cellSpacing="0" width="100%" className="right-tbl">
<tbody>
{rowData.BigRoad.map((d,i) => (
tblrw1(d,i)
))}
{compressMaps(rowData.BigEye,120).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw2(d)}
</tr>
))}
{compressMaps(rowData.SmallRoad).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw3(d)}
{tblrw4(compressMaps(rowData.Cockroach)[i])}
</tr>
))}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
)}else{
return (
<table cellPadding="0" cellSpacing="0" className="main-tbl">
<tbody>
<tr>
<td className="firdt-td" valign="top">
<RoadMapLeftColumn predictor={rowData.Predictor} />
</td>
<td>
<table cellPadding="0" cellSpacing="0" width="100%" className="right-tbl">
<tbody>
{rowData.BigRoad.map((d,i) => (
tblrw1(d,i)
))}
{compressMaps(rowData.BigEye,120).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw2(d)}
</tr>
))}
{document.body.clientWidth<=460 ?
compressMaps(rowData.SmallRoad,120).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw3(d)}
</tr>
)) :
compressMaps(rowData.SmallRoad).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw3(d)}
</tr>
))}
{document.body.clientWidth<=460 ?
compressMaps(rowData.SmallRoad,120).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw4(compressMaps(rowData.Cockroach,120)[i])}
</tr>
)):
compressMaps(rowData.SmallRoad).map((d,i) => (
<tr key={i} className={i === 0 ? "top-extra-border" : ''}>
{tblrw4(compressMaps(rowData.Cockroach)[i])}
</tr>
))}
{/*{compressMaps(rowData.SmallRoad).map((d,i) => (*/}
{/*<tr key={i} className={i === 0 ? "top-extra-border" : ''}>*/}
{/*{tblrw3(d)}*/}
{/*</tr>*/}
{/*))}*/}
{/*{compressMaps(rowData.SmallRoad).map((d,i) => (*/}
{/*<tr key={i} className={i === 0 ? "top-extra-border" : ''}>*/}
{/*{tblrw4(compressMaps(rowData.Cockroach)[i])}*/}
{/*</tr>*/}
{/*))}*/}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>)
}
}
}
export default withStyles(styles)(RoadMap6);
|
wangxmin/my-travel-plans
|
app-src/scripts/main/global-filters/duration-filter.spec.js
|
<reponame>wangxmin/my-travel-plans<filename>app-src/scripts/main/global-filters/duration-filter.spec.js
'use strict';
describe('Filter: duration', function () {
// load the filter's module
beforeEach(module('superProductivity'));
// initialize a new instance of the filter before each test
var duration;
beforeEach(inject(function ($filter) {
duration = $filter('duration');
}));
it('should change some output:"', function () {
// var text = 'angularjs';
// expect(duration(text)).toBe('something else');
expect(true).toBe(true);
});
});
|
stlee42/epubfx
|
src/main/java/de/machmireinebook/epubeditor/javafx/cells/EditingTreeCellBehavior.java
|
<gh_stars>0
package de.machmireinebook.epubeditor.javafx.cells;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.input.MouseButton;
import org.apache.log4j.Logger;
import com.sun.javafx.scene.control.behavior.TreeCellBehavior;
public class EditingTreeCellBehavior<T> extends TreeCellBehavior<T>
{
private static final Logger logger = Logger.getLogger(EditingTreeCellBehavior.class);
public EditingTreeCellBehavior(final TreeCell<T> control) {
super(control);
}
@Override
protected void handleClicks(MouseButton button, int clickCount, boolean isAlreadySelected) {
// handle editing, which only occurs with the primary mouse button
TreeItem<T> treeItem = getNode().getTreeItem();
if (button == MouseButton.PRIMARY) {
if (clickCount == 1) {
// dont edit or cancel edit
edit(null);
} else if (clickCount == 2 && treeItem.isLeaf()) {
// don't edit on double click, but open the file
logger.info("double click no edit");
edit(null);
} else if (clickCount % 2 == 0) {
// try to expand/collapse branch tree item
treeItem.setExpanded(!treeItem.isExpanded());
}
}
}
@Override
protected boolean handleDisclosureNode(double x, double y) {
/* TreeCell<T> treeCell = getNode();
Node disclosureNode = treeCell.getDisclosureNode();
if (disclosureNode != null) {
if (disclosureNode.getBoundsInParent().contains(x, y)) {
if (treeCell.getTreeItem() != null) {
logger.info("treeItem " + treeCell.getTreeItem() +", was expanded: " + treeCell.getTreeItem().isExpanded());
treeCell.getTreeItem().setExpanded(! treeCell.getTreeItem().isExpanded());
logger.info("treeItem is now expanded: " + treeCell.getTreeItem().isExpanded());
}
return true;
}
} */
return false;
}
}
|
CaelestisZ/HeraQ
|
drivers/video/fbdev/exynos/decon_8890/panels/s6e3ha2k_lcd_ctrl.c
|
<gh_stars>0
/*
* drivers/video/decon/panels/s6e3ha2k_lcd_ctrl.c
*
* Samsung SoC MIPI LCD CONTROL functions
*
* Copyright (c) 2014 Samsung Electronics
*
* <NAME>, <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include "s6e3ha2k_param.h"
#include "lcd_ctrl.h"
/* use FW_TEST definition when you test CAL on firmware */
/* #define FW_TEST */
#ifdef FW_TEST
#include "../dsim_fw.h"
#include "mipi_display.h"
#else
#include "../dsim.h"
#include <video/mipi_display.h>
#endif
/* Porch values. It depends on command or video mode */
#define S6E3HA2K_CMD_VBP 15
#define S6E3HA2K_CMD_VFP 1
#define S6E3HA2K_CMD_VSA 1
#define S6E3HA2K_CMD_HBP 1
#define S6E3HA2K_CMD_HFP 1
#define S6E3HA2K_CMD_HSA 1
/* These need to define */
#define S6E3HA2K_VIDEO_VBP 15
#define S6E3HA2K_VIDEO_VFP 1
#define S6E3HA2K_VIDEO_VSA 1
#define S6E3HA2K_VIDEO_HBP 20
#define S6E3HA2K_VIDEO_HFP 20
#define S6E3HA2K_VIDEO_HSA 20
#define S6E3HA2K_HORIZONTAL 1440
#define S6E3HA2K_VERTICAL 2560
#ifdef FW_TEST /* This information is moved to DT */
#define CONFIG_FB_I80_COMMAND_MODE
struct decon_lcd s6e3ha2k_lcd_info = {
#ifdef CONFIG_FB_I80_COMMAND_MODE
.mode = DECON_MIPI_COMMAND_MODE,
.vfp = S6E3HA2K_CMD_VFP,
.vbp = S6E3HA2K_CMD_VBP,
.hfp = S6E3HA2K_CMD_HFP,
.hbp = S6E3HA2K_CMD_HBP,
.vsa = S6E3HA2K_CMD_VSA,
.hsa = S6E3HA2K_CMD_HSA,
#else
.mode = DECON_VIDEO_MODE,
.vfp = S6E3HA2K_VIDEO_VFP,
.vbp = S6E3HA2K_VIDEO_VBP,
.hfp = S6E3HA2K_VIDEO_HFP,
.hbp = S6E3HA2K_VIDEO_HBP,
.vsa = S6E3HA2K_VIDEO_VSA,
.hsa = S6E3HA2K_VIDEO_HSA,
#endif
.xres = S6E3HA2K_HORIZONTAL,
.yres = S6E3HA2K_VERTICAL,
/* Maybe, width and height will be removed */
.width = 70,
.height = 121,
/* Mhz */
.hs_clk = 1100,
.esc_clk = 20,
.fps = 60,
.mic_enabled = 1,
.mic_ver = MIC_VER_1_2,
};
#endif
/*
* 3HA2K lcd init sequence
*
* Parameters
* - mic_enabled : if mic is enabled, MIC_ENABLE command must be sent
* - mode : LCD init sequence depends on command or video mode
*/
void lcd_init(int id, struct decon_lcd *lcd)
{
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TEST_KEY_ON_F0,
ARRAY_SIZE(SEQ_TEST_KEY_ON_F0)) < 0)
dsim_err("fail to write KEY_ON init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_REG_F2,
ARRAY_SIZE(SEQ_REG_F2)) < 0)
dsim_err("fail to write F2 init command.\n");
if (lcd->mic_enabled)
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_REG_F9,
ARRAY_SIZE(SEQ_REG_F9)) < 0)
dsim_err("fail to write F9 init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_SHORT_WRITE, (unsigned long)SEQ_SLEEP_OUT[0], 0) < 0)
dsim_err("fail to write SLEEP_OUT init command.\n");
msleep(10);
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TEST_KEY_ON_F0,
ARRAY_SIZE(SEQ_TEST_KEY_ON_F0)) < 0)
dsim_err("fail to write KEY_ON init command.\n");
/* TE rising time change : 10 line earlier */
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TE_START_SETTING,
ARRAY_SIZE(SEQ_TE_START_SETTING)) < 0)
dsim_err("fail to write TE_START_SETTING command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_REG_F2,
ARRAY_SIZE(SEQ_REG_F2)) < 0)
dsim_err("fail to write F2 init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_SHORT_WRITE, SEQ_TE_ON[0], 0) < 0)
dsim_err("fail to write TE_on init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TOUCH_HSYNC,
ARRAY_SIZE(SEQ_TOUCH_HSYNC)) < 0)
dsim_err("fail to write TOUCH_HSYNC init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_PENTILE_CONTROL,
ARRAY_SIZE(SEQ_PENTILE_CONTROL)) < 0)
dsim_err("fail to write PENTILE_CONTROL init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_COLUMN_ADDRESS,
ARRAY_SIZE(SEQ_COLUMN_ADDRESS)) < 0)
dsim_err("fail to write COLUMN_ADDRESS init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_GAMMA_CONDITION_SET,
ARRAY_SIZE(SEQ_GAMMA_CONDITION_SET)) < 0)
dsim_err("fail to write GAMMA_CONDITION_SET init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_AID_SET,
ARRAY_SIZE(SEQ_AID_SET)) < 0)
dsim_err("fail to write AID_SET init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_ELVSS_SET,
ARRAY_SIZE(SEQ_ELVSS_SET)) < 0)
dsim_err("fail to write ELVSS_SET init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_GAMMA_UPDATE,
ARRAY_SIZE(SEQ_GAMMA_UPDATE)) < 0)
dsim_err("fail to write GAMMA_UPDATE init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_ACL_OFF,
ARRAY_SIZE(SEQ_ACL_OFF)) < 0)
dsim_err("fail to write ACL_OFF init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_ACL_OPR,
ARRAY_SIZE(SEQ_ACL_OPR)) < 0)
dsim_err("fail to write ACL_OPR init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_HBM_OFF,
ARRAY_SIZE(SEQ_HBM_OFF)) < 0)
dsim_err("fail to write HBM_OFF init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TSET_GLOBAL,
ARRAY_SIZE(SEQ_TSET_GLOBAL)) < 0)
dsim_err("fail to write TSET_GLOBAL init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TSET,
ARRAY_SIZE(SEQ_TSET)) < 0)
dsim_err("fail to write TSET init command.\n");
if (dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)SEQ_TEST_KEY_OFF_F0,
ARRAY_SIZE(SEQ_TEST_KEY_OFF_F0)) < 0)
dsim_err("fail to write KEY_OFF init command.\n");
/* Added 120ms delay before SEQ_DISPLAY_ON */
msleep(120);
}
void lcd_enable(int id)
{
if (dsim_wr_data(id, MIPI_DSI_DCS_SHORT_WRITE, (unsigned long)SEQ_DISPLAY_ON[0], 0) < 0)
dsim_err("fail to write DISPLAY_ON command.\n");
}
void lcd_disable(int id)
{
/* This function needs to implement */
}
/*
* Set gamma values
*
* Parameter
* - backlightlevel : It is from 0 to 26.
*/
int lcd_gamma_ctrl(int id, u32 backlightlevel)
{
/* This will be implemented
int ret;
ret = dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (u32)gamma22_table[backlightlevel],
GAMMA_PARAM_SIZE);
if (ret) {
dsim_err("fail to write gamma value.\n");
return ret;
}
*/
return 0;
}
int lcd_gamma_update(int id)
{
/* This will be implemented
int ret;
ret = dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (u32)SEQ_GAMMA_UPDATE,
ARRAY_SIZE(SEQ_GAMMA_UPDATE));
if (ret) {
dsim_err("fail to update gamma value.\n");
return ret;
}
*/
return 0;
}
int dsim_write_by_panel(int id, const u8 *cmd, u32 cmdSize)
{
int ret;
if (cmdSize == 1)
ret = dsim_wr_data(id, MIPI_DSI_DCS_SHORT_WRITE, cmd[0], 0);
else if (cmdSize == 2)
ret = dsim_wr_data(id, MIPI_DSI_DCS_SHORT_WRITE_PARAM, cmd[0], cmd[1]);
else
ret = dsim_wr_data(id, MIPI_DSI_DCS_LONG_WRITE, (unsigned long)cmd, cmdSize);
return ret;
}
int dsim_read_from_panel(int id, u8 addr, u32 size, u8 *buf)
{
int ret;
ret = dsim_rd_data(id, MIPI_DSI_DCS_READ, (u32)addr, size, buf);
return ret;
}
static int s6e3ha2_wqhd_dump(int dsim)
{
int ret = 0;
unsigned char id[S6E3HA2_RD_LEN];
unsigned char rddpm[S6E3HA2_RD_LEN + 1];
unsigned char rddsm[S6E3HA2_RD_LEN + 1];
unsigned char err_buf[S6E3HA2_RD_LEN + 1];
dsim_info(" + %s\n", __func__);
ret = dsim_write_by_panel(dsim, SEQ_TEST_KEY_ON_F0, ARRAY_SIZE(SEQ_TEST_KEY_ON_F0));
if (ret < 0) {
dsim_err("%s : fail to write CMD : SEQ_TEST_KEY_ON_F0\n", __func__);
}
ret = dsim_write_by_panel(dsim, SEQ_TEST_KEY_ON_FC, ARRAY_SIZE(SEQ_TEST_KEY_ON_FC));
if (ret < 0) {
dsim_err("%s : fail to write CMD : SEQ_TEST_KEY_ON_FC\n", __func__);
}
ret = dsim_read_from_panel(dsim, 0xEA, S6E3HA2_RD_LEN, err_buf);
if (ret != S6E3HA2_RD_LEN) {
dsim_err("%s : can't read Panel's EA Reg\n",__func__);
goto dump_exit;
}
dsim_dbg("=== Panel's 0xEA Reg Value ===\n");
dsim_dbg("* 0xEA : buf[0] = %x\n", err_buf[0]);
dsim_dbg("* 0xEA : buf[1] = %x\n", err_buf[1]);
ret = dsim_read_from_panel(dsim, S6E3HA2_RDDPM_ADDR, S6E3HA2_RD_LEN, rddpm);
if (ret != S6E3HA2_RD_LEN) {
dsim_err("%s : can't read RDDPM Reg\n",__func__);
goto dump_exit;
}
dsim_info("=== Panel's RDDPM Reg Value : %x ===\n", rddpm[0]);
if (rddpm[0] & 0x80)
dsim_info("* Booster Voltage Status : ON\n");
else
dsim_info("* Booster Voltage Status : OFF\n");
if (rddpm[0] & 0x40)
dsim_info("* Idle Mode : On\n");
else
dsim_info("* Idle Mode : OFF\n");
if (rddpm[0] & 0x20)
dsim_info("* Partial Mode : On\n");
else
dsim_info("* Partial Mode : OFF\n");
if (rddpm[0] & 0x10)
dsim_info("* Sleep OUT and Working Ok\n");
else
dsim_info("* Sleep IN\n");
if (rddpm[0] & 0x08)
dsim_info("* Normal Mode On and Working Ok\n");
else
dsim_info("* Sleep IN\n");
if (rddpm[0] & 0x04)
dsim_info("* Display On and Working Ok\n");
else
dsim_info("* Display Off\n");
ret = dsim_read_from_panel(dsim, S6E3HA2_RDDSM_ADDR, S6E3HA2_RD_LEN, rddsm);
if (ret != S6E3HA2_RD_LEN) {
dsim_err("%s : can't read RDDSM Reg\n",__func__);
goto dump_exit;
}
dsim_info("=== Panel's RDDSM Reg Value : %x ===\n", rddsm[0]);
if (rddsm[0] & 0x80)
dsim_info("* TE On\n");
else
dsim_info("* TE OFF\n");
if (rddsm[0] & 0x02)
dsim_info("* S_DSI_ERR : Found\n");
if (rddsm[0] & 0x01)
dsim_info("* DSI_ERR : Found\n");
ret = dsim_read_from_panel(dsim, S6E3HA2_ID_REG, S6E3HA2_RD_LEN, id);
if (ret != S6E3HA2_RD_LEN) {
dsim_err("%s : can't read panel id\n",__func__);
goto dump_exit;
}
ret = dsim_write_by_panel(dsim, SEQ_TEST_KEY_OFF_FC, ARRAY_SIZE(SEQ_TEST_KEY_OFF_FC));
if (ret < 0) {
dsim_err("%s : fail to write CMD : SEQ_TEST_KEY_OFF_FC\n", __func__);
}
ret = dsim_write_by_panel(dsim, SEQ_TEST_KEY_OFF_F0, ARRAY_SIZE(SEQ_TEST_KEY_OFF_F0));
if (ret < 0) {
dsim_err("%s : fail to write CMD : SEQ_TEST_KEY_OFF_F0\n", __func__);
}
dump_exit:
dsim_info(" - %s\n", __func__);
return ret;
}
int lcd_dump(int id)
{
s6e3ha2_wqhd_dump(id);
return 0;
}
|
caolizhi/juc
|
src/main/java/top/caolizhi/example/juc/basic/SleepYieldJoin.java
|
<reponame>caolizhi/juc
/**
*@Description Sleep Yield 和 Join 的比较
*@Author 宝子哥
*@Date 2021/7/15 10:11
*@Version 1.0
**/
package top.caolizhi.example.juc.basic;
public class SleepYieldJoin {
/**
* 当前线程暂停一段时间让给别的线程去运行
*/
static void testSleep() {
System.out.println("thread " + Thread.currentThread().getName() + " suspend ....");
new Thread(() -> {
System.out.println("thread " + Thread.currentThread().getName() + " start ...");
for (int i = 0; i < 100; i++) {
System.out.println("i" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("thread " + Thread.currentThread().getName() + " end ...");
}).start();
}
/**
* 当前线程停下来进入等待队列,系统的调度算法可能还会把刚回的这个线程再拿出来执行,
* 更大的可能性是把原来等待的线程拿出一个来执行
*/
static void testYield() {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println("A " + i);
if (i % 10 == 0) {
Thread.yield();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println("**********B " + i);
if (i % 10 == 0) {
Thread.yield();
}
}
}).start();
}
/**
* 当前线程等待 join 的线程执行完,然后再继续执行当前线程,自己 join 自己没有意义
*/
static void testJoin() throws InterruptedException {
Thread t1 = new Thread(() -> {
System.out.println("thread " + Thread.currentThread().getName() + " start ...");
for (int i = 0; i < 100; i++) {
System.out.println("A" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("thread " + Thread.currentThread().getName() + " end ...");
});
Thread t2 = new Thread(() -> {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread " + Thread.currentThread().getName() + " start ...");
for (int i = 0; i < 100; i++) {
System.out.println("B" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("thread " + Thread.currentThread().getName() + " end ...");
});
t1.start();
t2.start();
}
public static void main(String[] args) {
//testSleep();
//testYield();
try {
testJoin();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
mengxy/swc
|
crates/swc_ecma_codegen/tests/test262-min/8f9e8be5a6c50e77.js
|
<reponame>mengxy/swc
function a(){return function b(c){}}
|
felipolis/UTFPR
|
Algoritmos/Vetores em C/Ex10.c
|
<gh_stars>0
#include <stdio.h>
int main(){
///Declaracao de variaveis
int A[30];
int maior;
int B[30];
int i;
///Lendo o vetor A
for(i = 0; i < 30; i++){
printf("Digite um numero inteiro para o vetor A: ");
scanf("%d", &A[i]);
}
///Imprimindo o vetor A
printf("\n\nVetor A = [");
for(i = 0; i < 30; i++){
printf(" %d", A[i]);
}
printf(" ]\n\n");
///Maior valor de A
maior = A[0];
for(i = 0; i < 30; i++){
if(A[i] > maior){
maior = A[i];
}
}
///Construindo vetor B
for(i = 0; i < 30; i++){
B[i] = A[i] * maior;
}
///Imprimindo o vetor B
printf("\n\nVetor B = [");
for(i = 0; i < 30; i++){
printf(" %d", B[i]);
}
printf(" ]\n\n");
return 0;
}
|
ibm-datapower/appliance-management-center
|
src/main/java/com/ibm/amc/AmcRuntimeomiserException.java
|
<gh_stars>1-10
/**
* Copyright 2014 IBM Corp.
*
* 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.ibm.amc;
import com.ibm.amc.ras.Logger47;
/**
* Special case exception to be able to throw a checked exception
*
* @author mallman
*/
public class AmcRuntimeomiserException extends RuntimeException
{
// @CLASS-COPYRIGHT@
static Logger47 logger = Logger47.get(AmcRuntimeomiserException.class.getCanonicalName(), Constants.CWZBA_BUNDLE_NAME);
final AmcException amcException;
private static final long serialVersionUID = 3242721778327754398L;
public AmcRuntimeomiserException(final AmcException amcException)
{
super();
if (logger.isEntryEnabled()) logger.entry("<init>", amcException);
this.amcException = amcException;
if (logger.isEntryEnabled()) logger.exit("<init>");
}
public AmcException getAmcException()
{
return amcException;
}
}
|
peengtao123/cloud
|
clouddo/clouddo-admin/src/main/java/com/bootdo/clouddoadmin/utils/JwtUtils.java
|
<filename>clouddo/clouddo-admin/src/main/java/com/bootdo/clouddoadmin/utils/JwtUtils.java
//package com.bootdo.clouddoadmin.utils;
//
//import com.bootdo.clouddoadmin.constants.constants;
//import com.bootdo.clouddoadmin.vo.UserToken;
//import com.netflix.discovery.CommonConstants;
//import io.jsonwebtoken.Claims;
//import io.jsonwebtoken.Jws;
//import io.jsonwebtoken.Jwts;
//import io.jsonwebtoken.SignatureAlgorithm;
//
//import java.util.Date;
//
///**
// * @author bootdo <EMAIL>
// * @version V1.0
// */
//public class JwtUtils {
// public static String generateToken(UserToken userToken, int expire) throws Exception {
// String token = Jwts.builder()
// .setSubject(userToken.getUsername())
// .claim(constants.USER_TOKEN_ID, userToken.getUserId())
// .claim(constants.USER_TOKEN_NAME, userToken.getName())
// .setExpiration(new Date(System.currentTimeMillis()+expire))
// .signWith(SignatureAlgorithm.HS256, constants.JWT_PRIVATE_KEY)
// .compact();
// return token;
// }
//
//
// public static UserToken getInfoFromToken(String token) throws Exception {
// Claims claims = Jwts.parser()
// .setSigningKey(constants.JWT_PRIVATE_KEY).parseClaimsJws(token)
// .getBody();
// return new UserToken(claims.getSubject(), ((Integer)claims.get(constants.USER_TOKEN_ID)).longValue() ,claims.get(constants.USER_TOKEN_NAME).toString());
// }
//}
|
philipstaffordwood/konfigadm
|
pkg/types/command.go
|
<filename>pkg/types/command.go<gh_stars>0
package types
import (
"fmt"
"strings"
"github.com/flanksource/yaml"
log "github.com/sirupsen/logrus"
)
//Command encapsulates a command and the tags for which it is applicable
type Command struct {
Cmd string
Flags []Flag
}
type Commands struct {
dependencies *[]Command
commands *[]Command
}
func NewCommand(cmd string) Commands {
return Commands{
commands: &[]Command{Command{Cmd: cmd}},
}
}
func (c *Commands) AddAll(cmd ...Command) *Commands {
if c.commands == nil {
c.commands = &[]Command{}
}
commandsSlice := *c.commands
commandsSlice = append(commandsSlice, cmd...)
c.commands = &commandsSlice
return c
}
func (c *Commands) Add(commands ...string) *Commands {
if c.commands == nil {
c.commands = &[]Command{}
}
commandsSlice := *c.commands
for _, command := range commands {
commandsSlice = append(commandsSlice, Command{Cmd: command})
}
c.commands = &commandsSlice
return c
}
func (c *Commands) AddDependency(commands ...string) *Commands {
if c.dependencies == nil {
c.dependencies = &[]Command{}
}
commandsSlice := *c.dependencies
for _, command := range commands {
commandsSlice = append(commandsSlice, Command{Cmd: command})
}
c.dependencies = &commandsSlice
return c
}
func (c Commands) GetCommands() []Command {
if c.dependencies == nil && c.commands == nil {
return []Command{}
}
if c.dependencies == nil {
return *c.commands
}
if c.commands == nil {
return *c.dependencies
}
return append(*c.dependencies, *c.commands...)
}
func (c1 *Commands) Append(c2 Commands) *Commands {
var cmdSlice []Command
var depSlice []Command
if c1.commands == nil {
c1.commands = &[]Command{}
}
if c2.commands != nil {
cmdSlice = append(*c1.commands, *c2.commands...)
c1.commands = &cmdSlice
}
if c1.dependencies == nil {
c1.dependencies = &[]Command{}
}
if c2.dependencies != nil {
depSlice = append(*c1.dependencies, *c2.dependencies...)
c1.dependencies = &depSlice
}
return c1
}
func (c *Commands) Merge() []Command {
commands := []Command{}
if c.dependencies != nil {
commands = append(commands, *c.dependencies...)
}
if c.commands != nil {
commands = append(commands, *c.commands...)
}
return commands
}
func (c Commands) WithTags(tags ...Flag) Commands {
if c.commands != nil {
commands := *c.commands
for i, command := range commands {
command.Flags = tags
commands[i] = command
}
c.commands = &commands
}
if c.dependencies != nil {
dependencies := *c.dependencies
for i, command := range dependencies {
command.Flags = tags
dependencies[i] = command
}
c.dependencies = &dependencies
}
return c
}
func (c Command) String() string {
return c.Cmd + fmt.Sprintf("%s", c.Flags)
}
func (cfg *Config) AddCommand(cmd string, flags ...*Flag) *Config {
command := Command{Cmd: cmd}
for _, flag := range flags {
if flag != nil {
command.Flags = append(command.Flags, *flag)
}
}
cfg.Commands = append(cfg.Commands, command)
return cfg
}
//UnmarshalYAML decodes comments into tags
func (c *Command) UnmarshalYAML(node *yaml.Node) error {
c.Cmd = node.Value
comment := node.LineComment
if !strings.Contains(comment, "#") {
return nil
}
comment = comment[1:]
for _, flag := range strings.Split(comment, " ") {
if FLAG, ok := FLAG_MAP[flag]; ok {
c.Flags = append(c.Flags, FLAG)
} else {
log.Debugf("Ignoring flags: %s on line: %s\n", comment, node.Value)
return nil
}
}
return nil
}
//MarshalYAML ads tags as comments
func (c Command) MarshalYAML() (interface{}, error) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
LineComment: Marshall(c.Flags),
Value: c.Cmd,
}, nil
}
//FindCmd returns a list of commands starting with prefix
func (cfg *Config) FindCmd(prefix string) []*Command {
cmds := []*Command{}
for _, cmd := range cfg.PreCommands {
if strings.HasPrefix(cmd.Cmd, prefix) {
cmds = append(cmds, &cmd)
}
}
return cmds
}
|
akraino-edge-stack/iec
|
src/type3_AndroidCloud/anbox-master/src/anbox/utils.cpp
|
<filename>src/type3_AndroidCloud/anbox-master/src/anbox/utils.cpp
/*
* Copyright (C) 2016 <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <boost/filesystem.hpp>
#include <boost/throw_exception.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <fcntl.h>
#include <mntent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "anbox/utils.h"
namespace fs = boost::filesystem;
namespace anbox {
namespace utils {
std::vector<std::string> collect_arguments(int argc, char **argv) {
std::vector<std::string> result;
for (int i = 1; i < argc; i++) result.push_back(argv[i]);
return result;
}
std::string read_file_if_exists_or_throw(const std::string &file_path) {
if (!boost::filesystem::is_regular(boost::filesystem::path(file_path)))
BOOST_THROW_EXCEPTION(std::runtime_error("File does not exist"));
std::ifstream file;
file.open(file_path, std::ifstream::in);
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
bool write_to_file(const std::string &file_path, const std::string &content) {
std::ofstream of;
of.open(file_path, std::ofstream::out);
of << content;
of.close();
return true;
}
int write_to_fd(int fd, const char *content, ssize_t len) {
while (len > 0) {
const auto res = write(fd, content, len);
if (res < 0 && errno == EINTR) continue;
if (res <= 0) {
if (res == 0) /* Unexpected short write, should not happen when writing to
a file */
errno = ENOSPC;
return -1;
}
len -= res;
content += res;
}
return 0;
}
int write_file_at(int dirfd, const char *path, const char *content) {
const auto fd = openat(dirfd, path, O_RDWR | O_CLOEXEC, 0);
if (fd == -1) return -1;
auto res = 0;
if (content) res = write_to_fd(fd, content, strlen(content));
const auto errsv = errno;
close(fd);
errno = errsv;
return res;
}
bool string_starts_with(const std::string &text, const std::string &prefix) {
return text.compare(0, prefix.size(), prefix) == 0;
}
std::vector<std::string> string_split(const std::string &text, char sep) {
std::vector<std::string> tokens;
return boost::algorithm::split(tokens, text, boost::is_from_range(sep, sep), boost::algorithm::token_compress_on);
}
std::string strip_surrounding_quotes(const std::string &text) {
auto result = text;
if (text[0] == '\"' && text[text.length() - 1] == '\"')
result = text.substr(1, text.length() - 2);
return result;
}
std::string hex_dump(const uint8_t *data, uint32_t size) {
unsigned char buff[17];
const uint8_t *pc = data;
std::stringstream buffer;
if (size == 0) {
buffer << "NULL" << std::endl;
return buffer.str();
}
uint32_t i;
for (i = 0; i < size; i++) {
if ((i % 16) == 0) {
if (i != 0) buffer << string_format(" %s", buff) << std::endl;
buffer << string_format("%02x ", i);
}
buffer << string_format(" %02x", static_cast<int>(pc[i]));
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
while ((i % 16) != 0) {
buffer << " ";
i++;
}
buffer << string_format(" %s", buff) << std::endl;
return buffer.str();
}
std::string get_env_value(const std::string &name,
const std::string &default_value) {
char *value = getenv(name.c_str());
if (!value) return default_value;
return std::string(value);
}
bool is_env_set(const std::string &name) {
return getenv(name.c_str()) != nullptr;
}
void ensure_paths(const std::vector<std::string> &paths) {
for (const auto &path : paths) {
if (!fs::is_directory(fs::path(path)))
fs::create_directories(fs::path(path));
}
}
std::string prefix_dir_from_env(const std::string &path,
const std::string &env_var) {
static auto snap_data_path = anbox::utils::get_env_value(env_var, "");
auto result = path;
if (!snap_data_path.empty())
result = anbox::utils::string_format("%s%s", snap_data_path, path);
return result;
}
std::string process_get_exe_path(const pid_t &pid) {
auto exe_path = string_format("/proc/%d/exe", pid);
return boost::filesystem::read_symlink(exe_path).string();
}
bool is_mounted(const std::string &path) {
FILE *mtab = nullptr;
struct mntent *part = nullptr;
bool is_mounted = false;
if ((mtab = setmntent("/etc/mtab", "r")) != nullptr) {
while ((part = getmntent(mtab)) != nullptr) {
if ((part->mnt_fsname != nullptr) && (strcmp(part->mnt_fsname, path.c_str())) == 0)
is_mounted = true;
}
endmntent(mtab);
}
return is_mounted;
}
std::string find_program_on_path(const std::string &name) {
struct stat sb;
std::string path = std::string(getenv("PATH"));
size_t start_pos = 0, end_pos = 0;
while ((end_pos = path.find(':', start_pos)) != std::string::npos) {
const auto current_path = path.substr(start_pos, end_pos - start_pos) + "/" + name;
if ((::stat(current_path.c_str(), &sb) == 0) && (sb.st_mode & S_IXOTH))
return current_path;
start_pos = end_pos + 1;
}
return "";
}
} // namespace utils
} // namespace anbox
|
a1967919189/HuasTools
|
app/src/main/java/com/xiaobudian/huastools/data/parse/ReplyParse.java
|
package com.xiaobudian.huastools.data.parse;
import com.xiaobudian.huastools.model.ReplyData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 小不点 on 2016/4/23.
*/
public class ReplyParse {
private List<String> l_accepting_unit_id;
private List<String> l_accepting_unit_data;
private List<String> l_category_id;
private List<String> l_category_data;
private List<ReplyData> mReplyDatas;
private List<String> l_details_html;
private String[] pages;
private List<String> l_page_id;
private List<String> l_page_data;
/**
* 获得主页信息
* @param html
*/
public void parseAll(String html){
if ((html==null)||(html.length()<1)) {
return;
}
l_accepting_unit_id=new ArrayList<String>();
l_accepting_unit_data=new ArrayList<String>();
l_category_id=new ArrayList<String>();
l_category_data=new ArrayList<String>();
mReplyDatas=new ArrayList<ReplyData>();
l_details_html=new ArrayList<String>();
l_page_id=new ArrayList<String>();
l_page_data=new ArrayList<String>();
Document document= Jsoup.parse(html);
/**
* 获取受理单位列表
*/
Elements e_accepting_unit=document.select("select[name=deptno]").select("option");
for(Element e:e_accepting_unit){
l_accepting_unit_id.add(e.attr("value").toString());
l_accepting_unit_data.add(e.text().toString());
}
/**
* 获取类别列表
*/
Elements e_category=document.select("select[id=requestType]").select("option");
for(Element e:e_category){
l_category_id.add(e.attr("value").toString());
l_category_data.add(e.text().toString());
}
/**
* 获取列表信息
*/
Elements e_list=document.select("tbody").get(1).select("tr");
for(int i=1;i<e_list.size();i++){
ReplyData replyData=new ReplyData();
replyData.setSerial_number(e_list.get(i).select("td").get(0).text().toString());
replyData.setTheme(e_list.get(i).select("td").get(1).text().toString());
replyData.setDate(e_list.get(i).select("td").get(2).text().toString());
replyData.setCategory(e_list.get(i).select("td").get(3).text().toString());
replyData.setAccepting_unit(e_list.get(i).select("td").get(4).text().toString());
replyData.setProcessing_status(e_list.get(i).select("td").get(5).text().toString());
mReplyDatas.add(replyData);
}
/**
* 获取详情网址
*/
for(int i=1;i<e_list.size();i++){
l_details_html.add("http://www.huas.cn:316/sunhuas/"+e_list.get(i).select("a").attr("href"));
}
/**
* 获取页码
*/
Elements e_page=document.select("tbody").last().select("td");
pages=new String[4];
pages[0]=e_page.get(0).text().toString();
pages[1]=e_page.get(1).text().toString();
pages[2]=e_page.get(2).text().toString();
pages[3]=e_page.get(4).text().toString();
Elements e_page_select=e_page.get(3).select("option");
for(Element e:e_page_select){
l_page_id.add(e.attr("value").toString());
l_page_data.add(e.text().toString());
}
}
/**
* 获取查看回复详情信息
* @param html
* @return
*/
public List<String> getReplyDetails(String html){
List<String> l_reply_detials=new ArrayList<>();
Document document=Jsoup.parse(html);
Elements elements2=document.select("tbody").get(1).select("tr");
for(int i=0;i<elements2.size()-6;i++){
Elements elements=elements2.get(i).select("td");
for(int j=0;j<elements.size();j++){
if(i==4&&j==1){
String text=elements.get(j).select("div[id=towaddress]").text();
l_reply_detials.add(text);
}else if(i==6&&j==1){
String text=elements.get(j).select("div[id=towcontent]").text();
l_reply_detials.add(text);
}
else{
l_reply_detials.add(elements.get(j).text().toString());
// l_reply_detials.add(elements2.get(i).select("td").get(j).text().toString());
}
}
}
return l_reply_detials;
}
public List<String> get_accepting_unit_id(){
return l_accepting_unit_id;
}
public List<String> get_accepting_unit_data(){
return l_accepting_unit_data;
}
public List<String> get_category_id(){
return l_category_id;
}
public List<String> get_category_data(){
return l_category_data;
}
public List<ReplyData> getReplyDatas() {
return mReplyDatas;
}
public List<String> get_details_html(){
return l_details_html;
}
public String[] get_pages(){
return pages;
}
public List<String> get_page_id(){
return l_page_id;
}
public List<String> get_page_data(){
return l_page_data;
}
}
|
Geode-solutions/OpenGeode
|
include/geode/basic/pimpl_impl.h
|
<gh_stars>10-100
/*
* Copyright (c) 2019 - 2021 Geode-solutions
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#pragma once
namespace geode
{
template < typename T >
template < typename... Args >
PImpl< T >::PImpl( Args&&... args )
: pimpl_{ new T{ std::forward< Args >( args )... } }
{
}
template < typename T >
PImpl< T >::PImpl( PImpl< T >&& other )
: pimpl_{ std::move( other.pimpl_ ) }
{
}
template < typename T >
PImpl< T >::~PImpl()
{
}
template < typename T >
void PImpl< T >::reset()
{
return pimpl_.reset();
}
template < typename T >
const T* PImpl< T >::operator->() const
{
return pimpl_.get();
}
template < typename T >
T* PImpl< T >::operator->()
{
return pimpl_.get();
}
template < typename T >
T& PImpl< T >::operator*()
{
return *pimpl_.get();
}
template < typename T >
const T& PImpl< T >::operator*() const
{
return *pimpl_.get();
}
} // namespace geode
|
knute-sifive/map
|
sparta/sparta/statistics/dispatch/StatisticsHierRootNodes.hpp
|
<gh_stars>0
// <StatisticsHierRootNodes> -*- C++ -*-
#ifndef __SPARTA_STATISTICS_HIER_ROOT_NODES_H__
#define __SPARTA_STATISTICS_HIER_ROOT_NODES_H__
#include <memory>
#include <string>
#include <unordered_map>
namespace sparta {
namespace statistics {
/*!
* \brief Utility class that holds onto statistics node
* hierarchies, accessible by a name that you choose.
*/
template <class StorageT>
class StatisticsHierRootNodes
{
public:
virtual ~StatisticsHierRootNodes() {}
//! Append a statistics hierarchy root node to this set
void addHierarchyRoot(const std::string & storage_name,
std::shared_ptr<StorageT> & root)
{
sparta_assert(root != nullptr, "Unexpected null statistics hierarchy root encountered");
if (roots_.count(storage_name) > 0) {
throw SpartaException("Statistic hiearchy with root named '") << storage_name
<< "' already exists in this statistics set";
}
roots_[storage_name] = root;
}
//! Access the root node names in this set
std::vector<std::string> getRootNames() const {
std::set<std::string> names;
for (const auto & root : roots_) {
names.insert(root.first);
}
const std::vector<std::string> more_names = getLazyLoadedRootNames_();
names.insert(more_names.begin(), more_names.end());
return std::vector<std::string>(names.begin(), names.end());
}
//! Maintain a mapping from report filenames like 'out.csv' to the
//! equivalent root name like 'out_csv'. This is to support tab
//! completion for Python shell users (Python won't allow dots in
//! node names).
void mapRootNameToReportFilename(const std::string & root_name,
const std::string & report_filename) const
{
root_names_to_report_filenames_[root_name] = report_filename;
}
//! Ask for a hierarchy root node by name. The name should be
//! one that you originally gave to addHierarchyRoot(), or this
//! method will return null.
StorageT * getRootByName(const std::string & root_name)
{
onNamedRootRequest_(root_name);
auto iter = roots_.find(root_name);
if (iter == roots_.end()) {
//Check if this root exists by a different name, for
//example the name passed in was 'out_csv' but its name
//in our hash is 'out.csv'
utils::ValidValue<std::string> report_filename =
getReportFilenameForRoot_(root_name);
if (report_filename.isValid()) {
return getRootByName(report_filename);
} else {
return nullptr;
}
}
return iter->second.get();
}
private:
utils::ValidValue<std::string> getReportFilenameForRoot_(
const std::string & root_name) const
{
utils::ValidValue<std::string> report_filename;
auto iter = root_names_to_report_filenames_.find(root_name);
if (iter != root_names_to_report_filenames_.end()) {
report_filename = iter->second;
}
return report_filename;
}
virtual void onNamedRootRequest_(const std::string & root_name) {
(void) root_name;
}
virtual std::vector<std::string> getLazyLoadedRootNames_() const {
return {};
}
mutable std::unordered_map<
std::string,
std::string> root_names_to_report_filenames_;
std::unordered_map<
std::string,
std::shared_ptr<StorageT>> roots_;
};
} // namespace sparta
} // namespace statistics
#endif
|
suvajitgupta/Tasks
|
persevere/WEB-INF/src/org/persvr/data/Status.java
|
<reponame>suvajitgupta/Tasks
package org.persvr.data;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.persvr.Persevere;
import org.persvr.data.Method.Timing;
import org.persvr.remote.AliasIds;
import org.persvr.remote.EventStream;
import org.persvr.security.PermissionLevel;
import org.persvr.security.SystemPermission;
import org.persvr.security.UserSecurity;
public class Status extends ReadonlyObject{
private Status() {
setPrototype(ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(),"Object"));
}
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
public static void initialize(){
Scriptable global = GlobalData.getGlobalScope();
global.put("status", global, instance);
}
static long startTime = new Date().getTime();
static long totalRequestTime;
static long requestCount;
static double runningAverageRequestTime;
static double maxRequestTime;
public static void addRequestTiming(long time){
totalRequestTime += time;
requestCount++;
runningAverageRequestTime = (runningAverageRequestTime * 9 + time) / 10;
maxRequestTime = Math.max(maxRequestTime, time);
}
public static Status instance = new Status();
public Object get(String key) {
if(PersistableObject.securityEnabled.get() != null){
if(!UserSecurity.hasPermission(SystemPermission.accessStatus)){
throw ScriptRuntime.constructError("AccessError", "You do not have access to the status object");
}
PersistableObject.checkSecurity(this, PermissionLevel.READ_LEVEL.level);
}
Runtime runtime = Runtime.getRuntime();
if ("freeMemory".equals(key))
return runtime.freeMemory();
if ("references".equals(key))
return DataSourceManager.softReferences ? "soft" : "weak";
if ("totalMemory".equals(key))
return runtime.totalMemory();
if ("maxMemory".equals(key))
return runtime.maxMemory();
if ("version".equals(key))
return Persevere.getPersevereVersion();
if ("availableProcessors".equals(key))
return runtime.availableProcessors();
if ("uptime".equals(key))
return (new Date().getTime() - startTime) / 1000;
if ("requests".equals(key))
return requestCount;
if ("averageRequestTime".equals(key))
return requestCount == 0 ? 0 : ((double)totalRequestTime) / requestCount;
if ("recentAverageRequestTime".equals(key))
return runningAverageRequestTime;
if ("maxRequestTime".equals(key))
return maxRequestTime;
long cpuTime = 0;
long userTime = 0;
int threadCount = 0;
for(long threadId : threadMXBean.getAllThreadIds()){
threadCount++;
cpuTime += threadMXBean.getThreadCpuTime(threadId);
userTime += threadMXBean.getThreadUserTime(threadId);
}
if ("threadCount".equals(key))
return threadCount;
if ("methodTimings".equals(key)) {
List timingsObject = new PersistableArray(0);
if(Method.timings != null)
for(Map.Entry<Method, Timing> entry : Method.timings.entrySet()){
Timing timing = entry.getValue();
Persistable timingObject = new PersistableObject();
timingObject.put("own", timingObject, timing.own/1000000000.0);
timingObject.put("total", timingObject, timing.total/1000000000.0);
timingObject.put("max", timingObject, timing.max/1000000000.0);
timingObject.put("calls", timingObject, timing.calls);
Method method = entry.getKey();
timingObject.put("name", timingObject, method.className == null ? method.methodName : (method.className + '.' + method.methodName));
timingsObject.add(timingObject);
}
return timingsObject;
}
if ("cpuTime".equals(key))
return cpuTime / 1000000000.0;
if ("userTime".equals(key))
return userTime / 1000000000.0;
if ("heapMemoryUsage".equals(key))
return memoryMXBean.getHeapMemoryUsage().getUsed();
if ("nonHeapMemoryUsage".equals(key))
return memoryMXBean.getNonHeapMemoryUsage().getUsed();
if ("cometClients".equals(key))
return EventStream.getConnectionCount();
if ("clients".equals(key))
return EventStream.streams.size();
if ("vm".equals(key))
return runtimeMXBean.getVmName() + " " + runtimeMXBean.getVmVendor() + " " + runtimeMXBean.getVmVersion();
long gcTime = 0;
for (GarbageCollectorMXBean gcMXBean : gcMXBeans){
gcTime += gcMXBean.getCollectionTime();
}
if ("gcTime".equals(key))
return gcTime / 1000.0;
return Scriptable.NOT_FOUND;
}
public static AliasIds.AliasHandler statusAlias = new AliasIds.AliasHandler() {
public Persistable getTarget() {
return instance;
}
};
public ObjectId getId() {
return statusAlias;
}
public Persistable getParent() {
return null;
}
Set<String> keys = new HashSet(Arrays.asList(
new String[]{"freeMemory","totalMemory","maxMemory","availableProcessors",
"uptime", "requests", "averageRequestTime", "recentAverageRequestTime",
"threadCount", "cpuTime", "userTime", "version", "methodTimings","references","maxRequestTime",
"heapMemoryUsage", "nonHeapMemoryUsage", "vm", "gcTime","cometClients", "clients"
}));
public Set<Map.Entry<String, Object>> entrySet(int options){
Map map = new HashMap();
for (String name : keys){
map.put(name, get(name));
}
return map.entrySet();
}
}
|
viktoryi/LeetCode
|
src/problems/Q260_SingleNumberIII.java
|
<reponame>viktoryi/LeetCode
package problems;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Q260_SingleNumberIII {
public static void main(String[] args) {
int[] array = new int[]{1, 2, 2, 3};
System.out.println(Arrays.toString(singleNumber(array)));
}
public static int[] singleNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
set.remove(num);
}
}
return set.stream().mapToInt(Integer::intValue).toArray();
}
}
|
luxe/CodeLang-compiler
|
source/code/utilities/bootstrap/exit/lib.cpp
|
<reponame>luxe/CodeLang-compiler
#include "lib.hpp"
#include <iostream>
void Exit_With_Error(std::string const& str){
std::cerr << str << std::endl;
exit(-1);
}
|
jadedevin13/collect
|
collect-webapp/frontend/src/ws/appWebSocket.js
|
<gh_stars>10-100
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import SockJsClient from 'react-stomp'
import Constants from '../Constants'
import EventQueue from 'model/event/EventQueue'
import { RecordEvent, RecordEventWrapper } from 'model/event/RecordEvent'
import ServiceFactory from 'services/ServiceFactory'
import { showSystemError } from 'actions/systemError'
import { clearActiveSurvey } from 'actions/activeSurvey'
import { fetchSurveySummaries } from 'actions/surveys'
import { recordLocked, recordUnlocked } from '../datamanagement/actions'
const eventsDestination = '/events'
const MESSAGE_TYPES = {
//TODO surveyUpdated: 'SURVEY_UPDATED',
surveyDeleted: 'SURVEY_DELETED',
surveyPublished: 'SURVEY_PUBLISHED',
surveyUnpublished: 'SURVEY_UNPUBLISHED',
surveysUpdated: 'SURVEYS_UPDATED',
recordLocked: 'RECORD_LOCKED',
recordUnlocked: 'RECORD_UNLOCKED',
recordUpdated: 'RECORD_UPDATED',
recordUpdateError: 'RECORD_UPDATE_ERROR',
}
const AppWebSocket = () => {
const dispatch = useDispatch()
const { survey: activeSurvey } = useSelector((state) => state.activeSurvey)
const invalidateSurveyCache = ({ surveyId }) => {
ServiceFactory.codeListService.invalidateCache({ surveyId })
if (activeSurvey?.id === surveyId) {
dispatch(clearActiveSurvey())
}
}
const messageHandlersByType = {
// TODO
// [messageTypes.surveyUpdated]: (message) => () => {
// const { surveyId } = message
// ServiceFactory.codeListService.invalidateCache({ surveyId })
// },
[MESSAGE_TYPES.surveyPublished]: (message) => () => {
const { surveyId } = message
invalidateSurveyCache({ surveyId })
},
[MESSAGE_TYPES.surveyUnpublished]: (message) => () => {
const { surveyId } = message
invalidateSurveyCache({ surveyId })
},
[MESSAGE_TYPES.surveyDeleted]: (message) => () => {
const { surveyId } = message
invalidateSurveyCache({ surveyId })
},
[MESSAGE_TYPES.surveysUpdated]: fetchSurveySummaries,
[MESSAGE_TYPES.recordLocked]: (message) => recordLocked(message.recordId, message.lockedBy),
[MESSAGE_TYPES.recordUnlocked]: (message) => recordUnlocked(message.recordId),
[MESSAGE_TYPES.recordUpdated]: (message) => () => {
const eventWrapper = new RecordEventWrapper(message.event)
EventQueue.publish(RecordEvent.TYPE, eventWrapper.event)
},
[MESSAGE_TYPES.recordUpdateError]: (content) => (dispatch) => {
dispatch(showSystemError(content))
},
}
const onMessage = (message) => {
const handler = messageHandlersByType[message.type]
dispatch(handler(message))
}
return <SockJsClient url={`${Constants.BASE_URL}ws`} topics={[eventsDestination]} onMessage={onMessage} />
}
export default AppWebSocket
|
sunnyclinches44/pegalogviewer
|
src/main/java/com/pega/gcs/logviewer/logfile/LogPattern.java
|
<reponame>sunnyclinches44/pegalogviewer
/*******************************************************************************
* Copyright (c) 2017 Pegasystems Inc. All rights reserved.
*
* Contributors:
* <NAME>
*******************************************************************************/
package com.pega.gcs.logviewer.logfile;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.logging.log4j.core.pattern.PatternFormatter;
import org.apache.logging.log4j.core.pattern.PatternParser;
public class LogPattern implements Serializable, Comparable<LogPattern> {
private static final long serialVersionUID = -3027272357446490017L;
private String name;
private String logPatternString;
private LogPattern() {
// for kryo
}
public LogPattern(String name, String logPatternString) {
super();
this.name = name;
this.logPatternString = logPatternString;
}
public String getName() {
return name;
}
public String getLogPatternString() {
return logPatternString;
}
public int getGroupCount() {
int groupCount = 0;
if ((logPatternString != null) && (!"".equals(logPatternString))) {
PatternParser patternParser = new PatternParser("Converter");
List<PatternFormatter> patternFormatterList = patternParser.parse(logPatternString);
groupCount = patternFormatterList.size();
}
return groupCount;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((logPatternString == null) ? 0 : logPatternString.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LogPattern other = (LogPattern) obj;
if (logPatternString == null) {
if (other.logPatternString != null)
return false;
} else if (!logPatternString.equals(other.logPatternString))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer displayString = new StringBuffer();
displayString.append(name);
displayString.append(" [ Group Count(" + getGroupCount() + ")]");
displayString.append(" [");
displayString.append(logPatternString);
displayString.append("]");
return displayString.toString();
}
@Override
public int compareTo(LogPattern o) {
// group count
int groupCount = getGroupCount();
int otherGroupCount = o.getGroupCount();
if (groupCount != otherGroupCount) {
// reverse order
return new Integer(otherGroupCount).compareTo(new Integer(groupCount));
}
// then pattern string
String patternString = getLogPatternString();
String otherPatternString = o.getLogPatternString();
return patternString.compareTo(otherPatternString);
}
public static Set<LogPattern> getDefaultPegaRulesLog4jPatternSet() {
TreeSet<LogPattern> defaultPegaRulesLog4jPatternSet = new TreeSet<LogPattern>();
String name;
String logPatternString;
LogPattern log4jPattern;
// 7.1.5
name = "7.x";
logPatternString = "%d [%20.20t] [%10.10X{pegathread}] [%20.20X{tenantid}] [%20.20X{app}] (%30.30c{3}) %-5p %X{stack} %X{userid} - %m%n";
log4jPattern = new LogPattern(name, logPatternString);
defaultPegaRulesLog4jPatternSet.add(log4jPattern);
// 6.3.1
name = "5.4.x";
logPatternString = "%d [%20.20t] [%10.10X{pegathread}] [%20.20X{app}] (%80.80c{3}) %-5p %X{stack} %X{userid} - %m%n";
log4jPattern = new LogPattern(name, logPatternString);
defaultPegaRulesLog4jPatternSet.add(log4jPattern);
// 5.2 SP1
name = "5.2.x";
logPatternString = "%d{ABSOLUTE} [%20.20t] (%30.30c{3}) %-5p %X{stack} %X{userid} - %m%n";
log4jPattern = new LogPattern(name, logPatternString);
defaultPegaRulesLog4jPatternSet.add(log4jPattern);
// UBS
name = "UBS";
logPatternString = "%d{dd HH:mm:ss,SSS} [%20.20t] [%10.10X{pegathread}] [%20.20X{app}] (%80.80c{3}) %-5p %X{stack} %X{userid} - %m%n";
log4jPattern = new LogPattern(name, logPatternString);
defaultPegaRulesLog4jPatternSet.add(log4jPattern);
// CTI
name = "CTI";
logPatternString = "%d [%20.20t] (%30.30c{3}) %-5p %X{stack} %X{userid} - %m%n";
log4jPattern = new LogPattern(name, logPatternString);
defaultPegaRulesLog4jPatternSet.add(log4jPattern);
return defaultPegaRulesLog4jPatternSet;
}
}
|
ali5ter/dispatch
|
pkg/dispatchserver/entitystore.go
|
///////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
///////////////////////////////////////////////////////////////////////
package dispatchserver
import (
log "github.com/sirupsen/logrus"
entitystore "github.com/vmware/dispatch/pkg/entity-store"
)
func entityStore(config *serverConfig) entitystore.EntityStore {
store, err := entitystore.NewFromBackend(
entitystore.BackendConfig{
Backend: config.DatabaseBackend,
Address: config.DatabaseAddress,
Bucket: config.DatabaseBucket,
Username: config.DatabaseUsername,
Password: config.DatabasePassword,
})
if err != nil {
log.Fatalln(err)
}
return store
}
|
178inaba/stripe-go
|
radar_valuelistitem.go
|
//
//
// File generated from our OpenAPI spec
//
//
package stripe
// Returns a list of ValueListItem objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first.
type RadarValueListItemListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
// Identifier for the parent value list this item belongs to.
RadarValueList *string `form:"value_list"`
// Return items belonging to the parent list whose value matches the specified value (using an "is like" match).
Value *string `form:"value"`
}
// Creates a new ValueListItem object, which is added to the specified parent value list.
type RadarValueListItemParams struct {
Params `form:"*"`
// The identifier of the value list which the created item will be added to.
RadarValueList *string `form:"value_list"`
// The value of the item (whose type must match the type of the parent value list).
Value *string `form:"value"`
}
// Value list items allow you to add specific values to a given Radar value list, which can then be used in rules.
//
// Related guide: [Managing List Items](https://stripe.com/docs/radar/lists#managing-list-items).
type RadarValueListItem struct {
APIResource
// Time at which the object was created. Measured in seconds since the Unix epoch.
Created int64 `json:"created"`
// The name or email address of the user who added this item to the value list.
CreatedBy string `json:"created_by"`
Deleted bool `json:"deleted"`
// Unique identifier for the object.
ID string `json:"id"`
// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
Livemode bool `json:"livemode"`
Name string `json:"name"`
// String representing the object's type. Objects of the same type share the same value.
Object string `json:"object"`
// The identifier of the value list this item belongs to.
RadarValueList string `json:"value_list"`
// The value of the item.
Value string `json:"value"`
}
// RadarValueListItemList is a list of ValueListItems as retrieved from a list endpoint.
type RadarValueListItemList struct {
APIResource
ListMeta
Data []*RadarValueListItem `json:"data"`
}
|
OpenSpace-VisLink/sandbox
|
src/sandbox/base/Transform.h
|
<filename>src/sandbox/base/Transform.h<gh_stars>0
#ifndef SANDBOX_BASE_TRANSFORM_H_
#define SANDBOX_BASE_TRANSFORM_H_
#include "glm/glm.hpp"
#include "sandbox/graphics/RenderObject.h"
#include <iostream>
namespace sandbox {
class TransformState : public StateContainerItem {
public:
TransformState() {
calculateTransform = false;
transform.set(glm::mat4(1.0f));
}
virtual ~TransformState() {}
StateContainerItemStack<glm::mat4>& getTransform() { return transform; }
static TransformState& get(const GraphicsContext& context) { return context.getRenderState()->getItem<TransformState>(); }
bool calculateTransform;
private:
StateContainerItemStack<glm::mat4> transform;
};
class Transform : public RenderObject {
public:
Transform();
Transform(const glm::mat4& transform);
virtual ~Transform();
const glm::mat4& getTransform() const { return transform; }
void setTransform(const glm::mat4& transform) { this->transform = transform; getEntity().incrementVersion(); }
glm::vec3 getLocation() const;
virtual void startRender(const GraphicsContext& context) {
TransformState& state = TransformState::get(context);
if (state.calculateTransform) {
state.getTransform().push(state.getTransform().get()*transform);
//std::cout << "begin Transform " << std::endl;
}
}
virtual void finishRender(const GraphicsContext& context) {
TransformState& state = TransformState::get(context);
if (state.calculateTransform) {
TransformState::get(context).getTransform().pop();
//std::cout << "end Transform " << std::endl;
}
}
private:
glm::mat4 transform;
};
}
#endif
|
156248605/backend
|
src/main/java/com/elex/oa/entity/project/WeeklyPlan.java
|
package com.elex.oa.entity.project;
public class WeeklyPlan { //项目周报
private int id;
private String projectCode; //项目编号
private String startDate; //实施启动时间
private String endDate; //预计完成时间
private String timeSchedule; //时间进度
private String fulfillment; //完成进度
private String punctuality; //是否按期
private String projectPhase; //项目阶段
private String completion; //完成概况
private String nextPlan; //下周计划
private String risk; //风险提醒
private String fillDate; //填写日期
private String projectManager; //项目经理
private String departmentManager; //部门经理
//private String leaderShip; //分管领导
public WeeklyPlan() {
}
public WeeklyPlan(int id, String projectCode, String startDate, String endDate, String timeSchedule, String fulfillment, String punctuality, String projectPhase, String completion, String nextPlan, String risk, String fillDate, String projectManager, String departmentManager) {
this.id = id;
this.projectCode = projectCode;
this.startDate = startDate;
this.endDate = endDate;
this.timeSchedule = timeSchedule;
this.fulfillment = fulfillment;
this.punctuality = punctuality;
this.projectPhase = projectPhase;
this.completion = completion;
this.nextPlan = nextPlan;
this.risk = risk;
this.fillDate = fillDate;
this.projectManager = projectManager;
this.departmentManager = departmentManager;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getTimeSchedule() {
return timeSchedule;
}
public void setTimeSchedule(String timeSchedule) {
this.timeSchedule = timeSchedule;
}
public String getFulfillment() {
return fulfillment;
}
public void setFulfillment(String fulfillment) {
this.fulfillment = fulfillment;
}
public String getPunctuality() {
return punctuality;
}
public void setPunctuality(String punctuality) {
this.punctuality = punctuality;
}
public String getProjectPhase() {
return projectPhase;
}
public void setProjectPhase(String projectPhase) {
this.projectPhase = projectPhase;
}
public String getCompletion() {
return completion;
}
public void setCompletion(String completion) {
this.completion = completion;
}
public String getNextPlan() {
return nextPlan;
}
public void setNextPlan(String nextPlan) {
this.nextPlan = nextPlan;
}
public String getRisk() {
return risk;
}
public void setRisk(String risk) {
this.risk = risk;
}
public String getFillDate() {
return fillDate;
}
public void setFillDate(String fillDate) {
this.fillDate = fillDate;
}
public String getProjectManager() {
return projectManager;
}
public void setProjectManager(String projectManager) {
this.projectManager = projectManager;
}
public String getDepartmentManager() {
return departmentManager;
}
public void setDepartmentManager(String departmentManager) {
this.departmentManager = departmentManager;
}
@Override
public String toString() {
return "WeeklyPlan{" +
"id=" + id +
", projectCode='" + projectCode + '\'' +
", startDate='" + startDate + '\'' +
", endDate='" + endDate + '\'' +
", timeSchedule='" + timeSchedule + '\'' +
", fulfillment='" + fulfillment + '\'' +
", punctuality='" + punctuality + '\'' +
", projectPhase='" + projectPhase + '\'' +
", completion='" + completion + '\'' +
", nextPlan='" + nextPlan + '\'' +
", risk='" + risk + '\'' +
", fillDate='" + fillDate + '\'' +
", projectManager='" + projectManager + '\'' +
", departmentManager='" + departmentManager + '\'' +
'}';
}
}
|
Briaares/Omegaup
|
frontend/www/js/lang.en.js
|
OmegaUp.T = {
aboutToStart: "You are about to start the contest. Once you click on start your time will begin.",
adminAdded: "Admin successfully added",
aliasInUse: "alias already exists. Please choose a different alias.",
apiNotFound: "Requested API endpoint not found.",
arenaAdminManageProblem: "Manage problem",
arenaCommonCode: "Code",
arenaCommonMemoryLimit: "Memory limit",
arenaCommonNewClarification: "New clarification",
arenaCommonOrUploadFile: "Or upload it:",
arenaCommonOverallWallTimeLimit: "Time limit (total)",
arenaCommonPasteTheCode: "Paste the source code here:",
arenaCommonTimeLimit: "Time limit (case)",
arenaContestOrganizer: "Organizer",
arenaContestWindowLength: "Time to solve all problems",
arenaCurrentContests: "Current contests",
arenaOldContests: "Past contents",
arenaPageIntroduction: "To join a live contest, click the contest title and follow the instructions. All past contest have a Practice mode you can use to continue solving its tasks.",
arenaPageRecommendedContestsText: "To show your contest in the Recommended Contest list, contact <EMAIL>.",
arenaPageTitle: "omegaUp Arena",
arenaPracticeEndtime: "End time",
arenaPracticeScoreboardCutoff: "Scoreboard cutoff time",
arenaPracticeStartTime: "Start time",
arenaRecommendedCurrentContests: "Recommended current contests",
arenaRecommendedOldContests: "Recommended past contents",
arenaRunSubmitFilename: "Filename your code will be saved as: ",
arenaRunSubmitPaste: "Paste your program's code here",
arenaRunSubmitUpload: "Or upload the file",
cannotAddProb: "Cannot add problem. You are not the contest director.",
clarificationEmailBody: "<p>Howdy!</p><p>The user <strong><a href=\"https://omegaup.com/profile/%(user_name)\">%(user_name)</a></strong> has requested a clarification for the problem <strong><a href=\"https://omegaup.com/arena/problem/%(problem_alias)\">%(problem_name)</a></strong>:</p><p><blockquote><p>%(clarification_body)</p></blockquote><p>To answer it, please visit the following link: <a href=\"%(url)\">%(url)</a>.</p><p>Thanks!,<br/>omegaUp</p>",
clarificationEmailSubject: "[omegaUp] New clarification for problem %(problem_name)",
clarificationNotFound: "Clarification not found",
coderOfTheMonthFullList: "See full list",
codersOfTheMonth: "Coders of the Month",
codersOfTheMonthDate: "Date",
codersOfTheMonthUser: "Username",
contestAddgroupAddGroup: "Add group",
contestAddproblemContestOrder: "Contest order",
contestAddproblemProblemName: "Problem",
contestAddproblemProblemPoints: "Points this problem is worth",
contestAddproblemProblemRemove: "Remove",
contestAddproblemRegisteredProblems: "Problems in this contest",
contestAddproblemTooManyProblems: "This contest has too many problems, so it is not possible to add a new one",
contestAdduserAddContestant: "Add contestant",
contestAdduserAddUser: "Add user",
contestAdduserRegisteredUserDelete: "Remove",
contestAdduserRegisteredUserTime: "First access time",
contestAdduserRegisteredUserUsername: "Username",
contestAdduserRegisteredUsers: "Registered users",
contestDetailsContestDetails: "Contest users",
contestDetailsGoToContest: "Go to contest",
contestDetailsMax: "Max",
contestDetailsNewProblem: "New problem",
contestDetailsPartialScore: "Partial Score",
contestDetailsProblemsInContest: "Problems in contest",
contestDetailsScoreboard: "Scoreboard",
contestDetailsSubmissionsGap: "Submissions Gap",
contestDetailsSubmit: "Submit problem",
contestDetailsSum: "Sum",
contestDetailsValidator: "Validator",
contestDetailsWindowLength: "Window Length",
contestDetailsYes: "Yes",
contestEdit: "Edit contest",
contestEditAddProblems: "Add problems",
contestEditContestEdited: "Your contest has been edited",
contestEditGoToContest: "View contest",
contestEditRegisteredAdminDelete: "Remove",
contestEditRegisteredAdminRole: "Role",
contestEditRegisteredAdminUsername: "Username",
contestEditRegisteredGroupAdminName: "Group",
contestEditTagDelete: "Delete",
contestEditTagName: "Name",
contestEditTagPublic: "Public",
contestJoin: "Join contest",
contestListAddAdmins: "Add admins",
contestListAddContestants: "Add contestants",
contestListSubmissions: "Submissions",
contestNew: "New contest",
contestNewCreatedContestSuccesfully: "Your contest hast been created!",
contestNewForm: "IOI Style",
contestNewFormByContests: "Minutes since contest started",
contestNewFormByProblem: "Minutes since problem opened",
contestNewFormByRuntime: "Milliseconds of program runtime",
contestNewFormConacupStyle: " CONACUP style",
contestNewFormContestToEdit: "Contest to edit",
contestNewFormDescription: "Contest description",
contestNewFormDifferentStarts: "Different starts",
contestNewFormDifferentStartsDesc: "Si está activo, indica el tiempo en minutos que tiene el usuario para concursar y envíar soluciones a partir de que entra al concurso en la arena (estilo USACO/Preselectivo IOI). Si Inicios Diferentes está desactivado, entonces el concursante tendrá todo el tiempo entre la hora de inicio y la hora de fin para concursar.",
contestNewFormEndDate: "End date",
contestNewFormEndDateDesc: "The time and date (in local time) in which the contest will end.",
contestNewFormImmediateFeedbackDesc: "Give immediate feedback to user about its problem",
contestNewFormNoPenalty: "No penalty",
contestNewFormPenaltyDesc: "Entero indicando el número de minutos con que se penaliza por enviar una respuesta incorrecta.",
contestNewFormPenaltyType: "Penalty type",
contestNewFormPenaltyTypeDesc: "Indicates how the submission penalty is calculated: minutes since the beginning of the contest, minutes since the problem was opened, or program execution time (milliseconds).",
contestNewFormPintDecrementFactor: "Factor de Decrecimiento de Puntaje",
contestNewFormPintDecrementFactorDesc: "Un número entre 0 y 1 inclusive. Si este número es distinto de cero, el puntaje que se obtiene al resolver correctamente un problema decae conforme pasa el tiempo. El valor del puntaje estará dado por (1 - points_decay_factor) + points_decay_factor * TT^2 / (10 * PT^2 + TT^2), donde PT es el penalty en minutos del envío y TT el tiempo total del concurso, en minutos.",
contestNewFormPublic: "Public",
contestNewFormPublicDesc: "Show contest in public listing. You have to add a problem to the contest before marking it as public.",
contestNewFormRegistration: "Registration",
contestNewFormRegistrationDesc: "Users need to register to participate in this contest.",
contestNewFormScheduleContest: "Schedule contest",
contestNewFormScoreboardAtContestEnd: "Scoreboard al finalizar el concurso",
contestNewFormScoreboardAtEnd: "Scoreboard at the end of contest",
contestNewFormScoreboardAtEndDesc: "Mostrar automáticamente el scoreboard completo al finalizar el concurso.",
contestNewFormScoreboardTimePercent: "¿Cuánto tiempo se mostrará el Scoreboard? (%)",
contestNewFormScoreboardTimePercentDesc: "Entero del 0 al 100, indicando el porcentaje de tiempo que el scoreboard será visible.",
contestNewFormShortTitle_alias_: "Short title (alias)",
contestNewFormShortTitle_alias_Desc: "El título corto se usa para construir la URL del concurso (ejemplos: ANPA2010, CONACUP2012, OMI2013, etc..). No puede contener espacios",
contestNewFormStartDate: "Start date",
contestNewFormStartDateDesc: "The time and date (in local time) in which the contest will begin",
contestNewFormSubmissionsSeparation: "Submission time window",
contestNewFormSubmissionsSeparationDesc: "Tiempo mínimo en minutos que debe de esperar un concursante despues de realizar un envío para hacer otro.",
contestNewFormUpdateContest: "Update contest",
contestNewInvalidStartTime: "The start time must be before the end time",
contestNewPublicInfoNotice: "To make a public contest, add a problem first and then mark it as public in Edit Contest.",
contestNotExist: "Contest provided does not exist",
contestNotFound: "Contest not found",
contestNotRegistered: "You are not registered for this contest.",
contestNotStarted: "Contest has not started yet.",
contestPrintableVersion: "Printable version",
contestPublicRequiresProblem: "Public contests require at least one problem. Please add a problem to this contest before marking it as public.",
contestRules: "Contest rules and details",
contestSNotFound: "Contest %s not found",
contestScoreboardAdminLink: "Admin Scoreboard link",
contestScoreboardLink: "Scoreboard link",
contestTimeExpired: "Contest time has expired or not started yet.",
contestWillBeginIn: "This contest will begin in ",
contestsCreateNew: "Create a new contest",
contestsJoinScoreboards: "Merge scoreboards",
contestsTablePublic: "Public",
countryNotFound: "Country not found",
createSchoolFailed: "School creation failed.",
currentStatus: "Current state",
editFieldRequired: "Missing required field",
emailInUse: "email already exists",
emailNotVerified: "Your email is not verified yet. Please look for the verification email in your inbox and spam folder. If you still have problems, please contact <EMAIL> for support.",
enterContest: "Enter contest",
errorEc2RunInstances: "Error executing ec2-run-instances. Please check log for details",
errorEc2TerminateInstance: "Error executing ec2-terminate-instances. Please check log for details",
errorWhileSendingMail: "There was an error sending the verification email. Please try again later or contact <EMAIL> for support. Your email is not verified yet.",
forSelectedItems: "For selected items",
frontPageBlogPosts: "Latest blog posts",
frontPageCreateContestButton: "Create your own contest!",
frontPageDescription: "omegaUp is a web project aimed at raising the level of competitiveness of software developers through problem solving with a competitive aproach and fun at the same time.",
frontPageDevelopers: "Developers",
frontPageFooter: "is a place for getting better at software development.",
frontPageIntroduction: "First time using omegaUp?",
frontPageIntroductionButton: "Read the tutorial",
frontPageLoading: "Loading...",
frontPageMaterial: "Suggested book",
frontPageNextContests: "Upcoming contests",
frontPageWelcome: "Welcome!",
frontPageWelcomeToOmegaup: "Welcome to OmegaUp!",
generalError: "Oops. I've encountered an internal error. Please try again.",
groupEditMembers: "Members",
groupEditScoreboards: "Scoreboards",
groupEditScoreboardsAdd: "Create scoreboard",
groupEditScoreboardsAddContest: "Add contest",
groupEditScoreboardsContests: "Contests",
groupNewFormCreateGroup: "Create group",
groupNewFormDescription: "Group description",
groupNewFormOnlyAC: "Only count ACs",
groupNewFormUpdateGroup: "Save group",
groupNewFormWeight: "Score weight",
groupsCreateNew: "New group",
index: "Coder of the month",
invalidContestType: "Invalid contest_type",
invalidParameters: "Invalid parameters.",
invalidResetToken: "Invalid reset token.",
invalidScoreboardUrl: "Invalid scoreboard url.",
invalidStatementType: "Invalid statement type",
invalidUser: "Invalid user.",
lastUpdate: "Last update",
libinteractiveIdlFilename: ".idl filename",
libinteractiveIdlFilenameHelp: "The name of the .idl file (without extension). Must be between 1 and 32 alphanumeric characters.",
libinteractiveLanguage: "Language",
libinteractiveOs: "Operating System",
locale: "en",
loginDisabled: "Your user is too old and for your security it has been disabled. Please contact <EMAIL> to login again.",
loginEmail: "E-mail",
loginEmailUsername: "E-mail or user",
loginFederated: "Login using these sites",
loginFederatedFailed: "Login using the external party failed. Did you reject access?",
loginHeader: "Login to OmegaUp",
loginLogIn: "Log in",
loginNative: "OmegaUp account",
loginPassword: "Password",
loginPasswordNotEqual: "<PASSWORD>",
loginPasswordTooShort: "<PASSWORD>",
loginRecover: "Forgot your password?",
loginRepeatPassword: "<PASSWORD>",
loginRequired: "You need to login to perform that action",
loginSignUp: "Register",
loginSignupHeader: "Create an omegaUp account, quick and easy!",
loginWithFacebook: "Login with Facebook",
loginWithGoogle: "Log in with Google",
mailInUse: "This mail is already in use. Try again.",
makePrivate: "Make private",
makePublic: "Make public",
messageMakeYourContestsPublic: "You have private contests that have already ended. Please consider make them public to contribute to the community.",
messageMakeYourProblemsPublic: "You have private problems that have already been used. Please consider make them public to contribute to the community.",
mustLoginToJoinContest: "You must login to join this contest",
mustProvideUserIdEmailOrUsername: "You must provide either one of the following: user_id, email or username",
mustRegisterToJoinContest: "You must register to join this contest",
mustWaitNToSubmit: "You have to wait %n between submissions",
myproblemsListAddContests: "Add a contest",
myproblemsListCreateProblem: "Create a problem",
myproblemsListMyProblems: "My Problems",
nativeSignupDisabled: "Direct signup has been temporarily disabled. Please sign up through Google or Facebook.",
navArena: "Arena",
navBlog: "Blog",
navContests: "Concursos",
navDevelopers: "Developers",
navGroups: "Groups",
navHelp: "Help",
navLogIn: "Log in",
navLogOut: "Log out",
navMyContests: "My contests",
navMyGroups: "My groups",
navMyProblems: "My problems",
navQuestions: "Questions",
navRanking: "Rank",
navRecent: "Latest activity",
navViewProfile: "My profile",
noCoders: "No coders.",
notRegisteredInContest: "You are not registered to this contest.",
oldPassword: "<PASSWORD>",
omegaupTitleAdminChangePassword: "<PASSWORD>",
omegaupTitleAdminIndex: "AdminIndex",
omegaupTitleAdminPanel: "Admin Panel",
omegaupTitleAdminUsers: "AdminUsers",
omegaupTitleApi: "Api",
omegaupTitleCodersofthemonth: "Codersofthemonth",
omegaupTitleContest: "Contest",
omegaupTitleContestAddAdmin: "Add admin",
omegaupTitleContestAddGroupAdmin: "Add admin group",
omegaupTitleContestAddproblem: "ContestAddproblem",
omegaupTitleContestAdduser: "ContestAdduser",
omegaupTitleContestDetails: "ContestDetails",
omegaupTitleContestEdit: "ContestEdit",
omegaupTitleContestNew: "ContestNew",
omegaupTitleContestStats: "ContestStats",
omegaupTitleGroups: "Groups",
omegaupTitleGroupsEdit: "Edit group",
omegaupTitleGroupsNew: "New group",
omegaupTitleGroupsScoreboardEdit: "Edit scoreboard",
omegaupTitleIndex: "Index",
omegaupTitleLogin: "Login",
omegaupTitleMyProblemsList: "MyProblemsList",
omegaupTitleProblemEdit: "ProblemEdit",
omegaupTitleProblemNew: "ProblemNew",
omegaupTitleProblemStats: "ProblemStats",
omegaupTitleProblems: "Problems",
omegaupTitleProfile: "Profile",
omegaupTitleRank: "Rank",
omegaupTitleRedaccion: "Redaccion",
omegaupTitleScoreboardmerge: "Scoreboardmerge",
openInKarelJs: "You can use karel.js to solve this problem",
parameterEmpty: "Empty parameter",
parameterInvalid: "Invalid parameter",
parameterInvalidAlias: "Parameter can only contain letters, digits, and _",
parameterNotANumber: "Parameter must be a number",
parameterNotFound: "Parameter value not found",
parameterNotInExpectedSet: "Value (%(bad_elements)) not in expected set (%(expected_set))",
parameterNumberTooLarge: "Parameter is larger than the maximum value of %(upper_bound)",
parameterNumberTooSmall: "Parameter is smaller than the minimum value of %(lower_bound)",
parameterStringTooLong: "Parameter is longer than %(max_length) characters",
parameterStringTooShort: "Parameter is shorter than %(min_length) characters",
parameterUsernameInUse: "Username already in use",
passwordMismatch: "Password mismatch.",
passwordResetMinWait: "You should wait some minutes before another request.",
passwordResetPassword: "<PASSWORD>",
passwordResetPasswordConfirmation: "<PASSWORD>",
passwordResetRequestSuccess: "Instructions have been sent to your email.",
passwordResetRequestTitle: "I forgot my password",
passwordResetResetExpired: "The time to reset your password has expired.",
passwordResetResetSuccess: "Your password has been updated.",
passwordResetResetTitle: "Reset password",
pendingRegistrations: "Pending requests",
privacyPolicyNotice: "By clicking on Register you are accepting the site <a href='http://blog.omegaup.com/privacy-policy/'>Use and Privacy Policy</a>.",
privateUsers: "private_users",
privateUsersContainsInvalidUser: "private_users contains a user that doesn't exists",
probAliasAndContestAliasInvalid: "problem_alias and contest_alias combination is invalid.",
problemDeployerCorruptZip: "Unable to open zipped file. It is either corrupt or didn't upload properly.",
problemDeployerEmptyStatement: "Statements file \"%(file)\" is empty",
problemDeployerExceededZipSizeLimit: "Extracted zip size (%(size)) over max allowed (%(max_size)). Rejecting.",
problemDeployerFailed: "Unable to deploy problem",
problemDeployerIdlMissing: "Interactive problem is missing an .idl file",
problemDeployerInteractiveSampleMissing: "The sample input 'interactive/examples/sample.in' is missing",
problemDeployerLibinteractiveValidationError: "Interactive problem is invalid",
problemDeployerMissingFromTestplan: "Case \"%(file)\" missing in testplan",
problemDeployerNoCases: "No cases found",
problemDeployerNoStatements: "No statements found",
problemDeployerOutMissing: ".out not found for case",
problemDeployerSlowRejected: "Problem would run for more than 5 minutes in case of TLE. Rejected.",
problemDeployerTestplanCaseMissing: "Case in testplan missing from case list \"%(file)\"",
problemDeployerTestplanEmpty: "No cases found in testplan or format not recognized. PPlease make sure to save the file in ASCII or UTF-8.",
problemDeployerValidatorRequired: "Problem requested custom validator but has no validator.",
problemDeprecated: "Problem is deprecated",
problemEditAddAdmin: "Administrators",
problemEditAddGroupAdmin: "Administrator Groups",
problemEditAddTags: "Tags",
problemEditCommitMessage: "Update description",
problemEditEditMarkdown: "Edit statement",
problemEditEditProblem: "Edit problem",
problemEditEmailClarifications: "Send clarifications through email",
problemEditFormAppearsAsPublic: "Appear in the public listing",
problemEditFormCreateProblem: "Create problem",
problemEditFormCustom: "Custom validator (validator.$lang$)",
problemEditFormFile: "File",
problemEditFormHelp: "Help",
problemEditFormHowToWriteProblems: "How to write problems for omegaUp",
problemEditFormLanguages: "Languages",
problemEditFormLiteral: "Interpret stdout as score",
problemEditFormNumericTokensWithTolerance: "Numeric tokens with tolerance",
problemEditFormTokenByToken: "Token by Token",
problemEditFormTokenCaseless: "Token by Token, ignoring upper/lowercase",
problemEditFormUpdateMarkdown: "Update statement",
problemEditFormUpdateProblem: "Update problem",
problemEditFormValidatorType: "Validador type",
problemEditGoToProblem: "Go to problem",
problemEditSlowWarning: "<strong>Warning</strong>: This problem will be judged in the slow queue since TLE runs might finish in more than 30s (number of cases * time limit in seconds rounded up). Problems in the slow queue might take up to several minutes in being judged, to avoid slowing the rest of the system. If you want this problem to not be in the slow queue, remove test cases or reduce the time limit.",
problemEditStackLimit: "Stack limit (bytes)",
problemExists: "Another problem with that name already exists. Choose another name.",
problemIsNotPublic: "The problem is not public.",
problemIsPrivate: "Problem is marked as private.",
problemNew: "Create problem",
problemNotFound: "Problem not found",
problemNotFoundInContest: "Problem not found in contest given",
problemNotInContest: "Problem does not exists in the contest given.",
problemProvidedDoesNotExist: "Problem provided does not exist",
problemTitleExists: "Problem title already exists. Please try a different one.",
profile: "Name",
profileContests: "Contests results",
profileContestsTablePlace: "Place",
profileCountry: "Country",
profileEdit: "Edit profile",
profileEmail: "Email",
profileGraduationDate: "Graduation date",
profileInfo: "Information",
profileSchool: "School",
profileSolvedProblems: "Solved problems",
profileState: "State",
profileStatistics: "Stats",
profileUsername: "Username",
publicContestMustHaveProb: "Public contest must have at least 1 problem added",
publish: "Publish",
rankHeaderPostCount: "users with the most solved problems",
rankHeaderPreCount: "Top",
rankScore: "Score",
rankSolved: "Solved problems",
rankViewFull: "View full rank",
registerForContest: "Register for contest",
registrationPending: "Your request to join this contest is pending approval from the contest admin.",
requestDate: "Date of request",
runNotEvenOpened: "You must open the problem before trying to submit a solution.",
runNotFound: "Run not found",
runNotInsideContest: "Contest time has expired or not started yet.",
runNotRegistered: "You are not registered to this contest.",
runProblemNotPublic: "The problem is not public.",
runWaitGap: "You have to wait between consecutive submissions.",
schoolNotFound: "School not found",
schoolToBeAdded: "Your school has not been registered in omegaUp. It will be added when you save your changes.",
scoreboardmerge: "Merge scorboard",
selectAction: "Select action",
sortByMyScore: "Sort by my score",
sortByPointsForRank: "Sort by points for ranking",
sortByRatio: "Sort by ratio",
sortByRuns: "Sort by runs",
sortBySolved: "Sort by solved",
spanishStatementMissing: "The problem must contain a problem statement in spanish.",
startContest: "Start contest",
startEndMismatch: "start_time cannot be after finish_time",
stateNotFound: "State not found",
statementLanguage: "Language",
statementLanguageEn: "English",
statementLanguageEs: "Spanish",
statementLanguagePt: "Portuguese",
statementNotFound: "Problem statement not found",
status: "Update your email here.",
submittingUnOpenedProblem: "User is submitting a run and he has not even opened the problem",
successfulOperation: "Success",
unableToVerifyCaptcha: "We failed to verify the captcha. Please reload the page and try again.",
unverifiedUser: "Unverified user.",
userEditBachelors: "Bachelors",
userEditBirthDate: "Birth date",
userEditChangePassword: "<PASSWORD>",
userEditChangePasswordNewPassword: "<PASSWORD>",
userEditChangePasswordOldPassword: "<PASSWORD>",
userEditChangePasswordRepeatNewPassword: "<PASSWORD>",
userEditCountry: "Country",
userEditDoctorate: "Doctorate",
userEditEditProfile: "Edit your profile",
userEditElementary: "Elementary",
userEditGraduationDate: "Graduation date",
userEditHighSchool: "High school",
userEditMasters: "Masters",
userEditMiddleSchool: "Middle school",
userEditName: "Name",
userEditProfileImage: "Profile image",
userEditSchool: "School",
userEditSchoolGrade: "School grade",
userEditState: "State",
userEditSuccess: "Profile successfully updated",
userEmailEditEditMainEmail: "update your main email",
userEmailEditEmail: "Email",
userEmailEditSaving: "Saving",
userNotAllowed: "User is not allowed to perform action",
userNotExist: "User does not exist",
userNotInListOfRequests: "The user is not pending request to join",
userOrMailNotFound: "Username or email not found",
usernameInUse: "Username already exists.",
usernameOrPassIsWrong: "Username or password is wrong. Please check your credentials.",
verdictAC: "Accepted",
verdictCE: "Compilation error",
verdictFO: "Runtime error (restricted function)",
verdictJE: "Judge error (do not re-submit)",
verdictML: "Memory limit exceeded",
verdictMLE: "Memory limit exceeded",
verdictOL: "Wrong answer (output limit exceeded)",
verdictOLE: "Wrong answer (output limit exceeded)",
verdictPA: "Partially accepted",
verdictRE: "Runtime error",
verdictRFE: "Runtime error (restricted function)",
verdictRTE: "Runtime error",
verdictTLE: "Time limit exceeded",
verdictTO: "Time limit exceeded",
verdictWA: "Wrong Answer",
verifiationIdInvalid: "Verification id is invalid.",
verificationIdInvalid: "The provided verification information is not valid.",
wordAccepted: "Accepted",
wordsAccepted: "Accepted",
wordsAddMember: "Add member",
wordsAddProblem: "Add problem",
wordsAddTag: "Add Tag",
wordsAdmin: "Admin",
wordsAlias: "Alias",
wordsAll: "All",
wordsAnswer: "Answer",
wordsAuthor: "Author",
wordsBestSolvers: "Best accepted solvers",
wordsBy: "by",
wordsCase: "Case",
wordsCases: "Cases",
wordsClarifications: "Clarification",
wordsCompilerOutput: "Compiler output",
wordsContest: "Contest",
wordsContests: "Contests",
wordsDenied: "Denied",
wordsDescription: "Description",
wordsDetails: "Details",
wordsDownload: "Download",
wordsDownloadDetails: "Download .zip with outputs",
wordsDownloadOutput: "Download output",
wordsEdit: "Edit",
wordsEndTime: "End",
wordsExtraWallTime: "Extra time for libinteractive",
wordsExtraWallTimeMs: "Extra time for libinteractive (ms)",
wordsFeedback: "Feedback",
wordsGroup: "Group",
wordsGroupAdmin: "Admin group",
wordsGroups: "Groups",
wordsID: "ID",
wordsJudgedBy: "Judged by",
wordsJustOutput: "Just output",
wordsKeyword: "Keyword",
wordsLanguage: "Language",
wordsLiveStatistics: "Live statistics",
wordsLogs: "Logs",
wordsMember: "Member",
wordsMemory: "Memory",
wordsMemoryLimit: "Memory limit",
wordsMessage: "Message",
wordsMinutes: "minutes",
wordsMode: "Mode",
wordsModeAsc: "Ascending",
wordsModeDesc: "Descending",
wordsMyScore: "My score",
wordsName: "Name",
wordsNewClarification: "New clarification",
wordsNewSubmissions: "New submission",
wordsNextPage: "Next page",
wordsNo: "No",
wordsOrderBy: "Order by",
wordsOverallWallTimeLimit: "Time limit (total)",
wordsPartial: "Partial",
wordsPenalty: "Penalty",
wordsPending: "Pending",
wordsPercentage: "Percentage",
wordsPoints: "Points",
wordsPointsForRank: "Points for ranking",
wordsPointsForRankTooltip: "These points respresent the actual value of this problem. Solving it will decrease its value. For details follow this link.",
wordsPractice: "Practice",
wordsPrevPage: "Previous page",
wordsPrivate: "Private",
wordsProblem: "Problem",
wordsProblems: "Problems",
wordsProblemsetter: "Uploaded by",
wordsPublic: "Public",
wordsRanking: "Ranking",
wordsRatio: "Ratio",
wordsRejudge: "Rejudge",
wordsReset: "OmegaUp: Reset password.",
wordsResetMessage: "Click the following link to reset your password: <a href='[link]'>[link]</a><br><br>If you didn't request this operation please do not click the link and make sure your account is safe.",
wordsResult: "Answer",
wordsRuns: "Submissions",
wordsRuntime: "Runtime",
wordsSaveChanges: "Save changes",
wordsSearch: "Search",
wordsSend: "Send",
wordsSource: "Source",
wordsStartTime: "Start",
wordsStatistics: "Statistics",
wordsStatus: "Status",
wordsSubmissions: "Submissions",
wordsSummary: "Summary",
wordsTags: "Tags",
wordsTime: "Submitted",
wordsTimeLimit: "Time limit (case)",
wordsTimeToSolveProblems: "Tiempo para resolver los problemas",
wordsTitle: "Title",
wordsTotal: "Total",
wordsUser: "User",
wordsValidator: "Validator",
wordsVerdict: "Verdict",
wordsYes: "Yes",
youMustOpenBeforeSubmit: "You must open the problem before trying to submit a solution.",
};
|
darkbreed/peak
|
node_modules/wtf_wikipedia/tests/unit_tests.js
|
'use strict';
var test = require('tape');
var redirects = require('../src/parse/parse_redirects');
var parse_line = require('../src/parse/parse_line');
var parse_categories = require('../src/parse/parse_categories');
var cleanup_misc = require('../src/parse/cleanup_misc');
var parse_image = require('../src/parse/parse_image');
var sentence_parser = require('../src/lib/sentence_parser');
var kill_xml = require('../src/parse/kill_xml');
test('sentence parser', (t) => {
[
['Tony is nice. He lives in Japan.', 2],
['I like that Color', 1],
['Soviet bonds to be sold in the U.S. market. Everyone wins.', 2],
['Hi there Dr. Joe, the price is 4.59 for N.A.S.A. Ph.Ds. I hope that\'s fine, etc. and you can attend Feb. 8th. Bye', 3],
['Mount Sinai Hospital, [[St. Michaels Hospital (Toronto)|St. Michaels Hospital]], North York', 1],
['he said ... oh yeah. I did', 2],
['32 C', 1],
['dom, kon. XIX w.', 2],
['a staged reenactment of [[Perry v. Brown]] world', 1],
].forEach((a) => {
let s = sentence_parser(a[0]);
let msg = a[1] + ' sentences - "' + a[0] + '"';
t.equal(s.length, a[1], msg);
});
t.end();
});
test('misc cleanup', (t) => {
[
['hi [[as:Plancton]] there', 'hi there'],
['hello <br/> world', 'hello world']
].forEach((a) => {
let s = cleanup_misc(a[0]);
t.equal(s, a[1]);
});
t.end();
});
test('redirects', t => {
[
['#REDIRECT[[<NAME>]]', '<NAME>'],
['#REDIRECT [[<NAME>]]', '<NAME>'],
['#REDIRECT [[<NAME>]] ', '<NAME>'],
['#redirect [[<NAME>]] ', '<NAME>'],
['#redirect [[<NAME>#funfun]] ', '<NAME>'],
['#přesměruj [[<NAME>#funfun]] ', '<NAME>'],
['#تغییر_مسیر [[Farming]] ', 'Farming']
].forEach((a) => {
let o = redirects.parse_redirect(a[0]);
var msg = '\'' + a[0] + '\' -> \'' + o.redirect + '\'';
t.equal(o.redirect, a[1], msg);
});
t.end();
});
test('parse_line_text', (t) => {
[
['tony hawk', 'tony hawk'],
[' tony hawk ', 'tony hawk'],
['it is [[tony hawk]] ', 'it is tony hawk'],
['it is [[tony hawk|tony]] ', 'it is tony'],
['it is [[tony danza|tony]] [[hawk]]', 'it is tony hawk'],
['tony hawk [http://www.whistler.ca]', 'tony hawk'],
['tony hawk in [http://www.whistler.ca whistler]', 'tony hawk in whistler'],
['it is [[Tony Hawk|Tony]]s mother in [[Toronto]]s', 'it is Tonys mother in Torontos']
].forEach((a) => {
let o = parse_line(a[0]);
var msg = '\'' + a[0] + '\' -> \'' + o.text + '\'';
t.equal(o.text, a[1], msg);
});
t.end();
});
test('parse_categories', (t) => {
[
['[[Category:<NAME>]]', ['<NAME>']],
['[[Category:<NAME>]][[Category:Formal Wear]]', ['<NAME>', 'Formal Wear']],
[' [[Category:<NAME>]] [[Category:Formal Wear]] ', ['<NAME>', 'Formal Wear']],
[' [[Category:<NAME>|metadata]] [[category:Formal Wear]] ', ['<NAME>', 'Formal Wear']],
['[[categoría:<NAME>|metadata]] ', ['<NAME>']]
].forEach((a) => {
let o = parse_categories(a[0]);
t.deepEqual(o, a[1]);
});
t.end();
});
test('parse_image', (t) => {
[
['[[File:<NAME>]]', 'File:<NAME>'],
['[[Image:<NAME>]]', 'Image:<NAME>'],
['[[Image:<NAME>|left]]', 'Image:<NAME>'],
['[[Image:Edouard Recon (2002).jpg|right|thumb|200px|Tropical Storm Edouard seen by [[Hurricane Hunters]]]]', 'Image:Edouard Recon (2002).jpg']
].forEach((a) => {
let o = parse_image(a[0]);
t.deepEqual(o, a[1]);
});
t.end();
});
test('xml', (t) => {
[
['North America,<ref name="fhwa"/> and one of', 'North America, and one of'],
['North America,<br /> and one of', 'North America, and one of'],
['hello <h2>world</h2>', 'hello world'],
[`hello<ref name="theroyal"/> world5, <ref name="">nono</ref> man`, 'hello world5, man'],
['hello <ref>nono!</ref> world1.', 'hello world1.'],
['hello <ref name=\'hullo\'>nono!</ref> world2.', 'hello world2.'],
['hello <ref name=\'hullo\'/>world3.', 'hello world3.'],
['hello <table name=\'\'><tr><td>hi<ref>nono!</ref></td></tr></table>world4.', 'hello world4.'],
['hello<ref name=\'\'/> world5', 'hello world5']
].forEach((a) => {
let s = kill_xml(a[0]);
t.equal(s, a[1]);
});
t.end();
});
|
imalberto/mojito
|
tests/func/examples/developerguide/test_adding_view_engines2.js
|
/*
* This is a basic func test for a UseCase application.
*/
YUI({
useConsoleOutput: true,
useBrowserConsole: true,
logInclude: { TestRunner: true }
}).use('node', 'node-event-simulate', 'test', 'console', function (Y) {
var suite = new Y.Test.Suite("Developerguide");
suite.add(new Y.Test.Case({
"test adding_view_engine2": function() {
Y.Assert.areEqual(' EJS at work!', Y.one('h2').get('innerHTML'));
Y.Assert.areEqual('In addition to Handlebars and EJS, you can also use these rendering engines:', Y.one('h3').get('innerHTML'));
Y.Assert.areEqual('Jade', Y.all('li').item(0).get('innerHTML'));
Y.Assert.areEqual('Dust', Y.all('li').item(1).get('innerHTML'));
Y.Assert.areEqual('underscore', Y.all('li').item(2).get('innerHTML'));
}
}));
Y.Test.Runner.add(suite);
});
|
ToQuery/clever-framework
|
clever-framework-core/src/main/java/io/github/toquery/framework/core/log/AppLogType.java
|
<gh_stars>1-10
package io.github.toquery.framework.core.log;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* @author toquery
* @version 1 modify
*/
@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum AppLogType {
CREATE("创建"),
MODIFY("修改"),
DELETE("删除"),
QUERY("查看");
private String remark;
}
|
PieterjanDeconinck/quarkus
|
integration-tests/maven/src/test/java/io/quarkus/maven/it/EnableForNative.java
|
package io.quarkus.maven.it;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EnabledIfSystemProperty(named = "quarkus.test.native", matches = "true")
public @interface EnableForNative {
}
|
cocrealabRutas/rutas-por-colombia-web-app
|
app/containers/Search/selectors.js
|
import { createSelector } from 'reselect';
import { initialSearchState } from './reducer';
/**
* Direct selector to the search state domain
*/
const selectSearchDomain = state =>
state.get('searchParameters', initialSearchState);
const makeSelectSearch = () =>
createSelector(
selectSearchDomain,
substate => substate.toJS(),
);
export { selectSearchDomain, makeSelectSearch };
|
LCBRU/identity
|
migrations/versions/065__RedcapProject__remove_ParticipantImportDefinition.py
|
from sqlalchemy import (
MetaData,
Table,
Column,
Integer,
)
from sqlalchemy.schema import ForeignKeyConstraint
meta = MetaData()
def upgrade(migrate_engine):
meta.bind = migrate_engine
t = Table("redcap_project", meta, autoload=True)
t.c.participant_import_definition_id.drop()
t.c.study_id.drop()
def downgrade(migrate_engine):
meta.bind = migrate_engine
pid = Table("participant_import_definition", meta, autoload=True)
s = Table("study", meta, autoload=True)
t = Table("redcap_project", meta, autoload=True)
participant_import_definition_id = Column("participant_import_definition_id", Integer, index=True)
participant_import_definition_id.create(t, index_name='idx__redcap_project__pid_id')
t.append_constraint(ForeignKeyConstraint([participant_import_definition_id], [pid.c.id]))
study_id = Column("study_id", Integer, index=True)
study_id.create(t, index_name='idx__redcap_project__study_id')
t.append_constraint(ForeignKeyConstraint([participant_import_definition_id], [pid.c.id]))
t.append_constraint(ForeignKeyConstraint([study_id], [s.c.id]))
|
marcusbalbi/study
|
javascript/testes-jasmine/src/procedimentos/ProcedimentoBase.js
|
var ProcedimentoBase = function (nome, preco) {
this.nome = nome;
this.preco = preco;
}
ProcedimentoBase.prototype.obterPreco = function (convenio) {
var desconto = convenio.obterDesconto ? convenio.obterDesconto : 0;
return this.preco + (convenio.obterDesconto() * this.preco);
}
module.exports = ProcedimentoBase;
|
manasys/grouper
|
grouper-misc/grouper-ui-dojo/dojo/dojox/editor/plugins/nls/th/InsertEntity.js.uncompressed.js
|
<filename>grouper-misc/grouper-ui-dojo/dojo/dojox/editor/plugins/nls/th/InsertEntity.js.uncompressed.js<gh_stars>100-1000
define(
"dojox/editor/plugins/nls/th/InsertEntity", ({
insertEntity: "แทรกสัญลักษณ์"
})
);
|
jordaoqualho/Lorena-Felicio
|
node_modules/@expo/vector-icons/build/SimpleLineIcons.js
|
import createIconSet from './createIconSet';
import font from './vendor/react-native-vector-icons/Fonts/SimpleLineIcons.ttf';
import glyphMap from './vendor/react-native-vector-icons/glyphmaps/SimpleLineIcons.json';
export default createIconSet(glyphMap, 'simple-line-icons', font);
//# sourceMappingURL=SimpleLineIcons.js.map
|
paranoid-software/elemental-cms
|
elementalcms/services/sessions/getme.py
|
<reponame>paranoid-software/elemental-cms
from elementalcms.persistence.repositories import SessionsRepository
from elementalcms.services import UseCaseResult, NoResult, Success, Failure
from elementalcms.core import MongoDbContext
class GetMe:
__db_context: MongoDbContext
def __init__(self, db_context: MongoDbContext):
self.__db_context = db_context
def execute(self, sid) -> UseCaseResult:
repo = SessionsRepository(self.__db_context)
result = repo.find({'sid': sid})
if result['total'] == 0:
return NoResult()
if result['total'] > 1:
return Failure({'duplicatedSession': True})
return Success(result['items'][0])
|
Coron4444/BalloonWorld
|
Document/html/class_vertex_shader_shadow_map.js
|
<gh_stars>0
var class_vertex_shader_shadow_map =
[
[ "Init", "class_vertex_shader_shadow_map.html#ad05ff60e979b3d2af8603a118cb51185", null ],
[ "ObjectSetting", "class_vertex_shader_shadow_map.html#a49f6120c2ca0200ca4d8bcb05cfae4d8", null ],
[ "Uninit", "class_vertex_shader_shadow_map.html#a5b36c3531d6116c609c8a62bc4ffd95d", null ],
[ "math_matrix_", "class_vertex_shader_shadow_map.html#a5b3069ce052a5de3e19ea578d8bdb950", null ]
];
|
TecArt/servicecatalog-development
|
oscm-extsvc/javasrc/org/oscm/types/exceptions/UserDeletionConstraintException.java
|
<filename>oscm-extsvc/javasrc/org/oscm/types/exceptions/UserDeletionConstraintException.java
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 2009-02-17
*
*******************************************************************************/
package org.oscm.types.exceptions;
import javax.xml.ws.WebFault;
import org.oscm.types.exceptions.beans.ApplicationExceptionBean;
/**
* Exception thrown when the deletion of a user fails due to constraint
* violations.
*
*/
@WebFault(name = "UserDeletionConstraintException", targetNamespace = "http://oscm.org/xsd")
public class UserDeletionConstraintException extends SaaSApplicationException {
private static final long serialVersionUID = -6822194102878539365L;
/**
* Constructs a new exception with <code>null</code> as its detail message.
* The cause is not initialized.
*/
public UserDeletionConstraintException() {
super();
}
/**
* Constructs a new exception with the specified detail message. The cause
* is not initialized.
*
* @param message
* the detail message
*/
public UserDeletionConstraintException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and bean for
* JAX-WS exception serialization.
*
* @param message
* the detail message
* @param bean
* the bean for JAX-WS exception serialization
*/
public UserDeletionConstraintException(String message,
ApplicationExceptionBean bean) {
super(message, bean);
}
/**
* Constructs a new exception with the specified detail message, cause, and
* bean for JAX-WS exception serialization.
*
* @param message
* the detail message
* @param bean
* the bean for JAX-WS exception serialization
* @param cause
* the cause
*/
public UserDeletionConstraintException(String message,
ApplicationExceptionBean bean, Throwable cause) {
super(message, bean, cause);
}
/**
* Constructs a new exception with the given detail message, and appends the
* specified reason to the message key.
*
* @param message
* the detail message
* @param reason
* the reason
*/
public UserDeletionConstraintException(String message, Reason reason) {
super(message);
setMessageKey(getMessageKey() + "." + reason.toString());
}
/**
* Enumeration of possible reasons for a
* {@link UserDeletionConstraintException}.
*/
public enum Reason {
/**
* The deletion failed because the user is the last administrator of the
* organization.
*/
LAST_ADMIN,
/**
* The deletion failed because the user tried to delete his own account.
*/
FORBIDDEN_SELF_DELETION,
/**
* The deletion failed because the user still has at least one active
* subscription.
*/
HAS_ACTIVE_SUBSCRIPTIONS;
}
}
|
yoshiekiura/algopeatio
|
vendor/bundle/ruby/2.2.0/gems/coercible-1.0.0/lib/coercible/coercer/array.rb
|
<reponame>yoshiekiura/algopeatio
module Coercible
class Coercer
# Coerce Array values
class Array < Object
primitive ::Array
TIME_SEGMENTS = [ :year, :month, :day, :hour, :min, :sec ].freeze
# Creates a Set instance from an Array
#
# @param [Array] value
#
# @return [Array]
#
# @api private
def to_set(value)
value.to_set
end
end # class Array
end # class Coercer
end # module Coercible
|
alphagov/transactions-explorer
|
test/service/test_department.py
|
import unittest
from hamcrest import is_, assert_that, contains, close_to
from lib.service import Department, Service
from test.service import details
class TestDepartment(unittest.TestCase):
def test_department_creation(self):
d = Department("Agency for Beautiful Code", [])
assert_that(d.name, is_("Agency for Beautiful Code"))
def test_building_a_list_of_departments_from_services(self):
services = [
Service(details({u'Abbr': 'ABC', u'Department': "Agency for Beautiful Code"})),
Service(details({u'Abbr': 'MSW', u'Department': "Ministry of Silly Walks"})),
Service(details({u'Abbr': 'ABC', u'Department': "Agency for Beautiful Code"})),
]
departments = Department.from_services(services)
assert_that(len(departments), is_(2))
assert_that(departments[0].name, is_("Agency for Beautiful Code"))
assert_that(departments[0].services,
contains(services[0], services[2]))
def test_count_of_high_volume_services(self):
services = [
Service(details({
u'High-volume?': 'yes'
})),
Service(details({
u'High-volume?': 'yes'
})),
Service(details({})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.high_volume_count, is_(2))
class TestDepartmentNameAsLink(unittest.TestCase):
def test_name_as_slug(self):
services = [
Service(details({u'Abbr': 'ABC', u'Department': 'Agency for Beautiful Code'})),
]
department = Department.from_services(services)[0]
assert_that(department.name_slug, is_('agency-for-beautiful-code'))
def test_name_with_quotes_as_slug(self):
services = [
Service(details({u'Abbr': 'ABC', u'Department': "Attorney General's Office"})),
]
department = Department.from_services(services)[0]
assert_that(department.name_slug, is_('attorney-generals-office'))
class TestDepartmentLink(unittest.TestCase):
def test_link_is_first_services_slugified_abbreviation(self):
services = [
Service(details({u'Abbr': "ABC"})),
Service(details({u'Abbr': "ABC"})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.link, is_("department/abc/by-transactions-per-year/descending"))
class TestDepartmentAbbreviation(unittest.TestCase):
def test_abbreviation_is_first_services_abbreviation(self):
services = [
Service(details({u'Abbr': "ABC"})),
Service(details({u'Abbr': "ABC"})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.abbr, is_("ABC"))
class TestDepartmentVolume(unittest.TestCase):
def test_volume_is_total_of_last_available_quarter_for_each_service(self):
services = [
Service(details({"2012-Q4 Vol.": "1,000", "2013-Q1 Vol.": "1,500"})),
Service(details({"2012-Q4 Vol.": "2,000"})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.volume, is_(3500))
def test_volume_with_one_service(self):
services = [
Service(details({"2012-Q4 Vol.": "2,000"}))
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.volume, is_(2000))
def test_volume_ignores_services_with_no_kpis(self):
services = [
Service(details({"2012-Q4 Vol.": "2,000"})),
Service(details({})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.volume, is_(2000))
def test_volume_is_none_if_no_service_has_kpis(self):
services = [
Service(details({})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.volume, is_(None))
class TestDepartmentCost(unittest.TestCase):
def test_cost_is_sum_of_transaction_costs_for_each_transaction_handled(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
u'2012-Q4 CPT (\xa3)': "2.00",
u'High-volume?': 'yes'
})),
Service(details({
"2013-Q1 Vol.": "1,000",
u'2013-Q1 CPT (\xa3)': "3.00",
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.cost, is_(7000))
def test_cost_ignores_non_high_volume_services(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
u'2012-Q4 CPT (\xa3)': "2.00",
u'High-volume?': 'yes'
})),
Service(details({
"2013-Q1 Vol.": "1,000",
u'2013-Q1 CPT (\xa3)': "3.00",
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.cost, is_(4000))
def test_cost_is_none_when_no_high_volume_services(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
u'2012-Q4 CPT (\xa3)': "2.00",
})),
Service(details({
"2013-Q1 Vol.": "1,000",
u'2013-Q1 CPT (\xa3)': "3.00",
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.cost, is_(None))
def test_cost_ignores_services_with_no_cpt(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
u'High-volume?': 'yes'
})),
Service(details({
"2013-Q1 Vol.": "1,000",
u'2013-Q1 CPT (\xa3)': "3.00",
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.cost, is_(3000))
def test_cost_is_none_when_no_kpi_is_available(self):
services = [
Service(details({
u'High-volume?': 'yes'
})),
Service(details({
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.cost, is_(None))
def test_cost_use_data_from_the_same_quarter_for_volume_and_digital_volume(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
u'2012-Q4 CPT (\xa3)': "2.00",
u'High-volume?': 'yes'
})),
Service(details({
"2012-Q4 Vol.": "1,000",
u'2012-Q4 CPT (\xa3)': "3.00",
"2013-Q1 Vol.": "3,000",
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.cost, is_(7000))
class TestDepartmentTakeup(unittest.TestCase):
def test_takeup_is_volume_divided_by_digital_volume(self):
services = [
Service(details({
'2012-Q4 Vol.': '10',
'2012-Q4 Digital vol.': '5',
u'High-volume?': 'yes'
})),
Service(details({
'2012-Q4 Vol.': '30',
'2012-Q4 Digital vol.': '10',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.takeup, is_(0.375))
def test_takeup_is_none_if_digital_volume_is_none(self):
services = [
Service(details({
'2012-Q4 Vol.': '10',
u'High-volume?': 'yes'
})),
Service(details({
'2012-Q4 Vol.': '30',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.takeup, is_(None))
def test_takeup_is_none_if_volume_is_none(self):
services = [
Service(details({
'2012-Q4 Digital vol.': '5',
u'High-volume?': 'yes'
})),
Service(details({
'2012-Q4 Digital vol.': '10',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.takeup, is_(None))
def test_takeup_only_includes_high_volume_services(self):
services = [
Service(details({
'2012-Q4 Vol.': '10',
'2012-Q4 Digital vol.': '5',
u'High-volume?': 'yes'
})),
Service(details({
'2012-Q4 Vol.': '30',
'2012-Q4 Digital vol.': '10',
u'High-volume?': 'yes'
})),
Service(details({
'2012-Q4 Vol.': '30',
'2012-Q4 Digital vol.': '10',
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.takeup, is_(0.375))
def test_takeup_use_data_from_the_same_quarter_for_volume_and_digital_volume(self):
services = [
Service(details({
'2012-Q4 Vol.': '10',
'2012-Q4 Digital vol.': '5',
u'High-volume?': 'yes'
})),
Service(details({
'2012-Q4 Vol.': '30',
'2012-Q4 Digital vol.': '10',
'2013-Q1 Vol.': '20',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.takeup, is_(0.375))
class TestDepartmentDataCoverage(unittest.TestCase):
def test_data_coverage_is_average_of_service_coverages(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
'2012-Q4 Digital vol.': '10',
u'2012-Q4 CPT (\xa3)': "2.00",
"2013-Q1 Vol.": "2,000",
u'2013-Q1 CPT (\xa3)': "2.00",
'2013-Q1 Digital vol.': '10',
u'High-volume?': 'yes'
})),
Service(details({
"2012-Q4 Vol.": "1,000",
u'2012-Q4 CPT (\xa3)': "3.00",
'2012-Q4 Digital vol.': '10',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
coverage = dept.data_coverage
assert_that(float(coverage.percentage), is_(0.1875))
assert_that(coverage.requested, is_(48))
assert_that(coverage.provided, is_(9))
def test_data_coverage_excludes_non_high_volume_services(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
'2012-Q4 Digital vol.': '10',
u'2012-Q4 CPT (\xa3)': "2.00",
"2013-Q1 Vol.": "2,000",
u'2013-Q1 CPT (\xa3)': "2.00",
'2013-Q1 Digital vol.': '10',
})),
Service(details({
"2012-Q4 Vol.": "1,000",
u'2012-Q4 CPT (\xa3)': "3.00",
'2012-Q4 Digital vol.': '10',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
coverage = dept.data_coverage
assert_that(float(coverage.percentage), is_(0.125))
assert_that(coverage.requested, is_(24))
assert_that(coverage.provided, is_(3))
def test_data_coverage_is_none_when_no_high_volume_services(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
'2012-Q4 Digital vol.': '10',
u'2012-Q4 CPT (\xa3)': "2.00",
"2013-Q1 Vol.": "2,000",
u'2013-Q1 CPT (\xa3)': "2.00",
'2013-Q1 Digital vol.': '10',
})),
Service(details({
"2012-Q4 Vol.": "1,000",
u'2012-Q4 CPT (\xa3)': "3.00",
'2012-Q4 Digital vol.': '10',
})),
]
dept = Department("Agency for Beautiful Code", services)
assert_that(dept.data_coverage, is_(None))
def test_data_coverage_when_quarter_not_requested(self):
services = [
Service(details({
"2012-Q4 Vol.": "2,000",
'2012-Q4 Digital vol.': '10',
u'2012-Q4 CPT (\xa3)': "2.00",
"2013-Q1 Vol.": "***",
u'2013-Q1 CPT (\xa3)': "***",
'2013-Q1 Digital vol.': '***',
u'High-volume?': 'yes'
})),
Service(details({
"2012-Q4 Vol.": "1,000",
u'2012-Q4 CPT (\xa3)': "3.00",
'2012-Q4 Digital vol.': '10',
u'High-volume?': 'yes'
})),
]
dept = Department("Agency for Beautiful Code", services)
coverage = dept.data_coverage
assert_that(float(coverage.percentage), close_to(0.1333333, 0.001))
assert_that(coverage.requested, is_(45))
assert_that(coverage.provided, is_(6))
|
ramiyer/voldemort
|
src/java/voldemort/rest/coordinator/config/StoreClientConfigSource.java
|
package voldemort.rest.coordinator.config;
/**
* The kinds of config sources supported or planned for Coordinator
*/
public enum StoreClientConfigSource {
FILE,
ZOOKEEPER;
public static StoreClientConfigSource get(String value) {
return StoreClientConfigSource.valueOf(value.trim().toUpperCase());
}
}
|
enfoTek/tomato.linksys.e2000.nvram-mod
|
tools-src/gnu/glibc/localedata/tests-mbwc/tgn_funcdef.h
|
#ifndef TGN_FUNCDEF_H
#define TGN_FUNCDEF_H
/* Unique number for each test. */
#define Tiswalnum 1
#define Tiswalpha 2
#define Tiswcntrl 3
#define Tiswctype 4
#define Tiswdigit 5
#define Tiswgraph 6
#define Tiswlower 7
#define Tiswprint 8
#define Tiswpunct 9
#define Tiswspace 10
#define Tiswupper 11
#define Tiswxdigit 12
#define Tmblen 13
#define Tmbrlen 14
#define Tmbrtowc 15
#define Tmbsrtowcs 16
#define Tmbstowcs 17
#define Tmbtowc 18
#define Tstrcoll 19
#define Tstrfmon 20
#define Tstrxfrm 21
#define Tswscanf 22
#define Ttowctrans 23
#define Ttowlower 24
#define Ttowupper 25
#define Twcrtomb 26
#define Twcscat 27
#define Twcschr 28
#define Twcscmp 29
#define Twcscoll 30
#define Twcscpy 31
#define Twcscspn 32
#define Twcslen 33
#define Twcsncat 34
#define Twcsncmp 35
#define Twcsncpy 36
#define Twcspbrk 37
#define Twcsrtombs 38
#define Twcsspn 39
#define Twcsstr 40
#define Twcstod 41
#define Twcstok 42
#define Twcstombs 43
#define Twcswidth 44
#define Twcsxfrm 45
#define Twctob 46
#define Twctomb 47
#define Twctrans 48
#define Twctype 49
#define Twcwidth 50
/* Name of each test. */
#define S_ISWALNUM "iswalnum"
#define S_ISWALPHA "iswalpha"
#define S_ISWCNTRL "iswcntrl"
#define S_ISWCTYPE "iswctype"
#define S_ISWDIGIT "iswdigit"
#define S_ISWGRAPH "iswgraph"
#define S_ISWLOWER "iswlower"
#define S_ISWPRINT "iswprint"
#define S_ISWPUNCT "iswpunct"
#define S_ISWSPACE "iswspace"
#define S_ISWUPPER "iswupper"
#define S_ISWXDIGIT "iswxdigit"
#define S_MBLEN "mblen"
#define S_MBRLEN "mbrlen"
#define S_MBRTOWC "mbrtowc"
#define S_MBSRTOWCS "mbsrtowcs"
#define S_MBSTOWCS "mbstowcs"
#define S_MBTOWC "mbtowc"
#define S_STRCOLL "strcoll"
#define S_STRFMON "strfmon"
#define S_STRXFRM "strxfrm"
#define S_SWSCANF "swscanf"
#define S_TOWCTRANS "towctrans"
#define S_TOWLOWER "towlower"
#define S_TOWUPPER "towupper"
#define S_WCRTOMB "wcrtomb"
#define S_WCSCAT "wcscat"
#define S_WCSCHR "wcschr"
#define S_WCSCMP "wcscmp"
#define S_WCSCOLL "wcscoll"
#define S_WCSCPY "wcscpy"
#define S_WCSCSPN "wcscspn"
#define S_WCSLEN "wcslen"
#define S_WCSNCAT "wcsncat"
#define S_WCSNCMP "wcsncmp"
#define S_WCSNCPY "wcsncpy"
#define S_WCSPBRK "wcspbrk"
#define S_WCSRTOMBS "wcsrtombs"
#define S_WCSSPN "wcsspn"
#define S_WCSSTR "wcsstr"
#define S_WCSTOD "wcstod"
#define S_WCSTOK "wcstok"
#define S_WCSTOMBS "wcstombs"
#define S_WCSWIDTH "wcswidth"
#define S_WCSXFRM "wcsxfrm"
#define S_WCTOB "wctob"
#define S_WCTOMB "wctomb"
#define S_WCTRANS "wctrans"
#define S_WCTYPE "wctype"
#define S_WCWIDTH "wcwidth"
/* Prototypes for test functions. */
extern int tst_iswalnum (FILE *, int);
extern int tst_iswalpha (FILE *, int);
extern int tst_iswcntrl (FILE *, int);
extern int tst_iswctype (FILE *, int);
extern int tst_iswdigit (FILE *, int);
extern int tst_iswgraph (FILE *, int);
extern int tst_iswlower (FILE *, int);
extern int tst_iswprint (FILE *, int);
extern int tst_iswpunct (FILE *, int);
extern int tst_iswspace (FILE *, int);
extern int tst_iswupper (FILE *, int);
extern int tst_iswxdigit (FILE *, int);
extern int tst_mblen (FILE *, int);
extern int tst_mbrlen (FILE *, int);
extern int tst_mbrtowc (FILE *, int);
extern int tst_mbsrtowcs (FILE *, int);
extern int tst_mbstowcs (FILE *, int);
extern int tst_mbtowc (FILE *, int);
extern int tst_strcoll (FILE *, int);
extern int tst_strfmon (FILE *, int);
extern int tst_strxfrm (FILE *, int);
extern int tst_swscanf (FILE *, int);
extern int tst_towctrans (FILE *, int);
extern int tst_towlower (FILE *, int);
extern int tst_towupper (FILE *, int);
extern int tst_wcrtomb (FILE *, int);
extern int tst_wcscat (FILE *, int);
extern int tst_wcschr (FILE *, int);
extern int tst_wcscmp (FILE *, int);
extern int tst_wcscoll (FILE *, int);
extern int tst_wcscpy (FILE *, int);
extern int tst_wcscspn (FILE *, int);
extern int tst_wcslen (FILE *, int);
extern int tst_wcsncat (FILE *, int);
extern int tst_wcsncmp (FILE *, int);
extern int tst_wcsncpy (FILE *, int);
extern int tst_wcspbrk (FILE *, int);
extern int tst_wcsrtombs (FILE *, int);
extern int tst_wcsspn (FILE *, int);
extern int tst_wcsstr (FILE *, int);
extern int tst_wcstod (FILE *, int);
extern int tst_wcstok (FILE *, int);
extern int tst_wcstombs (FILE *, int);
extern int tst_wcswidth (FILE *, int);
extern int tst_wcsxfrm (FILE *, int);
extern int tst_wctob (FILE *, int);
extern int tst_wctomb (FILE *, int);
extern int tst_wctrans (FILE *, int);
extern int tst_wctype (FILE *, int);
extern int tst_wcwidth (FILE *, int);
#endif /* TGN_FUNCDEF_H */
|
bcai-ps/py-pure-client
|
docs/source/examples/flashblade/get_file_system_snapshots_transfer.py
|
<reponame>bcai-ps/py-pure-client<gh_stars>0
# list all file systems
res = client.get_file_system_snapshots_transfer()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# list first five filesystems and sort by provisioned in descendant order
res = client.get_file_system_snapshots_transfer(names=["myfs.mysnap"])
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# Other valid fields: continuation_token, filter, ids, limit, offset, sort, total_only
# See section "Common Fields" for examples
|
tuvapp/tuvappcom
|
myvenv/lib/python3.5/site-packages/prompt_toolkit/eventloop/select.py
|
<filename>myvenv/lib/python3.5/site-packages/prompt_toolkit/eventloop/select.py<gh_stars>1-10
from __future__ import unicode_literals, absolute_import
import sys
import select
import errno
__all__ = (
'select_fds',
)
def _fd_to_int(fd):
if isinstance(fd, int):
return fd
else:
return fd.fileno()
def select_fds(read_fds, timeout):
"""
Wait for a list of file descriptors (`read_fds`) to become ready for
reading. This chooses the most appropriate select-tool for use in
prompt-toolkit.
Note: This is an internal API that shouldn't be used for external projects.
"""
# Map to ensure that we return the objects that were passed in originally.
# Whether they are a fd integer or an object that has a fileno().
# (The 'poll' implementation for instance, returns always integers.)
fd_map = dict((_fd_to_int(fd), fd) for fd in read_fds)
# Use of the 'select' module, that was introduced in Python3.4. We don't
# use it before 3.5 however, because this is the point where this module
# retries interrupted system calls.
if sys.version_info >= (3, 5):
try:
result = _python3_selectors(read_fds, timeout)
except PermissionError:
# We had a situation (in pypager) where epoll raised a
# PermissionError when a local file descriptor was registered,
# however poll and select worked fine. So, in that case, just try
# using select below.
result = None
else:
result = None
if result is None:
try:
# First, try the 'select' module. This is the most universal, and
# powerful enough in our case.
result = _select(read_fds, timeout)
except ValueError:
# When we have more than 1024 open file descriptors, we'll always
# get a "ValueError: filedescriptor out of range in select()" for
# 'select'. In this case, retry, using 'poll' instead.
result = _poll(read_fds, timeout)
return [fd_map[_fd_to_int(fd)] for fd in result]
def _python3_selectors(read_fds, timeout):
"""
Use of the Python3 'selectors' module.
NOTE: Only use on Python 3.5 or newer!
"""
import selectors # Inline import: Python3 only!
sel = selectors.DefaultSelector()
for fd in read_fds:
sel.register(fd, selectors.EVENT_READ, None)
events = sel.select(timeout=timeout)
try:
return [key.fileobj for key, mask in events]
finally:
sel.close()
def _poll(read_fds, timeout):
"""
Use 'poll', to wait for any of the given `read_fds` to become ready.
"""
p = select.poll()
for fd in read_fds:
p.register(fd, select.POLLIN)
tuples = p.poll(timeout) # Returns (fd, event) tuples.
return [t[0] for t in tuples]
def _select(read_fds, timeout):
"""
Wrapper around select.select.
When the SIGWINCH signal is handled, other system calls, like select
are aborted in Python. This wrapper will retry the system call.
"""
while True:
try:
return select.select(read_fds, [], [], timeout)[0]
except select.error as e:
# Retry select call when EINTR
if e.args and e.args[0] == errno.EINTR:
continue
else:
raise
|
wwwennie/pycdft
|
pycdft/atomic/pp.py
|
""" Input file for generation of promolecule densities, *.spavr files in rho/ """
SG15PP = {
'Ag': {'atomic_number': 47,
'mass': 107.87000275,
'nel': 19,
'upffile': 'Ag_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ag_ONCV_PBE-1.0.upf',
'xmlfile': 'Ag_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ag_ONCV_PBE-1.0.xml'},
'Al': {'atomic_number': 13,
'mass': 26.98200035,
'nel': 11,
'upffile': 'Al_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Al_ONCV_PBE-1.0.upf',
'xmlfile': 'Al_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Al_ONCV_PBE-1.0.xml'},
'Ar': {'atomic_number': 18,
'mass': 39.94800186,
'nel': 8,
'upffile': 'Ar_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Ar_ONCV_PBE-1.1.upf',
'xmlfile': 'Ar_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Ar_ONCV_PBE-1.1.xml'},
'As': {'atomic_number': 33,
'mass': 74.92199707,
'nel': 5,
'upffile': 'As_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/As_ONCV_PBE-1.1.upf',
'xmlfile': 'As_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/As_ONCV_PBE-1.1.xml'},
'Au': {'atomic_number': 79,
'mass': 196.97000122,
'nel': 19,
'upffile': 'Au_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Au_ONCV_PBE-1.0.upf',
'xmlfile': 'Au_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Au_ONCV_PBE-1.0.xml'},
'B': {'atomic_number': 5,
'mass': 10.81000042,
'nel': 3,
'upffile': 'B_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/B_ONCV_PBE-1.0.upf',
'xmlfile': 'B_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/B_ONCV_PBE-1.0.xml'},
'Ba': {'atomic_number': 56,
'mass': 137.33000183,
'nel': 10,
'upffile': 'Ba_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ba_ONCV_PBE-1.0.upf',
'xmlfile': 'Ba_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ba_ONCV_PBE-1.0.xml'},
'Be': {'atomic_number': 4,
'mass': 9.01220036,
'nel': 4,
'upffile': 'Be_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Be_ONCV_PBE-1.0.upf',
'xmlfile': 'Be_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Be_ONCV_PBE-1.0.xml'},
'Bi': {'atomic_number': 83,
'mass': 208.97999573,
'nel': 15,
'upffile': 'Bi_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Bi_ONCV_PBE-1.0.upf',
'xmlfile': 'Bi_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Bi_ONCV_PBE-1.0.xml'},
'Br': {'atomic_number': 35,
'mass': 79.90399933,
'nel': 7,
'upffile': 'Br_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Br_ONCV_PBE-1.0.upf',
'xmlfile': 'Br_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Br_ONCV_PBE-1.0.xml'},
'C': {'atomic_number': 6,
'mass': 12.01099968,
'nel': 4,
'upffile': 'C_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/C_ONCV_PBE-1.0.upf',
'xmlfile': 'C_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/C_ONCV_PBE-1.0.xml'},
'Ca': {'atomic_number': 20,
'mass': 40.07799911,
'nel': 10,
'upffile': 'Ca_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ca_ONCV_PBE-1.0.upf',
'xmlfile': 'Ca_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ca_ONCV_PBE-1.0.xml'},
'Cd': {'atomic_number': 48,
'mass': 112.41000366,
'nel': 20,
'upffile': 'Cd_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Cd_ONCV_PBE-1.0.upf',
'xmlfile': 'Cd_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Cd_ONCV_PBE-1.0.xml'},
'Cl': {'atomic_number': 17,
'mass': 35.45000076,
'nel': 7,
'upffile': 'Cl_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Cl_ONCV_PBE-1.1.upf',
'xmlfile': 'Cl_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Cl_ONCV_PBE-1.1.xml'},
'Co': {'atomic_number': 27,
'mass': 58.93299866,
'nel': 17,
'upffile': 'Co_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Co_ONCV_PBE-1.0.upf',
'xmlfile': 'Co_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Co_ONCV_PBE-1.0.xml'},
'Cr': {'atomic_number': 24,
'mass': 51.99599838,
'nel': 14,
'upffile': 'Cr_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Cr_ONCV_PBE-1.0.upf',
'xmlfile': 'Cr_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Cr_ONCV_PBE-1.0.xml'},
'Cs': {'atomic_number': 55,
'mass': 132.91000366,
'nel': 9,
'upffile': 'Cs_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Cs_ONCV_PBE-1.1.upf',
'xmlfile': 'Cs_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Cs_ONCV_PBE-1.1.xml'},
'Cu': {'atomic_number': 29,
'mass': 63.54600143,
'nel': 19,
'upffile': 'Cu_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Cu_ONCV_PBE-1.0.upf',
'xmlfile': 'Cu_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Cu_ONCV_PBE-1.0.xml'},
'F': {'atomic_number': 9,
'mass': 18.99799919,
'nel': 7,
'upffile': 'F_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/F_ONCV_PBE-1.0.upf',
'xmlfile': 'F_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/F_ONCV_PBE-1.0.xml'},
'Fe': {'atomic_number': 26,
'mass': 55.84500122,
'nel': 16,
'upffile': 'Fe_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Fe_ONCV_PBE-1.0.upf',
'xmlfile': 'Fe_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Fe_ONCV_PBE-1.0.xml'},
'Ga': {'atomic_number': 31,
'mass': 69.72299957,
'nel': 13,
'upffile': 'Ga_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ga_ONCV_PBE-1.0.upf',
'xmlfile': 'Ga_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ga_ONCV_PBE-1.0.xml'},
'Ge': {'atomic_number': 32,
'mass': 72.62999725,
'nel': 14,
'upffile': 'Ge_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ge_ONCV_PBE-1.0.upf',
'xmlfile': 'Ge_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ge_ONCV_PBE-1.0.xml'},
'H': {'atomic_number': 1,
'mass': 1.00800002,
'nel': 1,
'upffile': 'H_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/H_ONCV_PBE-1.0.upf',
'xmlfile': 'H_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/H_ONCV_PBE-1.0.xml'},
'He': {'atomic_number': 2,
'mass': 4.00260019,
'nel': 2,
'upffile': 'He_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/He_ONCV_PBE-1.0.upf',
'xmlfile': 'He_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/He_ONCV_PBE-1.0.xml'},
'Hf': {'atomic_number': 72,
'mass': 178.49000549,
'nel': 12,
'upffile': 'Hf_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Hf_ONCV_PBE-1.1.upf',
'xmlfile': 'Hf_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Hf_ONCV_PBE-1.1.xml'},
'Hg': {'atomic_number': 80,
'mass': 200.58999634,
'nel': 20,
'upffile': 'Hg_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Hg_ONCV_PBE-1.0.upf',
'xmlfile': 'Hg_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Hg_ONCV_PBE-1.0.xml'},
'I': {'atomic_number': 53,
'mass': 126.90000153,
'nel': 17,
'upffile': 'I_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/I_ONCV_PBE-1.1.upf',
'xmlfile': 'I_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/I_ONCV_PBE-1.1.xml'},
'In': {'atomic_number': 49,
'mass': 114.81999969,
'nel': 13,
'upffile': 'In_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/In_ONCV_PBE-1.1.upf',
'xmlfile': 'In_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/In_ONCV_PBE-1.1.xml'},
'Ir': {'atomic_number': 77,
'mass': 192.22000122,
'nel': 17,
'upffile': 'Ir_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ir_ONCV_PBE-1.0.upf',
'xmlfile': 'Ir_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ir_ONCV_PBE-1.0.xml'},
'K': {'atomic_number': 19,
'mass': 39.09799957,
'nel': 9,
'upffile': 'K_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/K_ONCV_PBE-1.0.upf',
'xmlfile': 'K_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/K_ONCV_PBE-1.0.xml'},
'Kr': {'atomic_number': 36,
'mass': 83.79799652,
'nel': 8,
'upffile': 'Kr_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Kr_ONCV_PBE-1.0.upf',
'xmlfile': 'Kr_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Kr_ONCV_PBE-1.0.xml'},
'La': {'atomic_number': 57,
'mass': 138.91000366,
'nel': 11,
'upffile': 'La_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/La_ONCV_PBE-1.0.upf',
'xmlfile': 'La_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/La_ONCV_PBE-1.0.xml'},
'Li': {'atomic_number': 3,
'mass': 6.94000006,
'nel': 3,
'upffile': 'Li_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Li_ONCV_PBE-1.0.upf',
'xmlfile': 'Li_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Li_ONCV_PBE-1.0.xml'},
'Mg': {'atomic_number': 12,
'mass': 24.30500031,
'nel': 10,
'upffile': 'Mg_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Mg_ONCV_PBE-1.0.upf',
'xmlfile': 'Mg_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Mg_ONCV_PBE-1.0.xml'},
'Mn': {'atomic_number': 25,
'mass': 54.93799973,
'nel': 15,
'upffile': 'Mn_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Mn_ONCV_PBE-1.0.upf',
'xmlfile': 'Mn_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Mn_ONCV_PBE-1.0.xml'},
'Mo': {'atomic_number': 42,
'mass': 95.95999908,
'nel': 14,
'upffile': 'Mo_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Mo_ONCV_PBE-1.0.upf',
'xmlfile': 'Mo_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Mo_ONCV_PBE-1.0.xml'},
'N': {'atomic_number': 7,
'mass': 14.00699997,
'nel': 5,
'upffile': 'N_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/N_ONCV_PBE-1.0.upf',
'xmlfile': 'N_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/N_ONCV_PBE-1.0.xml'},
'Na': {'atomic_number': 11,
'mass': 22.98999977,
'nel': 9,
'upffile': 'Na_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Na_ONCV_PBE-1.0.upf',
'xmlfile': 'Na_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Na_ONCV_PBE-1.0.xml'},
'Nb': {'atomic_number': 41,
'mass': 92.90599823,
'nel': 13,
'upffile': 'Nb_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Nb_ONCV_PBE-1.0.upf',
'xmlfile': 'Nb_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Nb_ONCV_PBE-1.0.xml'},
'Ne': {'atomic_number': 10,
'mass': 20.18000031,
'nel': 8,
'upffile': 'Ne_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ne_ONCV_PBE-1.0.upf',
'xmlfile': 'Ne_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ne_ONCV_PBE-1.0.xml'},
'Ni': {'atomic_number': 28,
'mass': 58.69300079,
'nel': 18,
'upffile': 'Ni_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ni_ONCV_PBE-1.0.upf',
'xmlfile': 'Ni_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ni_ONCV_PBE-1.0.xml'},
'O': {'atomic_number': 8,
'mass': 15.9989996,
'nel': 6,
'upffile': 'O_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/O_ONCV_PBE-1.0.upf',
'xmlfile': 'O_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/O_ONCV_PBE-1.0.xml'},
'Os': {'atomic_number': 76,
'mass': 190.22999573,
'nel': 16,
'upffile': 'Os_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Os_ONCV_PBE-1.0.upf',
'xmlfile': 'Os_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Os_ONCV_PBE-1.0.xml'},
'P': {'atomic_number': 15,
'mass': 30.97400093,
'nel': 5,
'upffile': 'P_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/P_ONCV_PBE-1.1.upf',
'xmlfile': 'P_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/P_ONCV_PBE-1.1.xml'},
'Pb': {'atomic_number': 82,
'mass': 207.19999695,
'nel': 14,
'upffile': 'Pb_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Pb_ONCV_PBE-1.0.upf',
'xmlfile': 'Pb_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Pb_ONCV_PBE-1.0.xml'},
'Pd': {'atomic_number': 46,
'mass': 106.41999817,
'nel': 18,
'upffile': 'Pd_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Pd_ONCV_PBE-1.0.upf',
'xmlfile': 'Pd_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Pd_ONCV_PBE-1.0.xml'},
'Pt': {'atomic_number': 78,
'mass': 195.08000183,
'nel': 18,
'upffile': 'Pt_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Pt_ONCV_PBE-1.0.upf',
'xmlfile': 'Pt_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Pt_ONCV_PBE-1.0.xml'},
'Rb': {'atomic_number': 37,
'mass': 85.46800232,
'nel': 9,
'upffile': 'Rb_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Rb_ONCV_PBE-1.0.upf',
'xmlfile': 'Rb_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Rb_ONCV_PBE-1.0.xml'},
'Re': {'atomic_number': 75,
'mass': 186.21000671,
'nel': 15,
'upffile': 'Re_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Re_ONCV_PBE-1.0.upf',
'xmlfile': 'Re_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Re_ONCV_PBE-1.0.xml'},
'Rh': {'atomic_number': 45,
'mass': 102.91000366,
'nel': 17,
'upffile': 'Rh_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Rh_ONCV_PBE-1.0.upf',
'xmlfile': 'Rh_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Rh_ONCV_PBE-1.0.xml'},
'Ru': {'atomic_number': 44,
'mass': 101.06999969,
'nel': 16,
'upffile': 'Ru_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ru_ONCV_PBE-1.0.upf',
'xmlfile': 'Ru_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ru_ONCV_PBE-1.0.xml'},
'S': {'atomic_number': 16,
'mass': 32.06000137,
'nel': 6,
'upffile': 'S_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/S_ONCV_PBE-1.1.upf',
'xmlfile': 'S_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/S_ONCV_PBE-1.1.xml'},
'Sb': {'atomic_number': 51,
'mass': 121.76000214,
'nel': 15,
'upffile': 'Sb_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Sb_ONCV_PBE-1.1.upf',
'xmlfile': 'Sb_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Sb_ONCV_PBE-1.1.xml'},
'Sc': {'atomic_number': 21,
'mass': 44.95600128,
'nel': 11,
'upffile': 'Sc_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Sc_ONCV_PBE-1.0.upf',
'xmlfile': 'Sc_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Sc_ONCV_PBE-1.0.xml'},
'Se': {'atomic_number': 34,
'mass': 78.95999908,
'nel': 6,
'upffile': 'Se_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Se_ONCV_PBE-1.1.upf',
'xmlfile': 'Se_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Se_ONCV_PBE-1.1.xml'},
'Si': {'atomic_number': 14,
'mass': 28.08499908,
'nel': 4,
'upffile': 'Si_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Si_ONCV_PBE-1.1.upf',
'xmlfile': 'Si_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Si_ONCV_PBE-1.1.xml'},
'Sn': {'atomic_number': 50,
'mass': 118.70999908,
'nel': 14,
'upffile': 'Sn_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Sn_ONCV_PBE-1.1.upf',
'xmlfile': 'Sn_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Sn_ONCV_PBE-1.1.xml'},
'Sr': {'atomic_number': 38,
'mass': 87.62000275,
'nel': 10,
'upffile': 'Sr_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Sr_ONCV_PBE-1.0.upf',
'xmlfile': 'Sr_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Sr_ONCV_PBE-1.0.xml'},
'Ta': {'atomic_number': 73,
'mass': 180.94999695,
'nel': 13,
'upffile': 'Ta_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Ta_ONCV_PBE-1.1.upf',
'xmlfile': 'Ta_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Ta_ONCV_PBE-1.1.xml'},
'Tc': {'atomic_number': 43,
'mass': 97.91000366,
'nel': 15,
'upffile': 'Tc_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Tc_ONCV_PBE-1.0.upf',
'xmlfile': 'Tc_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Tc_ONCV_PBE-1.0.xml'},
'Te': {'atomic_number': 52,
'mass': 127.59999847,
'nel': 16,
'upffile': 'Te_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Te_ONCV_PBE-1.1.upf',
'xmlfile': 'Te_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Te_ONCV_PBE-1.1.xml'},
'Ti': {'atomic_number': 22,
'mass': 47.86700058,
'nel': 12,
'upffile': 'Ti_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Ti_ONCV_PBE-1.0.upf',
'xmlfile': 'Ti_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Ti_ONCV_PBE-1.0.xml'},
'Tl': {'atomic_number': 81,
'mass': 204.38000488,
'nel': 13,
'upffile': 'Tl_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Tl_ONCV_PBE-1.0.upf',
'xmlfile': 'Tl_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Tl_ONCV_PBE-1.0.xml'},
'V': {'atomic_number': 23,
'mass': 50.94200134,
'nel': 13,
'upffile': 'V_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/V_ONCV_PBE-1.0.upf',
'xmlfile': 'V_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/V_ONCV_PBE-1.0.xml'},
'W': {'atomic_number': 74,
'mass': 183.83999634,
'nel': 14,
'upffile': 'W_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/W_ONCV_PBE-1.1.upf',
'xmlfile': 'W_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/W_ONCV_PBE-1.1.xml'},
'Xe': {'atomic_number': 54,
'mass': 131.28999329,
'nel': 18,
'upffile': 'Xe_ONCV_PBE-1.1.upf',
'upfpath': '../../potential/UPF/Xe_ONCV_PBE-1.1.upf',
'xmlfile': 'Xe_ONCV_PBE-1.1.xml',
'xmlpath': '../../potential/XML/Xe_ONCV_PBE-1.1.xml'},
'Y': {'atomic_number': 39,
'mass': 88.90599823,
'nel': 11,
'upffile': 'Y_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Y_ONCV_PBE-1.0.upf',
'xmlfile': 'Y_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Y_ONCV_PBE-1.0.xml'},
'Zn': {'atomic_number': 30,
'mass': 65.37999725,
'nel': 20,
'upffile': 'Zn_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Zn_ONCV_PBE-1.0.upf',
'xmlfile': 'Zn_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Zn_ONCV_PBE-1.0.xml'},
'Zr': {'atomic_number': 40,
'mass': 91.22399902,
'nel': 12,
'upffile': 'Zr_ONCV_PBE-1.0.upf',
'upfpath': '../../potential/UPF/Zr_ONCV_PBE-1.0.upf',
'xmlfile': 'Zr_ONCV_PBE-1.0.xml',
'xmlpath': '../../potential/XML/Zr_ONCV_PBE-1.0.xml'}
}
|
hongchun166/jtxt
|
app/src/main/java/com/linkb/jstx/adapter/ViewPaperAdapter.java
|
<filename>app/src/main/java/com/linkb/jstx/adapter/ViewPaperAdapter.java
package com.linkb.jstx.adapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
public class ViewPaperAdapter extends PagerAdapter {
private List<View> pageViews;
public ViewPaperAdapter(List<View> pageViews) {
this.pageViews = pageViews;
}
@Override
public int getCount() {
return pageViews.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(pageViews.get(position));
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(pageViews.get(position));
return pageViews.get(position);
}
}
|
benhunter/ctf
|
htb/fatty-10.10.10.174/fatty-client/org/springframework/cglib/proxy/FixedValueGenerator.java
|
<gh_stars>0
/* */ package org.springframework.cglib.proxy;
/* */
/* */ import java.util.Iterator;
/* */ import java.util.List;
/* */ import org.springframework.asm.Type;
/* */ import org.springframework.cglib.core.ClassEmitter;
/* */ import org.springframework.cglib.core.CodeEmitter;
/* */ import org.springframework.cglib.core.MethodInfo;
/* */ import org.springframework.cglib.core.Signature;
/* */ import org.springframework.cglib.core.TypeUtils;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ class FixedValueGenerator
/* */ implements CallbackGenerator
/* */ {
/* 23 */ public static final FixedValueGenerator INSTANCE = new FixedValueGenerator();
/* */
/* 25 */ private static final Type FIXED_VALUE = TypeUtils.parseType("org.springframework.cglib.proxy.FixedValue");
/* */
/* 27 */ private static final Signature LOAD_OBJECT = TypeUtils.parseSignature("Object loadObject()");
/* */
/* */ public void generate(ClassEmitter ce, CallbackGenerator.Context context, List methods) {
/* 30 */ for (Iterator<MethodInfo> it = methods.iterator(); it.hasNext(); ) {
/* 31 */ MethodInfo method = it.next();
/* 32 */ CodeEmitter e = context.beginMethod(ce, method);
/* 33 */ context.emitCallback(e, context.getIndex(method));
/* 34 */ e.invoke_interface(FIXED_VALUE, LOAD_OBJECT);
/* 35 */ e.unbox_or_zero(e.getReturnType());
/* 36 */ e.return_value();
/* 37 */ e.end_method();
/* */ }
/* */ }
/* */
/* */ public void generateStatic(CodeEmitter e, CallbackGenerator.Context context, List methods) {}
/* */ }
/* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/cglib/proxy/FixedValueGenerator.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 1.1.3
*/
|
SolonProject/solon-web
|
apps/dev-tools/src/components/Sidebar/index.js
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './Sidebar.module.scss';
import SideOverlay from '../SideOverlay';
import Text from '../Text';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
const ModalContext = React.createContext({});
class TabIcon extends React.Component {
render() {
return (
<ModalContext.Consumer>
{({ activeTab, onTabClick }) => {
const { icon, tabKey, title } = this.props;
let tabStyle = styles.iconTab;
if (activeTab === tabKey) {
tabStyle += ` ${styles.active}`;
}
return (
<a
href="#toggle"
className={tabStyle}
onClick={() => (tabKey ? onTabClick(tabKey) : null)}
>
<FontAwesomeIcon icon={icon} className={styles.navIcon} />
{title && (
<Text className={styles.navText} typeScale="h4">
{title}
</Text>
)}
</a>
);
}}
</ModalContext.Consumer>
);
}
}
TabIcon.displayName = 'TabIcon';
class TabGroup extends React.Component {
render() {
return this.props.children;
}
}
TabGroup.displayName = 'TabGroup';
TabGroup.propTypes = {
children: PropTypes.arrayOf(function(propValue, key) {
for (let i = 0; i < propValue.length; i++) {
if (propValue[i].type.displayName !== TabIcon.displayName) {
return new Error('Children Must Be an Instance of TabIcon');
}
}
})
};
class Footer extends React.Component {
render() {
return this.props.children;
}
}
Footer.displayName = 'Footer';
TabIcon.propTypes = {
icon: PropTypes.object,
tabKey: PropTypes.string
};
class Sidebar extends React.Component {
state = {
activeTab: null
};
onTabClick = tabKey => {
this.setState({ activeTab: tabKey });
this.props.onTabClick(`/${tabKey}`);
};
render() {
const { activeTab: activeTabState } = this.state;
const {
defaultActiveTab,
className,
activeTab,
mobileVisible,
onMobileHide
} = this.props;
let footer, tabGroup;
const children = Array.isArray(this.props.children)
? this.props.children
: [this.props.children];
children.forEach(child => {
if (!child) {
return null;
}
const childName = child.type.displayName;
if (childName === Footer.displayName) {
footer = child;
}
if (childName === TabGroup.displayName) {
tabGroup = child;
}
});
const currentTab = activeTab || activeTabState || defaultActiveTab;
const sidebarBody = (
<ModalContext.Provider
value={{
activeTab: currentTab,
onTabClick: this.onTabClick
}}
>
<div className={`${styles.sidebar} ${className}`}>
<div className={styles.icons}>{tabGroup}</div>
<div className={styles.footer}>{footer}</div>
</div>
</ModalContext.Provider>
);
return (
<div>
<div className={styles.mobileSideNav}>
<SideOverlay visible={mobileVisible} onClose={onMobileHide}>
{sidebarBody}
</SideOverlay>
</div>
<div className={styles.desktopSideNav}>{sidebarBody}</div>
</div>
);
}
}
Sidebar.propTypes = {
children: PropTypes.arrayOf(function(propValue, key) {
for (let i = 0; i < propValue.length; i++) {
if (
// if child is a boolean then abort because it is the remnants of
// an expression that should not be displayed at this time
typeof propValue[i] !== 'boolean' &&
propValue[i].type.displayName !== TabGroup.displayName &&
propValue[i].type.displayName !== Footer.displayName
) {
return new Error('Children Must Be an Instance of TabGroup or Footer');
}
}
}),
className: PropTypes.string,
defaultActiveTab: PropTypes.string
};
Sidebar.defaultProps = {};
Sidebar.TabGroup = TabGroup;
Sidebar.Footer = Footer;
Sidebar.TabIcon = TabIcon;
export default Sidebar;
|
Toska29/auction-system
|
src/test/java/com/phoenix/auctionsystem/service/bid/BidServiceImplTest.java
|
<filename>src/test/java/com/phoenix/auctionsystem/service/bid/BidServiceImplTest.java
package com.phoenix.auctionsystem.service.bid;
import com.phoenix.auctionsystem.data.model.AppUser;
import com.phoenix.auctionsystem.data.model.Bid;
import com.phoenix.auctionsystem.data.model.Item;
import com.phoenix.auctionsystem.data.repository.AppUserRepository;
import com.phoenix.auctionsystem.data.repository.BidRepository;
import com.phoenix.auctionsystem.data.repository.ItemRepository;
import com.phoenix.auctionsystem.dto.request.BidRequestDto;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@Slf4j
class BidServiceImplTest {
@Mock
BidRepository bidRepository;
@Mock
AppUserRepository appUserRepository;
@Mock
ItemRepository itemRepository;
@Mock
Page<Bid> bidPage;
BidService bidService;
@BeforeEach
void setUp() {
bidService = new BidServiceImpl(bidRepository, appUserRepository, itemRepository);
}
@AfterEach
void tearDown() {
}
@SneakyThrows
@Test
void createBidTest() {
//given
BidRequestDto bidRequestDto = new BidRequestDto();
bidRequestDto.setBidPrice(100.0);
bidRequestDto.setBidderId(1L);
bidRequestDto.setItemId(1L);
AppUser lister = new AppUser();
lister.setId(1L);
lister.setEmail("<EMAIL>");
lister.setFirstName("Ahmad");
lister.setLastName("Samson");
lister.setAddress("Link");
AppUser bidder = new AppUser();
bidder.setId(1L);
bidder.setEmail("<EMAIL>");
bidder.setFirstName("Ahmad");
bidder.setLastName("Samson");
bidder.setAddress("Link");
Item item = new Item();
item.setId(1L);
item.setPrice(200.0);
item.setAppUser(lister);
item.setQuantity(1);
item.setName("backpack");
item.setDescription("school bag");
item.setDateCreated(LocalDateTime.now());
when(appUserRepository.findById(anyLong())).thenReturn(java.util.Optional.of(bidder));
when(itemRepository.findById(anyLong())).thenReturn(Optional.of(item));
//when
bidService.createBid(bidRequestDto);
//then
verify(appUserRepository).findById(anyLong());
verify(itemRepository).findById(anyLong());
verify(bidRepository).save(any(Bid.class));
}
@SneakyThrows
@Test
void findBidByItemTest() {
//given
Item item = new Item();
item.setId(1L);
item.setPrice(200.0);
item.setQuantity(1);
item.setName("backpack");
item.setDescription("school bag");
item.setDateCreated(LocalDateTime.now());
Pageable pageable = PageRequest.of(0, 10, Sort.by("dateCreated").descending());
when(itemRepository.findById(1L)).thenReturn(Optional.of(item));
when(bidRepository.findBidByItem(item, pageable)).thenReturn(bidPage);
//when
List<Bid> bidByItem = bidService.findBidByItem(1L, pageable);
//then
verify(bidRepository).findBidByItem(item, pageable);
}
@SneakyThrows
@Test
void findBidByBidderTest() {
//given
AppUser bidder = new AppUser();
bidder.setId(1L);
bidder.setEmail("<EMAIL>");
bidder.setFirstName("Ahmad");
bidder.setLastName("Samson");
bidder.setAddress("Link");
Pageable pageable = PageRequest.of(0, 10, Sort.by("dateCreated").descending());
when(appUserRepository.findById(1L)).thenReturn(Optional.of(bidder));
when(bidRepository.findBidByAppUser(bidder, pageable)).thenReturn(bidPage);
//when
List<Bid> bidByItem = bidService.findBidByBidder(1L, pageable);
//then
verify(bidRepository).findBidByAppUser(bidder, pageable);
}
}
|
JavaFamilyClub/jfoa
|
runner/src/main/java/club/javafamily/runner/common/filter/BaseFilter.java
|
/*
* Copyright (c) 2020, JavaFamily Technology Corp, All Rights Reserved.
*
* The software and information contained herein are copyrighted and
* proprietary to JavaFamily Technology Corp. This software is furnished
* pursuant to a written license agreement and may be used, copied,
* transmitted, and stored only in accordance with the terms of such
* license and with the inclusion of the above copyright notice. Please
* refer to the file "COPYRIGHT" for further copyright and licensing
* information. This software and information or any other copies
* thereof may not be provided or otherwise made available to any other
* person.
*/
package club.javafamily.runner.common.filter;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public abstract class BaseFilter <T extends FilterInfo<R>, R> implements Filter<T, R> {
public abstract void buildFilters(List<T> filterInfos);
@Override
public final List<T> filters() {
if(filterInfos == null) {
lock.lock();
try{
if(filterInfos == null) {
filterInfos = new ArrayList<>();
buildFilters(filterInfos);
}
}
finally {
lock.unlock();
}
}
return filterInfos;
}
@Override
public boolean accept(FilterInfo<T> filterInfo) {
List<T> filters = filters();
return !CollectionUtils.isEmpty(filters);
}
protected List<T> filterInfos;
private Lock lock = new ReentrantLock();
}
|
RaidAndFade/Penny
|
commands/admin/uptime.js
|
<reponame>RaidAndFade/Penny
exports.run = (client, message) => {
// How long have I been alive?
// Shout out to https://github.com/Gravebot/Gravebot/blob/master/src/commands/info/uptime.js for
// doing the math I didn't wanna do
let days = Math.floor(process.uptime() / (60 * 60 * 24));
let hours = Math.floor(process.uptime() / (60 * 60) % 24);
let minutes = Math.floor(process.uptime() % (60 * 60) / 60);
let seconds = Math.floor(process.uptime() % 60);
if (message)
message.channel.send(`My uptime: ${days} days ${hours} hours, ${minutes} minutes, and ${seconds} seconds.`);
else
return `${days} days ${hours} hours, ${minutes} minutes, and ${seconds} seconds.`;
};
exports.conf = {
name: 'uptime',
description: 'The amount of time node has been running.',
usage: 'uptime',
aliases: [],
};
|
francis-pouatcha/forgelab
|
adpharma/adpharma.modules/adpharma.client.frontoffice/src/main/java/org/adorsys/adpharma/client/jpa/packagingmode/PackagingModeController.java
|
package org.adorsys.adpharma.client.jpa.packagingmode;
import java.util.List;
import java.util.Map;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.adorsys.javafx.crud.extensions.DomainComponentController;
import org.adorsys.javafx.crud.extensions.EntityController;
import org.adorsys.javafx.crud.extensions.ViewType;
import org.adorsys.javafx.crud.extensions.events.CreateModelEvent;
import org.adorsys.javafx.crud.extensions.events.EntityCreateRequestedEvent;
import org.adorsys.javafx.crud.extensions.events.EntityEditCanceledEvent;
import org.adorsys.javafx.crud.extensions.events.EntityEditDoneEvent;
import org.adorsys.javafx.crud.extensions.events.EntityEditRequestedEvent;
import org.adorsys.javafx.crud.extensions.events.EntitySearchDoneEvent;
import org.adorsys.javafx.crud.extensions.events.EntitySearchRequestedEvent;
import org.adorsys.javafx.crud.extensions.events.EntitySelectionEvent;
import org.adorsys.javafx.crud.extensions.events.SearchModelEvent;
import org.adorsys.javafx.crud.extensions.events.SelectedModelEvent;
@Singleton
public class PackagingModeController extends DomainComponentController
{
@Inject
private PackagingModeSearchController searchController;
@Inject
private PackagingModeCreateController createController;
@Inject
private PackagingModeEditController editController;
@Inject
private PackagingModeListController listController;
@Inject
private PackagingModeDisplayController displayController;
@Inject
private PackagingModeIntialScreenController intialScreenController;
@Inject
@CreateModelEvent
private Event<PackagingMode> createModelEvent;
@Inject
@SearchModelEvent
private Event<PackagingMode> searchModelEvent;
@Inject
@SelectedModelEvent
private Event<PackagingMode> selectedModelEvent;
private PackagingMode createModel = new PackagingMode();
private PackagingMode searchModel = new PackagingMode();
private PackagingMode selectedModel = new PackagingMode();
@Inject
private PackagingModeRegistration registration;
@Override
protected void initViews(Map<ViewType, EntityController> entityViews)
{
entityViews.put(searchController.getViewType(), searchController);
entityViews.put(listController.getViewType(), listController);
entityViews.put(displayController.getViewType(), displayController);
entityViews.put(editController.getViewType(), editController);
entityViews.put(createController.getViewType(), createController);
createModelEvent.fire(createModel);
searchModelEvent.fire(searchModel);
selectedModelEvent.fire(selectedModel);
}
/**
* Listen to search result and display.
* @param entities
*/
public void handleSearchResult(@Observes @EntitySearchDoneEvent List<PackagingMode> entities)
{
if (!registration.canRead())
return;
// if result is empty: display no result.
if (!getDisplayedViews().contains(listController))
{
getDisplayedViews().add(listController);
}
displayComponent();
}
/**
* Listens to list selection events and display
*/
public void handleSelectionEvent(@Observes @EntitySelectionEvent PackagingMode selectedEntity)
{
if (!registration.canRead())
return;
// if result is empty: display no result.
// else display list of packagingModes.
List<EntityController> displayedViews = getDisplayedViews();
displayedViews.clear();
displayedViews.add(listController);
displayedViews.add(displayController);
displayComponent();
}
/**
* Display the search and list panel
* @param selectedEntity
*/
public void handleSearchRequestedEvent(@Observes @EntitySearchRequestedEvent PackagingMode selectedEntity)
{
if (!registration.canRead())
return;
List<EntityController> displayedViews = getDisplayedViews();
displayedViews.clear();
displayedViews.add(searchController);
displayedViews.add(listController);
displayComponent();
}
/**
* Display search form.
* @param selectedPackagingMode
*/
public void handleCreateRequestedEvent(@Observes @EntityCreateRequestedEvent PackagingMode templateEntity)
{
if (!registration.canCreate())
return;
List<EntityController> displayedViews = getDisplayedViews();
displayedViews.clear();
displayedViews.add(listController);
displayedViews.add(createController);
displayComponent();
}
public void handleEditRequestedEvent(@Observes @EntityEditRequestedEvent PackagingMode selectedEntity)
{
if (!registration.canEdit())
return;
List<EntityController> displayedViews = getDisplayedViews();
displayedViews.clear();
displayedViews.add(listController);
displayedViews.add(editController);
displayComponent();
}
public void handleEditCanceledEvent(@Observes @EntityEditCanceledEvent PackagingMode selectedEntity)
{
List<EntityController> displayedViews = getDisplayedViews();
displayedViews.clear();
displayedViews.add(listController);
displayedViews.add(displayController);
displayComponent();
}
public void handleEditDoneEvent(@Observes @EntityEditDoneEvent PackagingMode selectedEntity)
{
List<EntityController> displayedViews = getDisplayedViews();
displayedViews.clear();
displayedViews.add(listController);
displayedViews.add(displayController);
displayComponent();
}
@Override
protected void selectDisplay()
{
if (searchController != null)
{
intialScreenController.startWithSeach();
}
else if (createController != null)
{
intialScreenController.startWithCreate();
}
else
{
throw new IllegalStateException("Missing search and display component.");
}
}
@Override
public void reset() {
displayController.reset();
editController.reset();
searchController.reset();
listController.reset();
}
}
|
marcust/jzenith
|
jzenith-rest/src/main/java/org/jzenith/rest/tracing/RequestScopedScopeManager.java
|
<reponame>marcust/jzenith
/**
* Copyright © 2018 <NAME> (<EMAIL>)
*
* 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.jzenith.rest.tracing;
import io.opentracing.Scope;
import io.opentracing.ScopeManager;
import io.opentracing.Span;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
public class RequestScopedScopeManager implements ScopeManager {
@Override
public Scope activate(Span span) {
return new RequestScopedScope(this, false, span, getScope());
}
@Override
public Span activeSpan() {
final RequestScopedScope scope = getScope();
if (scope != null) {
return scope.activeSpan();
}
return null;
}
public RequestScopedScope getScope() {
return ResteasyProviderFactory.getContextData(RequestScopedScope.class);
}
public void setScope(RequestScopedScope requestScopedScope) {
ResteasyProviderFactory.pushContext(RequestScopedScope.class, requestScopedScope);
}
}
|
nianxiongdi/mpx
|
packages/webpack-plugin/lib/platform/template/wx/component-config/live-player.js
|
const TAG_NAME = 'live-player'
module.exports = function ({ print }) {
const baiduValueLogError = print({ platform: 'baidu', tag: TAG_NAME, isError: true, type: 'value' })
const baiduPropLog = print({ platform: 'baidu', tag: TAG_NAME, isError: false })
const baiduEventLog = print({ platform: 'baidu', tag: TAG_NAME, isError: false, type: 'event' })
const qqPropLog = print({ platform: 'qq', tag: TAG_NAME, isError: false })
const qqEventLog = print({ platform: 'qq', tag: TAG_NAME, isError: false, type: 'event' })
const ttEventLog = print({ platform: 'bytedance', tag: TAG_NAME, isError: false, type: 'event' })
const ttPropLog = print({ platform: 'bytedance', tag: TAG_NAME, isError: false })
return {
test: TAG_NAME,
props: [
{
test: 'mode',
swan ({ name, value }) {
// 百度只有直播模式,也就是微信的mode=live
if (value !== 'live') {
baiduValueLogError({ name, value })
}
return false
}
},
{
test: /^(sound-mode|auto-pause-if-navigate|auto-pause-if-open-native)$/,
swan: baiduPropLog
},
{
test: /^(background-mute|picture-in-picture-mode)$/,
qq: qqPropLog
},
{
test: /^(mode|background-mute|min-cache|max-cache|sound-mode|auto-pause-if-navigate|auto-pause-if-open-native)$/,
tt: ttPropLog
}
],
event: [
{
test: /^(audiovolumenotify|enterpictureinpicture|leavepictureinpicture)$/,
qq: qqEventLog,
swan: baiduEventLog
},
{
test: /^(netstatus|audiovolumenotify|enterpictureinpicture|leavepictureinpicture)$/,
tt: ttEventLog
}
]
}
}
|
KirIgor/csp-parser
|
spec/directive_value/source/scheme_spec.rb
|
# frozen_string_literal: true
describe CSPParser::DirectiveValue::Source::Scheme do
it "parses right scheme" do
nonce = CSPParser::DirectiveValue::Source::Scheme.new("example:")
expect(nonce.to_s).to eq("example:")
end
it "raises error if invalid scheme" do
expect do
CSPParser::DirectiveValue::Source::Scheme.new("??'")
end.to raise_error(CSPParser::DirectiveValue::InvalidSource)
end
end
|
DissoluteGao/xqoo-cloud-admin
|
xqoo-cloud-authorization/src/main/java/com/xqoo/authorization/controller/authentication/AuthentictionCenterController.java
|
<filename>xqoo-cloud-authorization/src/main/java/com/xqoo/authorization/controller/authentication/AuthentictionCenterController.java
package com.xqoo.authorization.controller.authentication;
import cn.hutool.core.util.ObjectUtil;
import com.xqoo.authorization.service.authentication.AuthenticationDefaultService;
import com.xqoo.common.core.config.JWTUtils;
import com.xqoo.common.core.entity.CurrentUser;
import com.xqoo.common.core.utils.StringUtils;
import com.xqoo.common.dto.AuthenDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/authen")
@Api(tags = "鉴权中心控制器(内部接口)")
@Validated
public class AuthentictionCenterController {
@Autowired
private AuthenticationDefaultService authentictionDefaultService;
@Autowired
private JWTUtils jwtUtils;
@GetMapping("/isLogin")
@ApiOperation(value = "查看是否已登录(内部接口)")
public AuthenDTO LoginStatus(@RequestParam(required = false) String token){
if(StringUtils.isEmpty(token)){
AuthenDTO dto = new AuthenDTO();
dto.setSuccess(false);
dto.setMessage("token丢失,请退出后重新登录");
dto.setStatus(HttpStatus.NOT_ACCEPTABLE);
}
return authentictionDefaultService.loginCheck(token);
}
@GetMapping("/getLoginUserInfo")
@ApiOperation(value = "获取已登录用户基本信息(内部接口)")
public CurrentUser getLoginUserInfo(@RequestParam(required = false, value = "token") String token){
if(StringUtils.isEmpty(token)){
return new CurrentUser();
}
CurrentUser currentUser = authentictionDefaultService.getUserBaseInfo(token);
if(currentUser == null){
return new CurrentUser();
}
return currentUser;
}
}
|
rexlManu/mlgrush
|
plugin/src/main/java/de/rexlmanu/mlgrush/plugin/game/npc/InteractiveMob.java
|
<filename>plugin/src/main/java/de/rexlmanu/mlgrush/plugin/game/npc/InteractiveMob.java<gh_stars>1-10
package de.rexlmanu.mlgrush.plugin.game.npc;
import de.rexlmanu.mlgrush.plugin.GamePlugin;
import de.rexlmanu.mlgrush.plugin.player.PlayerProvider;
import de.rexlmanu.mlgrush.plugin.utility.NoAI;
import de.rexlmanu.mlgrush.plugin.utility.hologram.Hologram;
import eu.miopowered.packetlistener.reflection.PacketReflection;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import java.util.List;
public class InteractiveMob implements Runnable, Listener {
private Entity entity;
private BukkitTask viewTask;
private Hologram hologram;
private Location location;
private final EntityType type;
private List<String> lines;
private final InteractionHandler listener;
public InteractiveMob(EntityType type, List<String> lines, InteractionHandler listener) {
this.type = type;
this.lines = lines;
this.listener = listener;
}
public InteractiveMob create(Location location) {
this.location = location;
return this.spawn();
}
public InteractiveMob spawn() {
this.entity = location.getWorld().spawnEntity(location, this.type);
NoAI.setEntityAi(this.entity, false);
this.hologram = new Hologram(this.lines, location.clone().add(0, 0.6, 0));
JavaPlugin plugin = GamePlugin.getProvidingPlugin(GamePlugin.class);
this.viewTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this, 0, 1);
Bukkit.getPluginManager().registerEvents(this, plugin);
return this;
}
public void remove() {
this.viewTask.cancel();
this.entity.remove();
this.hologram.delete();
HandlerList.unregisterAll(this);
}
@Override
public void run() {
Bukkit.getOnlinePlayers()
.stream()
.filter(player -> player.getLocation().getWorld().equals(entity.getWorld()))
.filter(player -> player.getLocation().distance(entity.getLocation()) < 5)
.forEach(player -> {
Vector direction = entity.getLocation().toVector().subtract(player.getLocation().toVector()).normalize();
try {
Object nmsPlayer = player.getClass().getMethod("getHandle").invoke(player);
Object playerConnection = nmsPlayer.getClass().getField("playerConnection").get(nmsPlayer);
Object entityLookPacket = PacketReflection.nmsClass("PacketPlayOutEntity$PacketPlayOutEntityLook")
.getConstructor(int.class, byte.class, byte.class, boolean.class
).newInstance(
this.entity.getEntityId(),
toPackedByte((float) (180 - Math.toDegrees(Math.atan2(direction.getX(), direction.getZ())))),
toPackedByte((float) (90 - Math.toDegrees(Math.acos(direction.getY())))),
true
);
Location location = entity.getLocation();
location.setDirection(direction);
location.setYaw((float) (180 - Math.toDegrees(Math.atan2(direction.getX(), direction.getZ()))));
location.setPitch((float) (90 - Math.toDegrees(Math.acos(direction.getY()))));
Object packetPlayOutEntityTeleport = PacketReflection.nmsClass("PacketPlayOutEntityTeleport")
.getConstructor(int.class, int.class, int.class, int.class, byte.class, byte.class, boolean.class)
.newInstance(
this.entity.getEntityId(),
floor(location.getX() * 32D),
floor(location.getY() * 32D),
floor(location.getZ() * 32D),
toPackedByte(location.getYaw()),
toPackedByte(location.getPitch()),
true
);
playerConnection.getClass().getMethod("sendPacket", PacketReflection.nmsClass("Packet")).invoke(playerConnection, packetPlayOutEntityTeleport);
playerConnection.getClass().getMethod("sendPacket", PacketReflection.nmsClass("Packet")).invoke(playerConnection, entityLookPacket);
} catch (Exception e) {
e.printStackTrace();
}
});
}
@EventHandler
public void handle(PlayerInteractEntityEvent event) {
if (event.getRightClicked().equals(this.entity)) {
event.setCancelled(true);
PlayerProvider.find(event.getPlayer().getUniqueId()).ifPresent(this.listener::handle);
}
}
private byte toPackedByte(float f) {
return (byte) ((int) (f * 256.0F / 360.0F));
}
public static int floor(double var0) {
int var2 = (int) var0;
return var0 < (double) var2 ? var2 - 1 : var2;
}
}
|
hanstrompert/nsi-dds
|
src/main/java/net/es/nsi/dds/config/http/HttpsConfig.java
|
package net.es.nsi.dds.config.http;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.net.ssl.SSLContext;
import net.es.nsi.dds.config.Properties;
import net.es.nsi.dds.jaxb.configuration.KeyStoreType;
import net.es.nsi.dds.jaxb.configuration.ObjectFactory;
import net.es.nsi.dds.jaxb.configuration.SecureType;
import org.glassfish.jersey.SslConfigurator;
public class HttpsConfig {
private final ObjectFactory factory = new ObjectFactory();
private String basedir;
private SecureType config;
public HttpsConfig(SecureType config) throws IOException {
if (config == null) {
throw new IllegalArgumentException("HttpConfig: server configuration not provided");
}
// We will use the application basedir to fully qualify any relative paths.
basedir = System.getProperty(Properties.SYSTEM_PROPERTY_BASEDIR);
// Determine the keystore configuration.
KeyStoreType keyStore = config.getKeyStore();
if (keyStore == null) {
// Check to see if the keystore was provided on the commandline.
keyStore = factory.createKeyStoreType();
keyStore.setFile(System.getProperty(Properties.SYSTEM_PROPERTY_SSL_KEYSTORE, Properties.DEFAULT_SSL_KEYSTORE));
keyStore.setPassword(System.getProperty(Properties.SYSTEM_PROPERTY_SSL_KEYSTORE_PASSWORD, Properties.DEFAULT_SSL_KEYSTORE_PASSWORD));
keyStore.setType(System.getProperty(Properties.SYSTEM_PROPERTY_SSL_KEYSTORE_TYPE, Properties.DEFAULT_SSL_KEYSTORE_TYPE));
}
keyStore.setFile(getAbsolutePath(keyStore.getFile()));
KeyStoreType trustStore = config.getTrustStore();
if (trustStore == null) {
trustStore = factory.createKeyStoreType();
trustStore.setFile(System.getProperty(Properties.SYSTEM_PROPERTY_SSL_TRUSTSTORE, Properties.DEFAULT_SSL_TRUSTSTORE));
trustStore.setPassword(System.getProperty(Properties.SYSTEM_PROPERTY_SSL_TRUSTSTORE_PASSWORD, Properties.DEFAULT_SSL_TRUSTSTORE_PASSWORD));
trustStore.setType(System.getProperty(Properties.SYSTEM_PROPERTY_SSL_TRUSTSTORE_TYPE, Properties.DEFAULT_SSL_TRUSTSTORE_TYPE));
}
trustStore.setFile(getAbsolutePath(trustStore.getFile()));
this.config = config;
}
private String getAbsolutePath(String inPath) throws IOException {
Path outPath = Paths.get(inPath);
if (!outPath.isAbsolute()) {
outPath = Paths.get(basedir, inPath);
}
return outPath.toRealPath().toString();
}
public SSLContext getSSLContext() {
SslConfigurator sslConfig = SslConfigurator.newInstance()
.trustStoreFile(config.getTrustStore().getFile())
.trustStorePassword(config.getTrustStore().getPassword())
.trustStoreType(config.getTrustStore().getType())
.keyStoreFile(config.getKeyStore().getFile())
.keyPassword(config.getKeyStore().getPassword())
.keyStoreType(config.getKeyStore().getType())
.securityProtocol("TLS");
return sslConfig.createSSLContext();
}
public boolean isProduction() {
return config.isProduction();
}
public int getMaxConnPerRoute() { return config.getMaxConnPerRoute(); }
public int getMaxConnTotal() { return config.getMaxConnTotal(); }
}
|
DamienFremont/blog
|
20141214-todoapp-javascript/routes/todoRepository.js
|
var datas = [ {
title : "task 1 from backend",
completed : false
}, {
title : "task 2 from backend",
completed : false
} ];
exports.findAll = function() {
return datas;
};
exports.updateAll = function(newDatas) {
datas = newDatas;
};
|
ramrod-project/database-brain
|
schema/test_schema_plugin.py
|
"""
"""
from .brain.checks import verify
from .brain import brain_pb2 as b
from uuid import uuid4
from copy import deepcopy
plugin1_controller = {
"id": "1-1-A",
"Name": "Plugin1",
"ServiceName": str(uuid4()),
"State": "Available",
"DesiredState": "",
"OS": "posix",
"Interface": "172.16.31.10",
"ExternalPorts": ["9999/tcp"],
"InternalPorts": ["9999/tcp"],
"Environment": ["STAGE=DEV"]
}
plugin1_controller_empty_ports = {
"id": "1-1-A",
"Name": "Plugin1",
"ServiceName": str(uuid4()),
"State": "Available",
"DesiredState": "",
"OS": "posix",
"Interface": "172.16.31.10",
"ExternalPorts": [],
"InternalPorts": [],
"Environment": ["STAGE=DEV"]
}
def test_good_plugin():
assert verify(plugin1_controller, b.Plugin())
def test_empty_ports():
assert verify(plugin1_controller_empty_ports, b.Plugin())
def test_no_id():
p = deepcopy(plugin1_controller)
del p['id']
assert verify(p, b.Plugin())
def test_no_name():
p = deepcopy(plugin1_controller)
del p['Name']
assert not verify(p, b.Plugin())
def test_no_servicename():
p = deepcopy(plugin1_controller)
del p['ServiceName']
assert not verify(p, b.Plugin())
def test_no_state():
p = deepcopy(plugin1_controller)
del p['State']
assert not verify(p, b.Plugin())
def test_no_dstate():
p = deepcopy(plugin1_controller)
del p['DesiredState']
assert not verify(p, b.Plugin())
def test_no_os():
p = deepcopy(plugin1_controller)
del p['OS']
assert not verify(p, b.Plugin())
def test_no_if():
p = deepcopy(plugin1_controller)
del p['Interface']
assert not verify(p, b.Plugin())
def test_no_ports():
p = deepcopy(plugin1_controller)
del p['ExternalPorts']
assert not verify(p, b.Plugin())
def test_no_iports():
p = deepcopy(plugin1_controller)
del p['InternalPorts']
assert not verify(p, b.Plugin())
def test_bad_ports():
p = deepcopy(plugin1_controller)
p['ExternalPorts'] = ["9333"]
assert not verify(p, b.Plugin())
def test_bad_iports():
p = deepcopy(plugin1_controller)
p['InternalPorts'] = ["9333"]
assert not verify(p, b.Plugin())
def test_matched_ports():
p = deepcopy(plugin1_controller)
p['ExternalPorts'] = ["9333/tcp"]
p['InternalPorts'] = ["9333/tcp"]
assert verify(p, b.Plugin())
def test_mismatched_ports():
p = deepcopy(plugin1_controller)
p['ExternalPorts'] = ["9333/tcp"]
p['InternalPorts'] = ["3339/tcp"]
assert verify(p, b.Plugin())
def test_bad_length_ports():
p = deepcopy(plugin1_controller)
p['ExternalPorts'] = ["9333/tcp"]
p['InternalPorts'] = ["2400/tcp", "4200/tcp"]
assert not verify(p, b.Plugin())
def test_bad_length_ports():
p = deepcopy(plugin1_controller)
p['ExternalPorts'] = ["9333/tcp", "4200/tcp"]
p['InternalPorts'] = ["2400/tcp"]
assert not verify(p, b.Plugin())
def test_no_envs():
p = deepcopy(plugin1_controller)
del (p['Environment'])
assert not verify(p, b.Plugin())
def test_no_value_envs():
p = deepcopy(plugin1_controller)
p['Environment'] = ["key="]
assert not verify(p, b.Plugin())
def test_no_key_envs():
p = deepcopy(plugin1_controller)
p['Environment'] = ["=value"]
assert not verify(p, b.Plugin())
def test_duplicate_keys_overwrite_ok_envs():
p = deepcopy(plugin1_controller)
p['Environment'] = ["key1=value", "key1=value2"]
# should expect env to be set with key1=value2 in this case
assert verify(p, b.Plugin())
|
invinst/CPDB
|
share/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_extensions.db.fields.json
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Session',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),
('title', models.CharField(max_length=255)),
('query', django_extensions.db.fields.json.JSONField()),
('share_count', models.IntegerField(default=0)),
('share_from', models.ForeignKey(default=None, to='share.Session', null=True)),
],
),
]
|
urchinpro/L2-forms
|
rmis_integration/management/commands/rmis_org_title.py
|
from django.core.management import BaseCommand
from rmis_integration.client import Client
class Command(BaseCommand):
help = "Получение названия организации"
def add_arguments(self, parser):
parser.add_argument('id', type=int)
def handle(self, *args, **options):
c = Client()
self.stdout.write(str(c.get_organization_title(options["id"], full=True)))
self.stdout.write(str(c.get_organization_title(options["id"])))
|
applefighting/babygo.github.io
|
client/node_modules/@cycle/html/lib/es6/index.js
|
<filename>client/node_modules/@cycle/html/lib/es6/index.js
export { HTMLSource } from './HTMLSource';
/**
* A factory for the HTML driver function.
*
* Takes an `effect` callback function and an `options` object as arguments. The
* input to this driver is a stream of virtual DOM objects, or in other words,
* Snabbdom "VNode" objects. The output of this driver is a "DOMSource": a
* collection of Observables queried with the methods `select()` and `events()`.
*
* The HTML Driver is supplementary to the DOM Driver. Instead of producing
* elements on the DOM, it generates HTML as strings and does a side effect on
* those HTML strings. That side effect is described by the `effect` callback
* function. So, if you want to use the HTML Driver on the server-side to render
* your application as HTML and send as a response (which is the typical use
* case for the HTML Driver), you need to pass something like the
* `html => response.send(html)` function as the `effect` argument. This way,
* the driver knows what side effect to cause based on the HTML string it just
* rendered.
*
* The HTML driver is useful only for that side effect in the `effect` callback.
* It can be considered a sink-only driver. However, in order to serve as a
* transparent replacement to the DOM Driver when rendering from the server, the
* HTML driver returns a source object that behaves just like the DOMSource.
* This helps reuse the same application that is written for the DOM Driver.
* This fake DOMSource returns empty streams when you query it, because there
* are no user events on the server.
*
* `DOMSource.select(selector)` returns a new DOMSource with scope restricted to
* the element(s) that matches the CSS `selector` given.
*
* `DOMSource.events(eventType, options)` returns an empty stream. The returned
* stream is an *xstream* Stream if you use `@cycle/xstream-run` to run your app
* with this driver, or it is an RxJS Observable if you use `@cycle/rxjs-run`,
* and so forth.
*
* `DOMSource.elements()` returns the stream of HTML string rendered from your
* sink stream of virtual DOM. The alternative method `DOMSource.element()` does
* the same (it only exists to be compatible with DOMSource from `@cycle/dom`).
*
* @param {Function} effect a callback function that takes a string of rendered
* HTML as input and should run a side effect, returning nothing.
* @param {HTMLDriverOptions} options an object with one optional property:
* `transposition: boolean` enables/disables transposition of inner streams in
* the virtual DOM tree.
* @return {Function} the HTML driver function. The function expects a stream of
* VNode as input, and outputs the DOMSource object.
* @function makeHTMLDriver
*/
export { makeHTMLDriver } from './makeHTMLDriver';
//# sourceMappingURL=index.js.map
|
inorangestylee/lsvmtools
|
lsvmload/bootbio.c
|
/*
**==============================================================================
**
** LSVMTools
**
** MIT License
**
** Copyright (c) Microsoft Corporation. All rights reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE
**
**==============================================================================
*/
#include "bootbio.h"
#include <lsvmutils/alloc.h>
#include <lsvmutils/blkdev.h>
#include <lsvmutils/luksblkdev.h>
#include <lsvmutils/efiblkdev.h>
#include <lsvmutils/efibio.h>
#include "luksbio.h"
#include "globals.h"
#include "trace.h"
#include "devpath.h"
#include "diskbio.h"
#include "logging.h"
#include "bootfs.h"
#include "initrd.h"
typedef struct _BlockIO
{
EFI_BLOCK_IO base;
EFI_BLOCK_IO_MEDIA media;
Blkdev* dev;
}
BlockIO;
static EFI_STATUS EFIAPI _EFI_BLOCK_IO_Reset(
IN struct _EFI_BLOCK_IO *this,
IN BOOLEAN ExtendedVerification)
{
return EFI_SUCCESS;
}
static EFI_STATUS EFIAPI _EFI_BLOCK_IO_ReadBlocks(
IN struct _EFI_BLOCK_IO *this,
IN UINT32 mediaId,
IN EFI_LBA lba,
IN UINTN bufferSize,
OUT VOID *buffer)
{
EFI_STATUS status = EFI_UNSUPPORTED;
BlockIO* impl = (BlockIO*)this;
if (!impl || !buffer)
goto done;
if (BlkdevRead(impl->dev, lba, buffer, bufferSize) != 0)
goto done;
#if 0
if (bufferSize >= BLKDEV_BLKSIZE)
{
SHA1Hash sha1;
char path[PATH_MAX];
ComputeSHA1(buffer, BLKDEV_BLKSIZE, &sha1);
if (MatchInitrdPathByHash(&sha1, path) == 0)
{
LOGI(L"Matched1: lba=%ld path=%a", (unsigned long)lba, Str(path));
}
if (MatchInitrdPathByLBA(lba, path) == 0)
{
LOGI(L"Matched2: lba=%ld path=%a", (unsigned long)lba, Str(path));
}
}
#endif
status = EFI_SUCCESS;
done:
return status;
}
static EFI_STATUS EFIAPI _EFI_BLOCK_IO_WriteBlocks(
IN struct _EFI_BLOCK_IO *this,
IN UINT32 mediaId,
IN EFI_LBA lba,
IN UINTN bufferSize,
IN VOID *buffer)
{
EFI_STATUS status = EFI_UNSUPPORTED;
BlockIO* impl = (BlockIO*)this;
if (!impl || !buffer)
goto done;
if (BlkdevWrite(impl->dev, lba, buffer, bufferSize) != 0)
goto done;
status = EFI_SUCCESS;
done:
return status;
}
static EFI_STATUS EFIAPI _EFI_BLOCK_IO_FlushBlocks(
IN struct _EFI_BLOCK_IO *this)
{
return EFI_SUCCESS;
}
static BlockIO _block_io =
{
{
1, /* Revision */
NULL, /* Media */
_EFI_BLOCK_IO_Reset,
_EFI_BLOCK_IO_ReadBlocks,
_EFI_BLOCK_IO_WriteBlocks,
_EFI_BLOCK_IO_FlushBlocks,
},
};
EFI_STATUS WrapBootBIO(
EFI_HANDLE imageHandle,
EFI_TCG2_PROTOCOL* tcg2Protocol,
const UINT8* masterkeyData,
UINTN masterkeySize)
{
EFI_STATUS status = EFI_UNSUPPORTED;
EFI_STATUS rc;
EFI_GUID guid;
EFI_DEVICE_PATH* dp = NULL;
UINT64 firstLBA = 0;
UINT64 lastLBA = 0;
EFI_HANDLE handle = NULL;
Blkdev* bootdev = NULL;
/* Check parameters */
if (!imageHandle || !masterkeyData || !masterkeySize)
goto done;
/* Get boot device */
if (!(bootdev = GetBootDevice(
imageHandle,
tcg2Protocol,
masterkeyData,
masterkeySize)))
{
LOGE(L"WrapBootBIO(): GetBootDevice() failed");
goto done;
}
/* Copy over media from LUKS parition */
Memcpy(
&_block_io.media,
globals.bootbio->blockIO->Media,
sizeof(EFI_BLOCK_IO_MEDIA));
_block_io.base.Media = &_block_io.media;
/* Set EFI_BLOCK_IO_MEDIA.LastBlock */
{
union
{
LUKSHeader header;
UINT8 blocks[LUKS_SECTOR_SIZE*2];
}
u;
static UINT8 _magic[LUKS_MAGIC_SIZE] = LUKS_MAGIC_INITIALIZER;
/* Read the LUKS header (blkno == 0) */
if (ReadBIO(globals.bootbio, 0, &u, sizeof(u)) != EFI_SUCCESS)
{
LOGE(L"WrapBootBIO(): ReadBIO() failed");
goto done;
}
/* Check the magic number */
if (Memcmp(u.header.magic, _magic, sizeof(_magic)) != 0)
{
LOGE(L"WrapBootBIO(): bad LUK magic");
goto done;
}
/* Fix the byte order of the hader */
LUKSFixByteOrder(&u.header);
/* Adjust the last block field (omit leading LUKS metadata) */
_block_io.media.LastBlock -= u.header.payload_offset;
}
/* Set the function pointers */
_block_io.base.Reset = _EFI_BLOCK_IO_Reset;
_block_io.base.ReadBlocks = _EFI_BLOCK_IO_ReadBlocks;
_block_io.base.WriteBlocks = _EFI_BLOCK_IO_WriteBlocks;
_block_io.base.FlushBlocks = _EFI_BLOCK_IO_FlushBlocks;
_block_io.dev = bootdev;
#if 0
/* Use the guid from the boot file system */
if (globals.bootfs)
{
LogHexStr(L"EXT2-GUID", globals.bootfs->sb.s_uuid,
sizeof(globals.bootfs->sb.s_uuid));
MakeGUIDFromBytes(&guid, globals.bootfs->sb.s_uuid);
}
#endif
/* Allocate device path for this new parition */
if (!(dp = DevPathCreatePseudoPartition(
_block_io.media.LastBlock,
&guid,
&firstLBA,
&lastLBA)))
{
LOGE(L"WrapBootBIO(): DevPathCreatePseudoPartition() failed");
goto done;
}
LOGI(L"Mapped pseudo partition: firstLBA=%d lastLBA=%d",
(int)firstLBA, (int)lastLBA);
/* Install new EFI_BLOCK_IO (assigns new handle) */
{
static EFI_GUID protocol = BLOCK_IO_PROTOCOL;
if ((rc = uefi_call_wrapper(
BS->InstallProtocolInterface,
4,
&handle,
&protocol,
EFI_NATIVE_INTERFACE,
&_block_io)) != EFI_SUCCESS)
{
LOGE(L"WrapBootBIO(): InstallProtocolInterface(1) failed");
goto done;
}
}
/* Install new DEVICE_PATH protocol interface */
{
static EFI_GUID protocol = DEVICE_PATH_PROTOCOL;
if ((rc = uefi_call_wrapper(
BS->InstallProtocolInterface,
4,
&handle,
&protocol,
EFI_NATIVE_INTERFACE,
dp)) != EFI_SUCCESS)
{
LOGE(L"WrapBootBIO(): InstallProtocolInterface(2) failed");
goto done;
}
}
/* Add this new parition to the GPT */
if (AddPartition(L"BOOTFS", &guid, firstLBA, lastLBA) != 0)
{
LOGE(L"WrapBootBIO(): AddPartition() failed");
goto done;
}
/* Add a region so diskbio will find this data */
if (AddRegion(
REGION_ID_BOOT,
firstLBA,
lastLBA,
lastLBA - firstLBA + 1,
FALSE, /* readOnly */
NULL,
&_block_io.base) != 0)
{
LOGE(L"WrapBootBIO(): AddRegion() failed");
goto done;
}
status = EFI_SUCCESS;
done:
return status;
}
|
bzhaoopenstack/hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ErasureCoderOptions.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.io.erasurecode;
import org.apache.hadoop.classification.InterfaceAudience;
/**
* Erasure coder configuration that maintains schema info and coder options.
*/
@InterfaceAudience.Private
public final class ErasureCoderOptions {
private final int numDataUnits;
private final int numParityUnits;
private final int numAllUnits;
private final boolean allowChangeInputs;
private final boolean allowVerboseDump;
public ErasureCoderOptions(int numDataUnits, int numParityUnits) {
this(numDataUnits, numParityUnits, false, false);
}
public ErasureCoderOptions(int numDataUnits, int numParityUnits,
boolean allowChangeInputs, boolean allowVerboseDump) {
this.numDataUnits = numDataUnits;
this.numParityUnits = numParityUnits;
this.numAllUnits = numDataUnits + numParityUnits;
this.allowChangeInputs = allowChangeInputs;
this.allowVerboseDump = allowVerboseDump;
}
/**
* The number of data input units for the coding. A unit can be a byte,
* chunk or buffer or even a block.
* @return count of data input units
*/
public int getNumDataUnits() {
return numDataUnits;
}
/**
* The number of parity output units for the coding. A unit can be a byte,
* chunk, buffer or even a block.
* @return count of parity output units
*/
public int getNumParityUnits() {
return numParityUnits;
}
/**
* The number of all the involved units in the coding.
* @return count of all the data units and parity units
*/
public int getNumAllUnits() {
return numAllUnits;
}
/**
* Allow changing input buffer content (not positions). Maybe better
* performance if not allowed.
* @return true if allowing input content to be changed, false otherwise
*/
public boolean allowChangeInputs() {
return allowChangeInputs;
}
/**
* Allow dump verbose debug info or not.
* @return true if verbose debug info is desired, false otherwise
*/
public boolean allowVerboseDump() {
return allowVerboseDump;
}
}
|
Aaron1011/Glowstone
|
src/main/java/net/glowstone/net/message/play/game/MapDataMessage.java
|
package net.glowstone.net.message.play.game;
import com.flowpowered.networking.Message;
import org.apache.commons.lang.Validate;
import java.util.List;
public final class MapDataMessage implements Message {
private final int id, scale;
private final List<Icon> icons;
private final Section section;
public MapDataMessage(int id, int scale, List<Icon> icons, Section section) {
this.id = id;
this.scale = scale;
this.icons = icons;
this.section = section;
}
public int getId() {
return id;
}
public int getScale() {
return scale;
}
public List<Icon> getIcons() {
return icons;
}
public Section getSection() {
return section;
}
@Override
public String toString() {
return "MapDataMessage{" +
"id=" + id +
", scale=" + scale +
", icons=" + icons +
", section=" + section +
'}';
}
public static class Icon {
public final int type, facing, x, y;
public Icon(int type, int facing, int x, int y) {
this.type = type;
this.facing = facing;
this.x = x;
this.y = y;
}
}
public static class Section {
public final int width, height, x, y;
public final byte[] data;
public Section(int width, int height, int x, int y, byte[] data) {
Validate.isTrue(width * height == data.length, "width * height == data.length");
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.data = data;
}
}
}
|
RobotGuide/RobotGuideProject
|
Servercpp/ServerCPP/ServerCPP/include/robotguide/Communication/TransportLayer/IRouteRequester.h
|
<filename>Servercpp/ServerCPP/ServerCPP/include/robotguide/Communication/TransportLayer/IRouteRequester.h
#ifndef ROBOTGUIDE_COMMUNICATION_TRANSPORTLAYER_IROUTEREQUESTER_H
#define ROBOTGUIDE_COMMUNICATION_TRANSPORTLAYER_IROUTEREQUESTER_H
#include <string>
namespace robotguide::com::transportlayer
{
class IRouteRequester
{
public:
virtual ~IRouteRequester() = default;
/// <summary>
/// Handle a message from the transport layer
/// </summary>
/// <param name="message">The message you need to handle</param>
virtual std::string HandleMessage(const std::string& message) = 0;
};
}
#endif
|
itcastopen/itcast-sms
|
itcast-sms-server/src/main/java/com/itheima/sms/redismq/HighServerReceiver.java
|
package com.itheima.sms.redismq;
import com.itheima.sms.factory.SmsConnectLoader;
import com.itheima.sms.model.ServerTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
/**
* 高优先级队列
*/
@Component
@Slf4j
public class HighServerReceiver implements MessageListener {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private SmsConnectLoader smsConnectLoader;
@Override
public void onMessage(Message message, byte[] pattern) {
RedisSerializer<?> valueSerializer = redisTemplate.getDefaultSerializer();
String deserialize = valueSerializer.deserialize(message.getBody()).toString();
log.info("收到的服务id消息:{}", deserialize);
ServerTopic serverTopic = ServerTopic.load(deserialize);
switch (serverTopic.getOption()) {
case ServerTopic.USE_NEW_CONNECT: //应用通道连接池
log.info("服务:{} ,发起新连接应用", serverTopic.getValue());
smsConnectLoader.changeNewConnect();
break;
case ServerTopic.INIT_CONNECT: //创建通道连接池
log.info("服务:{} ,发起新连接初始化", serverTopic.getValue());
smsConnectLoader.initConnect();
break;
default:
break;
}
}
}
|
kuyacai/BroadleafCommerce
|
integration/src/test/java/org/broadleafcommerce/core/offer/service/legacy/LegacyOfferServiceTest.java
|
/*
* #%L
* BroadleafCommerce Integration
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.core.offer.service.legacy;
import org.broadleafcommerce.common.money.Money;
import org.broadleafcommerce.core.catalog.domain.Sku;
import org.broadleafcommerce.core.catalog.domain.SkuImpl;
import org.broadleafcommerce.core.catalog.service.CatalogService;
import org.broadleafcommerce.core.offer.domain.Offer;
import org.broadleafcommerce.core.offer.domain.OfferItemCriteria;
import org.broadleafcommerce.core.offer.service.OfferDataItemProvider;
import org.broadleafcommerce.core.offer.service.OfferService;
import org.broadleafcommerce.core.offer.service.type.OfferDiscountType;
import org.broadleafcommerce.core.order.domain.DiscreteOrderItem;
import org.broadleafcommerce.core.order.domain.DiscreteOrderItemImpl;
import org.broadleafcommerce.core.order.domain.FulfillmentGroup;
import org.broadleafcommerce.core.order.domain.FulfillmentGroupImpl;
import org.broadleafcommerce.core.order.domain.FulfillmentGroupItem;
import org.broadleafcommerce.core.order.domain.FulfillmentGroupItemImpl;
import org.broadleafcommerce.core.order.domain.GiftWrapOrderItem;
import org.broadleafcommerce.core.order.domain.GiftWrapOrderItemImpl;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.domain.OrderItem;
import org.broadleafcommerce.core.order.service.OrderItemService;
import org.broadleafcommerce.core.order.service.OrderService;
import org.broadleafcommerce.core.order.service.type.OrderItemType;
import org.broadleafcommerce.core.pricing.service.exception.PricingException;
import org.broadleafcommerce.core.pricing.service.workflow.type.ShippingServiceType;
import org.broadleafcommerce.profile.core.domain.Address;
import org.broadleafcommerce.profile.core.domain.AddressImpl;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.service.CustomerService;
import org.broadleafcommerce.test.legacy.LegacyCommonSetupBaseTest;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.Test;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
public class LegacyOfferServiceTest extends LegacyCommonSetupBaseTest {
@Resource
protected OfferService offerService;
@Resource(name = "blOrderService")
protected OrderService orderService;
@Resource
protected CustomerService customerService;
@Resource
protected CatalogService catalogService;
@Resource(name = "blOrderItemService")
protected OrderItemService orderItemService;
private Order createTestOrderWithOfferAndGiftWrap() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.createNewCartForCustomer(customer);
customerService.saveCustomer(order.getCustomer());
createCountry();
createState();
Address address = new AddressImpl();
address.setAddressLine1("123 Test Rd");
address.setCity("Dallas");
address.setFirstName("Jeff");
address.setLastName("Fischer");
address.setPostalCode("75240");
address.setPrimaryPhone("972-978-9067");
address.setState(stateService.findStateByAbbreviation("KY"));
address.setCountry(countryService.findCountryByAbbreviation("US"));
address.setIsoCountrySubdivision("US-KY");
address.setIsoCountryAlpha2(isoService.findISOCountryByAlpha2Code("US"));
FulfillmentGroup group = new FulfillmentGroupImpl();
group.setAddress(address);
group.setIsShippingPriceTaxable(true);
List<FulfillmentGroup> groups = new ArrayList<FulfillmentGroup>();
group.setMethod("standard");
group.setService(ShippingServiceType.BANDED_SHIPPING.getType());
group.setShippingPrice(new Money("0"));
group.setOrder(order);
groups.add(group);
group.setTotal(new Money(0));
order.setFulfillmentGroups(groups);
Money total = new Money(5D);
group.setRetailShippingPrice(total);
group.setShippingPrice(total);
DiscreteOrderItem item1;
{
item1 = new DiscreteOrderItemImpl();
Sku sku = new SkuImpl();
sku.setName("Test Sku");
sku.setRetailPrice(new Money(10D));
sku.setDiscountable(true);
sku = catalogService.saveSku(sku);
item1.setSku(sku);
item1.setQuantity(2);
item1.setOrder(order);
item1.setOrderItemType(OrderItemType.DISCRETE);
item1 = (DiscreteOrderItem) orderItemService.saveOrderItem(item1);
order.addOrderItem(item1);
FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl();
fgItem.setFulfillmentGroup(group);
fgItem.setOrderItem(item1);
fgItem.setQuantity(2);
//fgItem.setPrice(new Money(0D));
group.addFulfillmentGroupItem(fgItem);
}
{
DiscreteOrderItem item = new DiscreteOrderItemImpl();
Sku sku = new SkuImpl();
sku.setName("Test Product 2");
sku.setRetailPrice(new Money(20D));
sku.setDiscountable(true);
sku = catalogService.saveSku(sku);
item.setSku(sku);
item.setQuantity(1);
item.setOrder(order);
item.setOrderItemType(OrderItemType.DISCRETE);
item = (DiscreteOrderItem) orderItemService.saveOrderItem(item);
order.addOrderItem(item);
FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl();
fgItem.setFulfillmentGroup(group);
fgItem.setOrderItem(item);
fgItem.setQuantity(1);
//fgItem.setPrice(new Money(0D));
group.addFulfillmentGroupItem(fgItem);
}
{
GiftWrapOrderItem item = new GiftWrapOrderItemImpl();
Sku sku = new SkuImpl();
sku.setName("Test GiftWrap");
sku.setRetailPrice(new Money(1D));
sku.setDiscountable(true);
sku = catalogService.saveSku(sku);
item.setSku(sku);
item.setQuantity(1);
item.setOrder(order);
item.getWrappedItems().add(item1);
item.setOrderItemType(OrderItemType.GIFTWRAP);
item = (GiftWrapOrderItem) orderItemService.saveOrderItem(item);
order.addOrderItem(item);
FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl();
fgItem.setFulfillmentGroup(group);
fgItem.setOrderItem(item);
fgItem.setQuantity(1);
//fgItem.setPrice(new Money(0D));
group.addFulfillmentGroupItem(fgItem);
}
return order;
}
public int countPriceDetails(Order order) {
int count = 0;
for (OrderItem orderItem : order.getOrderItems()) {
if (orderItem.getOrderItemPriceDetails().isEmpty()) {
count += 1;
} else {
count += orderItem.getOrderItemPriceDetails().size();
}
}
return count;
}
/*
The offer portion of this test was commented to support price lists - without this the test is not valid
TODO fix test if GiftWrapOrderItems will continue to be supported by offers
*/
/*@Test(groups = {"testOffersWithGiftWrapLegacy"}, dependsOnGroups = { "testShippingInsertLegacy"})
@Transactional
public void testOrderItemOfferWithGiftWrap() throws PricingException {
Order order = createTestOrderWithOfferAndGiftWrap();
OfferDataItemProvider dataProvider = new OfferDataItemProvider();
List<Offer> offers = dataProvider.createItemBasedOfferWithItemCriteria(
"order.subTotal.getAmount()>20",
OfferDiscountType.PERCENT_OFF,
"([MVEL.eval(\"toUpperCase()\",\"Test Sku\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.sku.name))",
"([MVEL.eval(\"toUpperCase()\",\"Test Sku\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.sku.name))"
);
for (Offer offer : offers) {
offer.setName("testOffer");
//reset the offer is the targets and qualifiers, otherwise the reference is incorrect
for (OfferItemCriteria criteria : offer.getTargetItemCriteria()) {
criteria.setTargetOffer(null);
}
for (OfferItemCriteria criteria : offer.getQualifyingItemCriteria()) {
criteria.setQualifyingOffer(null);
}
offerService.save(offer);
}
order = orderService.save(order, true);
assert order.getTotalTax().equals(new Money("2.05"));
assert order.getTotalShipping().equals(new Money("0"));
assert order.getSubTotal().equals(new Money("41.00"));
assert order.getTotal().equals(new Money("43.05"));
assert countPriceDetails(order) == 3;
boolean foundGiftItemAndCorrectQuantity = false;
for (OrderItem orderItem : order.getOrderItems()) {
if (orderItem instanceof GiftWrapOrderItem && ((GiftWrapOrderItem) orderItem).getWrappedItems().size() == 1) {
foundGiftItemAndCorrectQuantity = true;
break;
}
}
assert foundGiftItemAndCorrectQuantity;
}*/
}
|
icnocop/NUglify
|
src/NUglify.Tests/TestData/JS/Expected/Strict/UnknownGlobal.js
|
function foo(n){"use strict";return bar=n.cave||location.href,ack(bar)+vat++}
|
ScalablyTyped/SlinkyTyped
|
s/semantic-ui-popup/src/main/scala/typingsSlinky/semanticUiPopup/anon/PickImploffset.scala
|
package typingsSlinky.semanticUiPopup.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/* Inlined std.Pick<semantic-ui-popup.SemanticUI.PopupSettings._Impl, 'offset'> */
@js.native
trait PickImploffset extends StObject {
var offset: Double = js.native
}
object PickImploffset {
@scala.inline
def apply(offset: Double): PickImploffset = {
val __obj = js.Dynamic.literal(offset = offset.asInstanceOf[js.Any])
__obj.asInstanceOf[PickImploffset]
}
@scala.inline
implicit class PickImploffsetMutableBuilder[Self <: PickImploffset] (val x: Self) extends AnyVal {
@scala.inline
def setOffset(value: Double): Self = StObject.set(x, "offset", value.asInstanceOf[js.Any])
}
}
|
The127/ImmutableJava
|
src/de/julian/baehr/immutable/listeners/statements/StatementIfListener.java
|
<reponame>The127/ImmutableJava
package de.julian.baehr.immutable.listeners.statements;
import de.julian.baehr.immutable.generated.JavaParser.StatementIfContext;
import de.julian.baehr.immutable.listeners.ImmutableBaseListener;
import de.julian.baehr.immutable.listeners.ParExpressionListener;
import de.julian.baehr.immutable.models.MConstructor;
import de.julian.baehr.immutable.models.statements.MStatementIf;
public class StatementIfListener extends ImmutableBaseListener<MStatementIf>{
private final boolean arraysAllowed;
private final MConstructor autoCpy;
public StatementIfListener(boolean arraysAllowed, MConstructor autoCpy) {
this.arraysAllowed = arraysAllowed;
this.autoCpy = autoCpy;
}
@Override
public void enterStatementIf(StatementIfContext ctx) {
setResult(new MStatementIf());
enterThere(ctx.parExpression(), new ParExpressionListener(arraysAllowed, autoCpy))
.ifResult(getResult()::setParExpression);
enterThere(ctx.ifStmt, new StatementListener(arraysAllowed, autoCpy))
.ifResult(getResult()::setIfStatement);
enterThere(ctx.elseStmt, new StatementListener(arraysAllowed, autoCpy))
.ifResult(getResult()::setElseStatement);
}
}
|
schnatterer/AnExplorer
|
app/src/television/java/dev/dworks/apps/anexplorer/ui/RecyclerViewCompat.java
|
package dev.dworks.apps.anexplorer.ui;
import android.content.Context;
import android.util.AttributeSet;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewCompat extends RecyclerView {
public RecyclerViewCompat(Context context) {
super(context);
}
public RecyclerViewCompat(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public RecyclerViewCompat(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
|
diztinct-tim/PTS
|
node_modules/history.js/scripts/uncompressed/history.adapter.extjs.js
|
/**
* History.js ExtJS Adapter
* @author <NAME> <<EMAIL>>
* @copyright 2012 <NAME> <<EMAIL>>
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
// Closure
(function(window,undefined){
"use strict";
// Localise Globals
var
History = window.History = window.History||{},
Ext = window.Ext;
window.JSON = {
stringify: Ext.JSON.encode,
parse: Ext.JSON.decode
};
// Check Existence
if ( typeof History.Adapter !== 'undefined' ) {
throw new Error('History.js Adapter has already been loaded...');
}
// Add the Adapter
History.Adapter = {
observables: {},
/**
* History.Adapter.bind(el,event,callback)
* @param {Element|string} el
* @param {string} event - custom and standard events
* @param {function} callback
* @param {Object} scope
* @return {void}
*/
bind: function(element,eventName,callback,scope){
Ext.EventManager.addListener(element, eventName, callback, scope);
//bind an observable to the element that will let us "trigger" events on it
var id = Ext.id(element, 'history-'), observable = this.observables[id];
if (!observable) {
observable = Ext.create('Ext.util.Observable');
this.observables[id] = observable;
}
observable.on(eventName, callback, scope);
},
/**
* History.Adapter.trigger(el,event)
* @param {Element|string} el
* @param {string} event - custom and standard events
* @param {Object=} extra - a object of extra event data (optional)
* @return {void}
*/
trigger: function(element,eventName,extra){
var id = Ext.id(element, 'history-'), observable = this.observables[id];
if (observable) {
observable.fireEvent(eventName, extra);
}
},
/**
* History.Adapter.extractEventData(key,event,extra)
* @param {string} key - key for the event data to extract
* @param {string} event - custom and standard events
* @param {Object=} extra - a object of extra event data (optional)
* @return {mixed}
*/
extractEventData: function(key,event,extra){
var result = (event && event.browserEvent && event.browserEvent[key]) || (extra && extra[key]) || undefined;
return result;
},
/**
* History.Adapter.onDomLoad(callback)
* @param {function} callback
* @return {void}
*/
onDomLoad: function(callback) {
Ext.onReady(callback);
}
};
// Try and Initialise History
if ( typeof History.init !== 'undefined' ) {
History.init();
}
})(window);
|
Legabog/social_network_legabog
|
src/containers/Music/components/BodyMusicListItem/index.js
|
export * from "./BodyMusicListItem"
|
smartrplace/api-draft
|
src/util-public/smartrplace-util-public/src/main/java/org/ogema/accessadmin/api/UserPermissionService.java
|
package org.ogema.accessadmin.api;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.ogema.model.locations.BuildingPropertyUnit;
import org.ogema.model.locations.Room;
import org.smartrplace.external.accessadmin.config.AccessConfigUser;
import org.smartrplace.gui.filtering.GenericFilterFixedGroup;
/** This service shall be offered to applications for checking whether relevant permissions are available
* TODO: Move this to smartrplace-util or ogema-gui-api*/
public interface UserPermissionService {
/** Rooms marked as priority are the primary rooms displayed to the user. Other rooms may be viewed, but
* are not shown by default. Implies USER_ROOM_PERM*/
public static final String USER_PRIORITY_PERM = "UserRoomPriority";
//public static final String SUBCUSTOMER_PRIORITY_PERM = "UserSubcustomerPriority";
/** General access permission to the room. If this is granted then checking for read or write
* shall return true for both. If read/write are set separately then the integer of the most
* specific permission set shall be returned. */
public static final String USER_ROOM_PERM = "UserRoomPermission";
//public static final String USER_SUBCUSTOMER_PERM = "UserSubcustomerPermission";
/** Permission to read the data point*/
public static final String USER_READ_PERM = "UserReadPermission";
/** Permisson to write the data point*/
public static final String USER_WRITE_PERM = "UserWritePermission";
/** Permission to create children of the data point and to delete them*/
public static final String USER_CREATE_DELETE_PERM = "UserCreateDeletePermission";
/** Permission to view and download the historical log data*/
public static final String USER_READ_HISTORICALDATA_PERM = "UserReadHistoricalDataPermission";
/** Permission to administer the room, especially change general settings like eco mode temperature*/
public static final String USER_ADMIN_PERM = "UserAdminPermission";
/** Permission to set back the setting for a {@link BuildingPropertyUnit} to the last
* backup marked as safe.
*/
public static final String RESTORE_SAFE_PERM = "RestoreSafeStatePermission";
/** Permission to install an application or an application type in a certain
* {@link BuildingPropertyUnit}
*/
public static final String UPDATE_INSTALL_PERM = "UpdateInstallPermission";
/** Permission to generate backups for a BuildingPropertyUnit, to mark a backup as stable
* and to restore them*/
public static final String UPDATE_RATING_PERM = "UpdateRatingPermission";
/** Permission to upload new apps with a certain permission level or updates for a certain app
* into the Appstore. Typically the main restrictions should now be imposed for the installation
* of apps - upload for installation on test servers can be done even for critical apps quit easily.
* For future public appstores this should be different, of course.
*/
public static final String UPDATE_DEFINITION_PERM = "UpdateDefinitionPermission";
/** Permissions for which the rooms per user shall be chosen via Multiselect. Currently USER_READ_HISTORICALDATA_PERM, USER_ADMIN_PERM
* are not processed per room, but just per user. So APPCONFIG_ permission types are used.*/
public static final String[] ROOMPERMISSONS = {USER_PRIORITY_PERM, USER_ROOM_PERM,
USER_READ_HISTORICALDATA_PERM, USER_ADMIN_PERM };
/** The extended version is currently not used*/
public static final String[] ROOMPERMISSONS_EXTENDED = {USER_PRIORITY_PERM, USER_ROOM_PERM, USER_READ_PERM, USER_WRITE_PERM,
USER_CREATE_DELETE_PERM, USER_READ_HISTORICALDATA_PERM, USER_ADMIN_PERM };
/** User System Permissions. Some of them may be defined per Building Unit in the future.*/
public static final String[] PROPUNITPERMISSIONS = {RESTORE_SAFE_PERM, UPDATE_INSTALL_PERM, UPDATE_RATING_PERM,
UPDATE_DEFINITION_PERM};
/** Permissions for which the subcustomers per user shall be chosen via Multiselect*/
//public static final String[] SUBCUSTOMER_PERMISSONS = {SUBCUSTOMER_PRIORITY_PERM, USER_SUBCUSTOMER_PERM};
public static final String MONITORING = "KPIs and Charts";
public static final String INSTALLATION_SETUP = "Setup&Installation";
public static final String ALARMING = "Alarming";
public static final String USER_MANAGEMENT = "User Management";
public static final String GROUP_AND_PERMISSION_MANAGEMENT = "Groups and Permissions";
public static final String APPSTORE = "Appstore";
public static final String BACNET = "BACnet Admin";
public static final String APPCONFIG_LOGOUT = "Logout";
public static final String APPCONFIG_OTHER_APPS = "Other Apps";
public static final String APPCONFIG_MEASUREMENTS = "Measuremt.";
public static final String APPCONFIG_ECOMODE = "Ecomode";
public static final String APPCONFIG_DETAILPAGE = "Detailpage";
public static final String APPCONFIG_SETPOINT_CURVE = "Setpoint Curve";
public static final String APPCONFIG_SETUPPAGE = "Setup Page";
//Permission under development
public static final String DASHBOARD_GENERAL = "Dashboad General";
public static final String DASHBOARD_SAVINGS = "Savings Dashboad";
public static final String DASHBOARD_CUSTOMERDOC = "FAQ Dashboad";
public static final String ROOMCONTROL_WE = "Roomcontrol WE";
public static final String ROOMCONTROL_2D = "Roomcontrol 2D";
public static final String ROOM_STATUS_CONTROL = "Room Status Control";
public static final String MODBUS_SERVER = "Modbus/Bacnet Server";
public static final String MONTORING_CHART_EXPERT = "Expert Charts";
public static final String[] APP_ACCESS_PERMISSIONS_ALL = {MONITORING, INSTALLATION_SETUP, ALARMING,
USER_MANAGEMENT, GROUP_AND_PERMISSION_MANAGEMENT, APPSTORE,
DASHBOARD_GENERAL, DASHBOARD_SAVINGS, DASHBOARD_CUSTOMERDOC,
ROOMCONTROL_WE, ROOMCONTROL_2D, ROOM_STATUS_CONTROL, MODBUS_SERVER, MONTORING_CHART_EXPERT};
public static final String[] APP_ACCESS_PERMISSIONS = {MONITORING, INSTALLATION_SETUP, ALARMING,
USER_MANAGEMENT, GROUP_AND_PERMISSION_MANAGEMENT};
public static final String[] APP_ACCESS_PERMISSIONS_WITHAPPSTORE = {MONITORING, INSTALLATION_SETUP, ALARMING,
USER_MANAGEMENT, GROUP_AND_PERMISSION_MANAGEMENT, APPSTORE};
public static final String[] APP_ACCESS_PERMISSIONS_FOR_SUPERADMIN = {DASHBOARD_GENERAL, DASHBOARD_SAVINGS, DASHBOARD_CUSTOMERDOC,
ROOMCONTROL_WE, ROOMCONTROL_2D, ROOM_STATUS_CONTROL, MODBUS_SERVER, MONTORING_CHART_EXPERT};
public static final String[] APP_CONFIG_PERMISSIONS = {APPCONFIG_LOGOUT, APPCONFIG_OTHER_APPS, APPCONFIG_MEASUREMENTS,
APPCONFIG_ECOMODE, APPCONFIG_SETPOINT_CURVE, APPCONFIG_DETAILPAGE, APPCONFIG_SETUPPAGE};
/** Permissions for which the building property units rooms per user and per app or app permission type
* shall be chosen via Multiselect. So the table will most likely only show one app or app permission type
* to be edited at once.
* TODO: For now we give these permissions for all apps per unit. To be discussed if a per-app differentiation
* makes sense*/
//public static final String[] PROPUNIT_PER_APP_PERMISSIONS = {APP_INSTALL_PERM, APP_RESTORE_PERM};
/** Permission that are given per app permission type per user. So a Multiselect to choose the apps
* instead of choosing the rooms could be used here. It could also be integrated
* with PROPUNIT_PER_APP_PERMISSIONS and show as just a BooleanCheckBox there.*/
public static final String[] USER_APP_PERMISSIONS = {UPDATE_DEFINITION_PERM};
/** True if at least a read permission for the room is granted*/
boolean hasUserPermissionForRoom(String userName, Room room);
/** Check if the user has a certain permission for a room*/
boolean hasUserPermissionForRoom(String userName, Room room, String permissionType);
/** Returns the permission value that may be greater than one for a permission granted*/
int getUserPermissionForRoom(String userName, Room room, String permissionType);
/**
* @param getSuperSetting if true the specific setting for the user and room will be ignored and
* only the more general setting will be returned
*/
public int getUserPermissionForRoom(String userName, String resourceId, String permissionType,
boolean getSuperSetting);
/** Returns the permission value that may be greater than one for a permission granted*/
int getUserSystemPermission(String userName, String permissionType);
/** Permission types allowed here are from APP_ACCESS_PERMISSIONS_ALL*/
int getUserStatusAppPermission(UserStatus userStatus, String permissionType, boolean useWorkingCopy);
/** Returns the permission value that may be greater than one for a permission granted*/
//int getUserPermissionForUnitApps(String userName, String unitName, String appName, String permissionType);
/** Returns the permission value that may be greater than one for a permission granted
* Note: Management of these permissions not implemented yet*/
int getUserPermissionForApp(String userName, String appName, String permissionType);
/** True if at least a read permission for the data point is granted*/
//boolean hasUserPermissionForDatapoint(String userName, DatapointDesc datapoint);
/** Check if the user has a certain permission for a datapoint*/
//boolean hasUserPermissionForDatapoint(String userName, DatapointDesc datapoint, String permissionType);
//int getUserPermissionForDatapoint(String userName, DatapointDesc datapoint, String permissionType);
/** Get all permission values for a datapoint to be added to the Datapoint interface*/
//int[] getPermissionValuesForDatapoint(String userName, DatapointDesc datapoint);
//TODO: Add methods to check directly for write, read and write
/** Get filter for a user group for which membership is not specified by {@link AccessConfigUser#superGroups()}
*
* @param userGroupName name of the group
* @return null if the group membership specified via superGroups
*/
default GenericFilterFixedGroup<String, AccessConfigUser> getUserGroupFiler(String userGroupName) {
return null;
}
default GenericFilterFixedGroup<Room, BuildingPropertyUnit> getRoomGroupFiler(String roomGroupName) {
return null;
}
public static class UserStatusResult {
public UserStatus status = null;
public List<String> addPerms = null;
}
UserStatusResult getUserStatus(String userName);
public boolean hasExtendedView(HttpSession session);
public boolean hasExtendedView(String user);
}
|
pieter-hendriks/STL-monitoring
|
stl/utility/plothelper.py
|
<filename>stl/utility/plothelper.py
""" Implementation of a plot managing class. """
import matplotlib.pyplot as plt
from .helpers import cm2inch
from .singleton import Singleton
class PlotHelper(metaclass=Singleton):
""" Singleton class to manage various plots used throughout the STL implementation """
def __init__(self):
self.__figure = None
self.__axs = None
self.__index = 0
def reset(self):
""" Reset the plots to None/empty"""
if self.__figure is not None:
for f in self.__figure:
f.close()
self.__figure = None
self.__axs = None
self.__index = 0
def createSubplots(self, count):
""" Add a subplot to the current figure """
self.__figure, self.__axs = plt.subplots(count, sharex=True, sharey=True)
self.__figure.set_size_inches(cm2inch(15), cm2inch(count * 3))
def booleanPlot(self, xValues, yValues, title, fmt='r-'):
""" Plot a boolean Signal (step fn) """
assert self.__figure is not None and self.__axs is not None
self.__axs[self.__index].step(xValues, yValues, fmt, where='post')
self.__genericPlotTasks(title)
def quantitativePlot(self, xValues, yValues, title, fmt='r-'):
""" Plot a quantitative signal (line) """
assert self.__figure is not None and self.__axs is not None
self.__axs[self.__index].plot(xValues, yValues, fmt)
self.__genericPlotTasks(title)
def __genericPlotTasks(self, title):
""" Helper function for plotting; common between quant and boolean """
self.__axs[self.__index].set_title(title)
self.__index += 1
# pylint: disable=no-self-use
def show(self):
""" Show the created figure. """
plt.show()
# pylint: enable=no-self-use
|
EPIICTHUNDERCAT/TameableMobs
|
src/main/java/com/github/EPIICTHUNDERCAT/TameableMobs/Reference.java
|
package com.github.epiicthundercat.tameablemobs;
public class Reference {
public static final String ID = "tameablemobs";
public static final String VER = "0.0.2";
public static final String NAME = "TameableMobs";
public static final String CLIENT_PROXY = "com.github.epiicthundercat.tameablemobs.proxy.ClientProxy";
public static final String SERVER_PROXY = "com.github.epiicthundercat.tameablemobs.proxy.CommonProxy";
}
|
software-is-art/hazelcast
|
hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/validate/operators/typeinference/JsonFunctionOperandTypeInference.java
|
/*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.validate.operators.typeinference;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.SqlCallBinding;
import org.apache.calcite.sql.type.SqlOperandTypeInference;
import org.apache.calcite.sql.type.SqlTypeName;
public final class JsonFunctionOperandTypeInference implements SqlOperandTypeInference {
@Override
public void inferOperandTypes(final SqlCallBinding callBinding,
final RelDataType returnType,
final RelDataType[] operandTypes) {
for (int i = 0; i < callBinding.getOperandCount(); i++) {
operandTypes[i] = callBinding.getOperandType(i);
if (operandTypes[i].getSqlTypeName() == SqlTypeName.NULL) {
operandTypes[i] = callBinding.getTypeFactory().createSqlType(SqlTypeName.VARCHAR);
}
}
if (operandTypes[0].getSqlTypeName() == SqlTypeName.NULL) {
operandTypes[0] = callBinding.getTypeFactory().createSqlType(SqlTypeName.VARCHAR);
}
}
}
|
zan-mateusz/brooklyn-server
|
rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/ScannerInjectHelper.java
|
/*
* Copyright 2015 The Apache Software Foundation.
*
* 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.apache.brooklyn.rest.util;
import io.swagger.jaxrs.config.SwaggerContextService;
import io.swagger.jaxrs.config.SwaggerScannerLocator;
import org.apache.brooklyn.rest.apidoc.RestApiResourceScanner;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import io.swagger.config.ScannerFactory;
public class ScannerInjectHelper {
public void setServer(JAXRSServerFactoryBean server) {
RestApiResourceScanner scanner = new RestApiResourceScanner(server.getResourceClasses());
ScannerFactory.setScanner(scanner);
// Above method broken in Swagger 1.6.2:
// In Swagger 1.6.2 the method SwaggerContextService.getScanner calls to ScannerFactory.getScanner() only
// when SwaggerScannerLocator.getInstance().getScanner(scannerIdKey) == null, but seeing its implementations,
// it's impossible to get a null value, so we need to use SwaggerScannerLocator instead.
SwaggerScannerLocator.getInstance().putScanner(SwaggerContextService.SCANNER_ID_DEFAULT, scanner);
}
}
|
CarbonDDR/al-go-rithms
|
data_structures/Graphs/graph/c++/singleSourceShortestPath.cpp
|
<reponame>CarbonDDR/al-go-rithms
#include<bits/stdc++.h>
using namespace std;
//generic graph using templates
template<typename T>
class graph{
int V;
map<T,list<T>> h;
public:
//adding edge between two vetices
void addEdge(T u,T v,bool biDir=true)
{
h[u].push_back(v);
if(biDir)
{
h[v].push_back(u);
}
return;
}
//printing the graph
void print()
{
for(auto i:h)
{
cout<<i.first<<" -> ";
for(auto j:i.second)
{
cout<<j<<" ";
}
cout<<endl;
}
}
//finding the shortest distance of all nodes from the source node
void sssp(T src)
{
queue <T>q;
q.push(src);
map<T,int> dist;
map<T,T> parent;
for(auto i:h)
{
dist[i.first]=INT_MAX;
}
dist[src]=0;
parent[src]=src;
while(!q.empty())
{
T temp=q.front();
q.pop();
for(auto i:h[temp])
{
if(dist[i]==INT_MAX)
{
q.push(i);
dist[i]=1+dist[temp];
parent[i]=temp;
}
}
}
for(auto i:h)
{
T temp=i.first;
cout<<"Distance of "<<temp<<" from "<<src<<" is " <<dist[temp]<<endl;
}
}
};
int main()
{
graph<int> g;
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(0,4);
g.addEdge(2,4);
g.addEdge(2,3);
g.addEdge(3,4);
g.addEdge(3,5);
//g.print();
g.sssp(0);
return 0;
}
|
xpertana/engage-demo
|
src/components/EngageClient/elements/Grid/types/ImageText.js
|
<filename>src/components/EngageClient/elements/Grid/types/ImageText.js
import React, { Component } from "react";
const sizeMap = [[80], [70], [60], [50], [40]];
export default class ImageText extends Component {
constructor(props) {
super(props);
this.state = { hidden: false };
}
handleAction(action) {
if (this.props.item._hide) this.setState({ hidden: true });
this.props.handler({
action,
index: this.props.index,
item: this.props.item
});
}
render() {
if (this.state.hidden) return <span></span>;
const { size = 3 } = this.props;
const [imsz] = sizeMap[size - 1];
return (
<div
onClick={() => this.handleAction("select")}
class="m-1 flex flex-col items-center justify-between border rounded-md shadow-sm"
>
<div style={{ width: imsz }} class="">
<img src={this.props.item.image} />
</div>
<div
className={`px-1 text-xs text-center left-0 flex-1 w-full rounded-b opacity`}
>
{this.props.item.text}
</div>
</div>
);
}
}
|
h4ck3rm1k3/NLP-project
|
stanford-corenlp-full-2012-11-12/src/edu/stanford/nlp/time/XMLUtils.java
|
package edu.stanford.nlp.time;
import edu.stanford.nlp.io.StringOutputStream;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
/**
* XML Utility functions for use with dealing with Timex expressions
*
* @author <NAME>
*/
public class XMLUtils {
private static Document document = createDocument();
public static String documentToString(Document document) {
StringOutputStream s = new StringOutputStream();
printNode(s, document, true, true);
return s.toString();
}
public static String nodeToString(Node node, boolean prettyPrint) {
StringOutputStream s = new StringOutputStream();
printNode(s, node, prettyPrint, false);
return s.toString();
}
public static void printNode(OutputStream out, Node node, boolean prettyPrint, boolean includeXmlDeclaration)
{
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer serializer;
try {
serializer = tfactory.newTransformer();
if (prettyPrint) {
//Setup indenting to "pretty print"
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
}
if (!includeXmlDeclaration) {
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
}
DOMSource xmlSource = new DOMSource(node);
StreamResult outputTarget = new StreamResult(out);
serializer.transform(xmlSource, outputTarget);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}
public static Document createDocument() {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
return doc;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Text createTextNode(String text) {
return document.createTextNode(text);
}
public static Element createElement(String tag) {
return document.createElement(tag);
}
public static Element parseElement(String xml) {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
return doc.getDocumentElement();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Like element.getAttribute except returns null if attribute not present
public static String getAttribute(Element element, String name) {
Attr attr = element.getAttributeNode(name);
return (attr != null)? attr.getValue(): null;
}
public static void removeChildren(Element e) {
NodeList list = e.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node n = list.item(i);
e.removeChild(n);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.