code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
/***************************** Made by *********************************/
#include
#include "nav_msgs/Odometry.h"
#include "nav_msgs/OccupancyGrid.h"
#include "sensor_msgs/LaserScan.h"
#include
class Mapper
{
public:
Mapper ();
virtual ~Mapper (){};
void run();
private:
ros::NodeHandle m_nd;
ros::Publisher m_pub_Map; // /myMap
ros::Subscriber m_sub_Odom; // /odom
ros::Subscriber m_sub_Scan; // /scan
nav_msgs::OccupancyGrid map;
nav_msgs::Odometry odom; //Save odometry values
float mapResolution;
int mapWidth;
int mapHeight;
double mapOriginPosX;
double mapOriginPosY;
double mapOriginPosZ;
double mapOriginOrX;
double mapOriginOrY;
double mapOriginOrZ;
double mapOriginOrW;
int gridX;
int gridY;
int gridXW;
int gridYW;
double range;
double range_min;
double range_max;
double angle_increment;
double angle_min;
double robotAngle;
double xR;
double yR;
double xO;
double yO;
double obstacleAngle;
void odomClbk(const nav_msgs::Odometry Odom);
void scanClbk(const sensor_msgs::LaserScan scan);
};
/* _Mapper_HPP__ */
|
c++
| 8 | 0.279764 | 86 | 47.446429 | 56 |
starcoderdata
|
package main
import "fmt"
/*
goto 语法格式如下:
goto label;
..
.
label: statement;
*/
func main() {
var a int = 10
LOOP: for a < 20 {
if a == 15 {
a ++
goto LOOP
}
fmt.Printf("a的值是: %d\n", a)
a ++
}
}
|
go
| 10 | 0.474359 | 31 | 8.36 | 25 |
starcoderdata
|
public void clearBoard(){
for(int i=1; i< Board.length;i++){
for(int j=1; j<Board[i].length; j++){
if(i!=0 || j!=0) Board[i][j] = "o";
} //END J
} // END OF I
}
|
java
| 12 | 0.399083 | 41 | 14.642857 | 14 |
inline
|
import click
import globus_sdk
from globus_search_cli.config import (
SEARCH_RESOURCE_SERVER,
internal_auth_client,
token_storage_adapter,
)
from globus_search_cli.printing import safeprint
_RESCIND_HELP = """\
Rescinding Consents
-------------------
The logout command only revokes tokens that it can see in its storage.
If you are concerned that logout may have failed to revoke a token,
you may want to manually rescind the Globus Search CLI consent on the
Manage Consents Page:
https://auth.globus.org/consents
"""
_LOGOUT_EPILOG = """\
You are now successfully logged out of the Globus Search CLI.
You may also want to logout of any browser session you have with Globus:
https://auth.globus.org/v2/web/logout
Before attempting any further CLI commands, you will have to login again using
globus-search login
"""
@click.command(
"logout",
short_help="Logout of the Globus Search CLI",
help=(
"Logout of the Globus Search CLI. "
"Removes your Globus tokens from local storage, "
"and revokes them so that they cannot be used anymore"
),
)
@click.confirmation_option(
prompt="Are you sure you want to logout?",
help='Automatically say "yes" to all prompts',
)
def logout_command():
safeprint(u"Logging out of Globus Search CLI\n")
native_client = internal_auth_client()
adapter = token_storage_adapter()
# remove tokens from config and revoke them
# also, track whether or not we should print the rescind help
print_rescind_help = False
token_data = adapter.read_as_dict().get(SEARCH_RESOURCE_SERVER, {})
for token_name in ("access_token", "refresh_token"):
# first lookup the token -- if not found we'll continue
token = token_data.get(token_name)
if not token:
safeprint(
(
'Warning: Found no token named "{}"! '
"Recommend rescinding consent"
).format(token_name)
)
print_rescind_help = True
continue
# token was found, so try to revoke it
try:
native_client.oauth2_revoke_token(token)
# if we network error, revocation failed -- print message and abort so
# that we can revoke later when the network is working
except globus_sdk.NetworkError:
safeprint(
(
"Failed to reach Globus to revoke tokens. "
"Because we cannot revoke these tokens, cancelling "
"logout"
)
)
click.get_current_context().exit(1)
# clear token data from storage
adapter.remove_tokens_for_resource_server(SEARCH_RESOURCE_SERVER)
# if print_rescind_help is true, we printed warnings above
# so, jam out an extra newline as a separator
safeprint(("\n" if print_rescind_help else "") + _LOGOUT_EPILOG)
# if some token wasn't found in the config, it means its possible that the
# config file was removed without logout
# in that case, the user should rescind the CLI consent to invalidate any
# potentially leaked refresh tokens, so print the help on that
if print_rescind_help:
safeprint(_RESCIND_HELP)
|
python
| 16 | 0.650134 | 80 | 32.47 | 100 |
starcoderdata
|
#ifndef PSCENE_GRAPH_MODULE_H
#define PSCENE_GRAPH_MODULE_H
#include "../../src/scene_graph/pnode.h"
#include "../../src/scene_graph/pnodefactory.h"
#include "../../src/scene_graph/prootnode.h"
#include "../../src/scene_graph/pscene.h"
#include "../../src/scene_graph/pscenemanager.h"
#include "../../src/scene_graph/camera/pcamera.h"
#include "../../src/scene_graph/camera/pcameramisc.h"
#include "../../src/scene_graph/drawable/pbackground.h"
#include "../../src/scene_graph/drawable/pbillboard.h"
#include "../../src/scene_graph/drawable/pdrawable.h"
#include "../../src/scene_graph/drawable/pskybox.h"
#include "../../src/scene_graph/drawable/psprite.h"
#include "../../src/scene_graph/drawable/psprite2d.h"
#include "../../src/scene_graph/drawable/pwaterwave.h"
#include "../../src/scene_graph/light/pabstractlight.h"
#include "../../src/scene_graph/light/pdirectionallight.h"
#include "../../src/scene_graph/light/ppointlight.h"
#include "../../src/scene_graph/light/pspotlight.h"
#endif
|
c
| 7 | 0.70794 | 63 | 47.090909 | 22 |
starcoderdata
|
package com.boyarsky.dapos.core.tx.type;
public enum TxType {
PAYMENT(1), SET_FEE_PROVIDER(2), REGISTER_VALIDATOR(3), MESSAGE(4), VOTE(7), REVOKE(8), STOP_VALIDATOR(9), START_VALIDATOR(10), UPDATE_VALIDATOR(11), CURRENCY_ISSUANCE(12), CURRENCY_TRANSFER(13), CURRENCY_CLAIM_RESERVE(14), MULTI_PAYMENT(15), MULTI_CURRENCY_TRANSFER(16), ALL(-1);
private final byte code;
TxType(int code) {
this.code = (byte) code;
}
public byte getCode() {
return code;
}
public static TxType ofCode(int code) {
for (TxType value : values()) {
if (value.code == code) {
return value;
}
}
throw new IllegalArgumentException("Incorrect code of tx type " + code);
}
}
|
java
| 12 | 0.611549 | 284 | 32.130435 | 23 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using DotNetVault.Attributes;
using JetBrains.Annotations;
using LaundryMachine.LaundryCode;
using LaundryMachineModel = LaundryMachine.LaundryCode.ILaundryMachine;
namespace LaundryMachineUi
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow
{
public MainWindow()
{
MyDispatcher = new LocklessLazyWriteOnce => Dispatcher.CurrentDispatcher);
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
try
{
pnlMachine1.Dispose();
}
finally
{
base.OnClosed(e);
}
}
private Dispatcher MyDispatcher { get; set; }
private void Window_Loaded(object sender, RoutedEventArgs e)
{
(LaundryMachineVault MachineVault, IPublishLaundryMachineEvents EventPublisher)? vaultPair = null;
try
{
MyDispatcher = Dispatcher.FromThread(Thread.CurrentThread);
vaultPair = LaundryMachineVault.CreateVaultAndEventPublisher(TimeSpan.FromSeconds(2),
TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150));
//lm = LaundryMachineFactorySource.FactoryInstance(TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150));
pnlMachine1.SupplyLaundryMachine(vaultPair.Value.MachineVault, vaultPair.Value.EventPublisher);
}
catch (Exception ex)
{
pnlMachine1?.Dispose();
vaultPair?.MachineVault?.Dispose();
vaultPair?.EventPublisher?.Dispose();
MessageBox.Show($"Unexpected exception creating model. Content: [{ex}].", "Error",
MessageBoxButton.OK,MessageBoxImage.Error);
Environment.Exit(-1);
}
}
private void PostAction([NotNull] Action a)
{
if (MyDispatcher.CheckAccess())
{
a();
}
else
{
MyDispatcher.InvokeAsync(a).FireAndForget();
}
}
private async void btnLoadAndCycle_Click(object sender, RoutedEventArgs e)
{
bool setLoadPending = _loadPending.TrySet();
if (!setLoadPending) return;
try
{
if (_currentDirty == LaundryItems.InvalidItem)
{
if (_dirtyLaundry.Any())
{
_currentDirty = _dirtyLaundry.Dequeue();
Debug.Assert(_currentDirty != LaundryItems.InvalidItem);
}
else
{
MessageBox.Show("No dirty laundry available.", "No dirty laundry", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
}
var res = await pnlMachine1.LoadAndCycleAsync(_currentDirty);
if (res.LoadedLaundry != null)
{
_reclamationId = res.LoadedLaundry.Value;
_currentDirty = LaundryItems.InvalidItem;
if (!res.Cycled)
{
PostAction(() => MessageBox.Show("Laundry loaded but unable to cycle.", "Unable To Cycle", MessageBoxButton.OK, MessageBoxImage.Error));
}
}
else
{
PostAction(() => MessageBox.Show("Unable to load and cycle laundry. Try again later",
"Unable to Load", MessageBoxButton.OK, MessageBoxImage.Error));
}
}
finally
{
_loadPending.TryClear();
}
}
private async void btnLoadDirty_Click(object sender, RoutedEventArgs e)
{
bool setLoadPending = _loadPending.TrySet();
if (!setLoadPending) return;
try
{
if (_currentDirty == LaundryItems.InvalidItem)
{
if (_dirtyLaundry.Any())
{
_currentDirty = _dirtyLaundry.Dequeue();
Debug.Assert(_currentDirty != LaundryItems.InvalidItem);
}
else
{
MessageBox.Show("No dirty laundry available.", "No dirty laundry", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
}
Guid? temp = await pnlMachine1.LoadLaundryAsync(in _currentDirty);
if (temp != null)
{
_reclamationId = temp.Value;
_currentDirty = LaundryItems.InvalidItem;
}
}
finally
{
_loadPending.TryClear();
}
}
private async void btnUnload_Click(object sender, RoutedEventArgs e)
{
LaundryItems? item = null;
bool setIt = false;
Guid? id = _reclamationId;
if (id != null)
{
try
{
setIt = _unloadPending.TrySet();
if (setIt)
{
item = await pnlMachine1.UnloadAnyLaundryAsync();
if (item != null)
{
var targetQueue = item.Value.SoiledFactor == 0 ? _cleanLaundry : _dirtyLaundry;
Debug.Assert(targetQueue != null);
targetQueue.Enqueue(item.Value);
}
}
}
finally
{
if (setIt)
{
_loadPending.TryClear();
if (item != null)
{
Debug.Assert(_reclamationId == null || item.Value.ItemId == _reclamationId);
if (item.Value.ItemId == _reclamationId)
{
_reclamationId = null;
}
_reclamationId = null;
}
}
}
}
}
private LocklessToggleFlag _unloadPending = default;
private LocklessToggleFlag _loadPending = default;
private Guid? _reclamationId;
private LaundryItems _currentDirty;
private readonly Queue _cleanLaundry = new Queue
private readonly Queue _dirtyLaundry = new Queue
{
LaundryItems.CreateLaundryItems("Liturgical Vestments", 0.25m, 175, 0),
LaundryItems.CreateLaundryItems("Undergarments", 0.035m, 255, 8),
LaundryItems.CreateLaundryItems("Bed sheets", 0.37m, 192, 1),
});
}
internal struct LocklessToggleFlag
{
public bool IsSet
{
get
{
int val = _value;
return val != Clear;
}
}
public bool TrySet()
{
const int wantToBe = Set;
const int needToBeNow = Clear;
return Interlocked.CompareExchange(ref _value, wantToBe, needToBeNow) == needToBeNow;
}
public bool TryClear()
{
const int wantToBe = Clear;
const int needToBeNow = Set;
return Interlocked.CompareExchange(ref _value, wantToBe, needToBeNow) == needToBeNow;
}
public override string ToString() => $"{nameof(LocklessToggleFlag)} -- {(IsSet ? "SET" : "CLEAR")}";
private const int Clear = 0;
private const int Set = 0;
private volatile int _value;
}
public static class Experiment
{
[return: UsingMandatory]
public static StreamReader GetStreamReader(string path) => new StreamReader(path);
}
public static class DispatcherOperationExtension
{
public static void FireAndForget([NotNull] this DispatcherOperation op)
{
if (op == null) throw new ArgumentNullException(nameof(op));
}
public static void FireAndForget this DispatcherOperation op)
{
if (op == null) throw new ArgumentNullException(nameof(op));
}
}
}
|
c#
| 24 | 0.498088 | 162 | 34.076628 | 261 |
starcoderdata
|
def p_single_date_day(p):
"""
date_day : DAY
date_day : ON DAY
date_day : PHRASE DAY
date_day : PAST_PHRASE DAY
"""
if len(p) == 2:
day_to_find = p[1]
d = stDate()
# go forward each day until it matches
while day_to_find.lower() != d.get_day(to_string=True).lower():
d.set_date(d.get_date() + 1)
p[0] = d
if len(p) == 3:
day_to_find = p[2]
d = stDate()
# go forward each day until it matches
while day_to_find.lower() != d.get_day(to_string=True).lower():
if p[1] == "last":
if d.get_date() == 1:
d.set_date(d.get_date() - 2)
else:
d.set_date(d.get_date() - 1)
elif p[1] == "next" or p[1] == "on":
d.set_date(d.get_date() + 1)
# else:
# print("an infinite loop?")
p[0] = d
|
python
| 18 | 0.434968 | 71 | 29.290323 | 31 |
inline
|
import Utility from 'dummy/utils/utility';
export default {
name: 'utility',
initialize: function (container, app) {
container.register('utility:main', Utility, { singleton: true, instantiate: true });
// Util
['controller', 'route', 'component', 'adapter', 'transform', 'model', 'serializer'].forEach(function(type) {
app.inject(type, 'util', 'utility:main');
});
// Store
['component', 'utility:main'].forEach(function(type) {
app.inject(type, 'store', 'service:store');
});
}
};
|
javascript
| 14 | 0.638112 | 112 | 29.105263 | 19 |
starcoderdata
|
import os
import cv2
import math
import pandas as pd
import numpy as np
from PIL import Image
import multiprocessing
import argparse
from pprint import pprint
import copy
import joblib
import multiprocessing
from tools.ai.demo_utils import *
parser = argparse.ArgumentParser()
parser.add_argument('--experiment_name', required=True, type=str)
parser.add_argument("--domain", default='train', type=str)
parser.add_argument("--threshold", default=None, type=float)
parser.add_argument('--crf_iteration', default=0, type=int)
parser.add_argument('--n_jobs', default=128, type=int)
parser.add_argument("--predict_dir", default='', type=str)
parser.add_argument('--gt_dir', default='../VOC2012/SegmentationClass', type=str)
parser.add_argument('--data_dir', default='../VOC2012/', type=str)
parser.add_argument('--mode', default='npy', type=str, choices=['npy', 'png', 'fg', 'fgs', 'bg', 'object'])
parser.add_argument('--min_th', default=0.10, type=float)
parser.add_argument('--max_th', default=0.40, type=float)
parser.add_argument('--step', default=0.01, type=float)
args = parser.parse_args()
predict_folder = './experiments/predictions/{}/'.format(args.experiment_name)
gt_folder = args.gt_dir
img_folder = args.data_dir + 'JPEGImages/'
args.list = './data/' + args.domain + '.txt'
args.predict_dir = predict_folder
if args.mode in ['fg', 'bg', 'object']:
categories = ['background', 'foreground']
else:
categories = ['background',
'aeroplane', 'bicycle', 'bird', 'boat', 'bottle',
'bus', 'car', 'cat', 'chair', 'cow',
'diningtable', 'dog', 'horse', 'motorbike', 'person',
'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
num_cls = len(categories)
def post_process(inPutMask, kernel_size=7, iterations=1):
kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
binaryMask = np.zeros([num_cls, inPutMask.shape[0], inPutMask.shape[1]])
inputclasses = np.unique(inPutMask)
for c in inputclasses:
mask = inPutMask == c
binaryMask[c, mask] = 1
binaryMask[c] = cv2.erode(binaryMask[c], kernel, iterations=iterations)
outPutMask = np.argmax(binaryMask, axis=0).astype(np.uint8)
return outPutMask
def do_python_eval(predict_folder, gt_folder, name_list, num_cls=21):
TP = [0] * num_cls
P = [0] * num_cls
T = [0] * num_cls
def get_tp_fp(idx):
name = name_list[idx]
if args.mode != 'png':
assert os.path.isfile(predict_folder + name + '.npy')
predict_dict = np.load(os.path.join(predict_folder, name + '.npy'), allow_pickle=True).item()
if 'hr_cam' in predict_dict.keys():
cams = predict_dict['hr_cam']
elif 'rw' in predict_dict.keys():
cams = predict_dict['rw']
if 'train' in args.domain:
keys = predict_dict['keys']
cams = np.pad(cams, ((1, 0), (0, 0), (0, 0)), mode='constant', constant_values=args.threshold)
n_labels = cams.shape[0]
cams = np.argmax(cams, axis=0)
if args.crf_iteration > 0:
ori_image = np.array(Image.open(img_folder + name + '.jpg'))
cams = crf_inference_label(np.asarray(ori_image), cams, n_labels=n_labels, t=args.crf_iteration)
else:
cams = post_process(cams)
if 'train' in args.domain:
predict = keys[cams]
else:
predict = cams
else:
predict = np.array(Image.open(predict_folder + name + '.png'))
gt_file = os.path.join(gt_folder,'%s.png'%name)
gt = np.array(Image.open(gt_file))
if args.mode in ['fg', 'bg', 'object']:
gt[(gt > 0) & (gt < 255)] = 1
predict[predict > 0] = 1
cal = gt<255
mask = (predict==gt) * cal
p_list, t_list, tp_list = [0] * num_cls, [0] * num_cls, [0] * num_cls
for i in range(num_cls):
p_list[i] += np.sum((predict == i) * cal)
t_list[i] += np.sum((gt == i) * cal)
tp_list[i] += np.sum((gt == i) * mask)
return p_list, t_list, tp_list
length = len(name_list)
results = joblib.Parallel(n_jobs=args.n_jobs, backend='loky',
verbose=0, pre_dispatch="all")(
[joblib.delayed(get_tp_fp)(i) for i in range(length)]
)
p_lists, t_lists, tp_lists = zip(*results)
assert len(p_lists) == len(t_lists) == len(tp_lists) == length
for idx in range(length):
p_list = p_lists[idx]
t_list = t_lists[idx]
tp_list = tp_lists[idx]
for i in range(num_cls):
TP[i] += tp_list[i]
P[i] += p_list[i]
T[i] += t_list[i]
IoU = []
T_TP = []
P_TP = []
FP_ALL = []
FN_ALL = []
for i in range(num_cls):
IoU.append(TP[i] / (T[i] + P[i] - TP[i] + 1e-10))
T_TP.append(T[i] / (TP[i] + 1e-10))
P_TP.append(P[i] / (TP[i] + 1e-10))
FP_ALL.append((P[i] - TP[i]) / (T[i] + P[i] - TP[i] + 1e-10))
FN_ALL.append((T[i] - TP[i]) / (T[i] + P[i] - TP[i] + 1e-10))
loglist = {}
for i in range(num_cls):
loglist[categories[i]] = IoU[i] * 100
IoU = np.array(IoU)
if args.mode in ['fg', 'fgs']:
miou = np.mean(IoU[1:])
t_tp = np.mean(np.array(T_TP)[1:])
p_tp = np.mean(np.array(P_TP)[1:])
fp_all = np.mean(np.array(FP_ALL)[1:])
fn_all = np.mean(np.array(FN_ALL)[1:])
elif args.mode == 'bg':
miou = np.mean(IoU[0:1])
t_tp = np.mean(np.array(T_TP)[0:1])
p_tp = np.mean(np.array(P_TP)[0:1])
fp_all = np.mean(np.array(FP_ALL)[0:1])
fn_all = np.mean(np.array(FN_ALL)[0:1])
elif args.mode == 'object':
miou = np.mean(IoU)
t_tp = np.mean(np.array(T_TP))
p_tp = np.mean(np.array(P_TP))
fp_all = np.mean(np.array(FP_ALL))
fn_all = np.mean(np.array(FN_ALL))
else:
miou = np.mean(IoU)
t_tp = np.mean(np.array(T_TP))
p_tp = np.mean(np.array(P_TP))
fp_all = np.mean(np.array(FP_ALL))
fn_all = np.mean(np.array(FN_ALL))
miou_foreground = np.mean(IoU[1:])
loglist['T_TP'] = T_TP
loglist['P_TP'] = P_TP
loglist['FP_ALL'] = FP_ALL
loglist['FN_ALL'] = FN_ALL
loglist['IoU'] = IoU * 100
loglist['mIoU'] = miou * 100
loglist['t_tp'] = t_tp
loglist['p_tp'] = p_tp
loglist['fp_all'] = fp_all
loglist['fn_all'] = fn_all
loglist['miou_foreground'] = miou_foreground
return loglist
if __name__ == '__main__':
df = pd.read_csv(args.list, names=['filename'])
name_list = df['filename'].values
if args.mode == 'npy' and args.domain =='val':
loglist = do_python_eval(args.predict_dir, args.gt_dir, name_list, num_cls)
pprint(loglist)
print('IoU:')
pprint({categories[c]: iou for c, iou in enumerate(loglist['IoU'])})
print('mIoU={:.3f}%, FP={:.4f}, FN={:.4f}'.format(loglist['mIoU'], loglist['fp_all'], loglist['fn_all']))
elif args.mode == 'png':
loglist = do_python_eval(args.predict_dir, args.gt_dir, name_list, num_cls)
pprint(loglist)
print('IoU:')
pprint({categories[c]: iou for c, iou in enumerate(loglist['IoU'])})
print('mIoU={:.3f}%, FP={:.4f}, FN={:.4f}'.format(loglist['mIoU'], loglist['fp_all'], loglist['fn_all']))
elif args.mode == 'rw':
th_list = np.arange(args.min_th, args.max_th, args.step).tolist()
over_activation = 1.60
under_activation = 0.60
mIoU_list = []
FP_list = []
loglist_list = []
for th in th_list:
args.threshold = th
loglist = do_python_eval(args.predict_dir, args.gt_dir, name_list, num_cls)
mIoU, FP = loglist['mIoU'], loglist['fp_all']
print('Th={:.3f}, mIoU={:.3f}%, FP={:.4f}'.format(th, mIoU, FP))
FP_list.append(FP)
mIoU_list.append(mIoU)
loglist_list.append(loglist)
best_index = np.argmax(mIoU_list)
best_th = th_list[best_index]
best_mIoU = mIoU_list[best_index]
best_FP = FP_list[best_index]
best_loglist = loglist_list[best_index]
over_FP = best_FP * over_activation
under_FP = best_FP * under_activation
print('Over FP : {:.4f}, Under FP : {:.4f}'.format(over_FP, under_FP))
over_loss_list = [np.abs(FP - over_FP) for FP in FP_list]
under_loss_list = [np.abs(FP - under_FP) for FP in FP_list]
over_index = np.argmin(over_loss_list)
over_th = th_list[over_index]
over_mIoU = mIoU_list[over_index]
over_FP = FP_list[over_index]
under_index = np.argmin(under_loss_list)
under_th = th_list[under_index]
under_mIoU = mIoU_list[under_index]
under_FP = FP_list[under_index]
print('IoU:')
pprint({categories[c]: iou for c, iou in enumerate(best_loglist['IoU'])})
print('Best Th={:.3f}, mIoU={:.3f}%, FP={:.4f}'.format(best_th, best_mIoU, best_FP))
print('Over Th={:.3f}, mIoU={:.3f}%, FP={:.4f}'.format(over_th, over_mIoU, over_FP))
print('Under Th={:.3f}, mIoU={:.3f}%, FP={:.4f}'.format(under_th, under_mIoU, under_FP))
else:
if args.threshold is None:
th_list = np.arange(args.min_th, args.max_th, args.step).tolist()
best_th = 0
best_log_list = None
best_mIoU = 0
for th in th_list:
args.threshold = th
loglist = do_python_eval(args.predict_dir, args.gt_dir, name_list, num_cls)
IoU = {categories[c]: iou for c, iou in enumerate(loglist['IoU'])}
print('IoU: {}'.format(IoU))
print('Th={:.3f}, mIoU={:.3f}%, FP={:.4f}, FN={:.4f}'.format(args.threshold, loglist['mIoU'],
loglist['fp_all'], loglist['fn_all']))
if loglist['mIoU'] > best_mIoU:
best_th = th
best_log_list = loglist
best_mIoU = loglist['mIoU']
pprint(best_log_list)
print('IoU:')
pprint({categories[c]: iou for c, iou in enumerate(best_log_list['IoU'])})
print('Best Th={:.3f}, mIoU={:.3f}%, FP={:.4f}, FN={:.4f}'.format(best_th, best_mIoU,
best_log_list['fp_all'], best_log_list['fn_all']))
else:
loglist = do_python_eval(args.predict_dir, args.gt_dir, name_list, num_cls)
pprint(loglist)
print('IoU:')
pprint({categories[c]: iou for c, iou in enumerate(loglist['IoU'])})
print('Th={:.3f}, mIoU={:.3f}%, FP={:.4f}, FN={:.4f}'.format(args.threshold, loglist['mIoU'],
loglist['fp_all'], loglist['fn_all']))
|
python
| 18 | 0.541674 | 113 | 36.139456 | 294 |
research_code
|
def sendMessage(self, message, username):
"""
Send a message to the client.
"""
data = json.dumps({
"type": "message",
"data": {
"message": message,
"username": username
}
})
self.transport.write(data)
|
python
| 12 | 0.42236 | 41 | 23.846154 | 13 |
inline
|
import base64
from rest_framework.test import APITestCase
from hyperion.models import *
from hyperion.serializers import PostSerializer, UserProfileSerializer
from hyperion.views import post_views
from django.test import TestCase, Client
from django.conf import settings
# python manage.py test -v=2 hyperion.tests.tests_comment_api
class CommentViewTestCase(TestCase):
username_1 = "2haotianzhu"
password_1 = "
username_2 = "hyuntian"
password_2 = "
username_3 = "yuntian1"
password_3 = "
server_username = "test_server"
server_password = "
server_host = "https://cmput404-front-t10.herokuapp.com"
home_host = settings.HYPERION_HOSTNAME
def setUp(self):
# friend of hyuntian
self.u_1 = User.objects.create_user(
username="2haotianzhu", first_name="haotian", last_name="zhu", password="
)
self.s_1 = User.objects.create_user(
username=self.server_username, password=self.server_password
)
UserProfile.objects.filter(author=self.s_1).update(url=self.server_host)
# Server.objects.create(author=self.s_1, url=self.server_host)
# friend of 2haotianzhu
self.u_2 = User.objects.create_user(
username="hyuntian", first_name="yuntian", last_name="zhang", password="
)
Friend.objects.create(profile1=self.u_1.profile, profile2=self.u_2.profile)
# foaf 2haotianzhu friend of hyuntian
self.u_3 = User.objects.create_user(
username="yuntian1", first_name="yuntian", last_name="zhang", password="123456"
)
Friend.objects.create(profile1=self.u_2.profile, profile2=self.u_3.profile)
# foaf 2haotianzhu friend of hyuntian
self.u_4 = User.objects.create_user(
username="yuntian2", first_name="yuntian", last_name="zhang", password="
)
Friend.objects.create(profile1=self.u_2.profile, profile2=self.u_4.profile)
# public stranger
self.u_5 = User.objects.create_user(
username="stranger", first_name="yuntian", last_name="zhang", password="
)
# private stranger
self.u_6 = User.objects.create_user(
username="_stranger", first_name="yuntian", last_name="zhang", password="
)
self.p_1 = Post.objects.create(
title="A post title",
author=self.u_1.profile,
content_type="text/plain",
content="some post content",
visibility="PRIVATE",
unlisted="False",
visible_to = [self.u_1.profile.get_url(), self.u_3.profile.get_url()]
)
self.p_2 = Post.objects.create(
title="A post title",
author=self.u_1.profile,
content_type="text/plain",
content="some post content",
visibility="PUBLIC",
unlisted="False",
)
self.client = None
self.s_1 = Server.objects.create(
author=self.s_1, url="https://cmput404-front-t10.herokuapp.com"
)
self.f_u_1 = UserProfile.objects.create(
display_name="haotian",
host=self.s_1,
url="https://cmput404-front-t10.herokuapp.com/author/1d698d25ff008f7538453c
)
def test_new_comment(self):
credentials = base64.b64encode(
"{}:{}".format(self.username_3, self.password_3).encode()
).decode()
self.client = Client(HTTP_AUTHORIZATION="Basic {}".format(credentials))
data = {
"query": "addComment",
"post": "{}/posts/{}".format(self.home_host, str(self.p_1.id)),
"comment": {
"author": {
"id": "{}/author/{}".format(self.home_host, str(self.u_3.profile.id)),
"host": self.home_host,
"display_name": str(self.u_3.profile.display_name),
},
"comment": "heyya",
"content_type": "text/markdown",
},
}
response = self.client.post(
"/posts/{}/comments".format(str(self.p_1.id)), data, content_type="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["query"], "addComment")
self.assertEqual(response.data["success"], True)
self.assertEqual(
Comment.objects.all()[0].author.display_name, self.u_3.profile.display_name
)
self.assertEqual(Comment.objects.all()[0].comment, "heyya")
def test_new_comment_403(self):
credentials = base64.b64encode(
"{}:{}".format(self.username_2, self.password_2).encode()
).decode()
self.client = Client(HTTP_AUTHORIZATION="Basic {}".format(credentials))
data = {
"query": "addComment",
"post": "{}/posts/{}".format(self.home_host, str(self.p_1.id)),
"comment": {
"author": {
"id": "{}/author/{}".format(self.home_host, str(self.u_2.profile.id)),
"host": self.home_host,
"display_name": str(self.u_2.profile.display_name),
},
"comment": "heyya",
"content_type": "text/markdown",
},
}
response = self.client.post(
"/posts/{}/comments".format(str(self.p_1.id)), data, content_type="application/json"
)
self.assertEqual(response.status_code, 403)
# def test_comment_foreign(self):
# credentials = base64.b64encode(
# "{}:{}".format(self.server_username, self.server_password).encode()
# ).decode()
# self.client = Client(HTTP_AUTHORIZATION="Basic {}".format(credentials))
#
# data = {
# "query": "addComment",
# "post": "{}/posts/{}".format(self.home_host, str(self.p_2.id)),
# "comment": {
# "author": {
# "id": "{}/author/{}".format(self.server_host, str(self.f_u_1.id)),
# "host": self.server_host,
# "display_name": str(self.f_u_1.display_name),
# },
# "comment": "heyya",
# "content_type": "text/markdown",
# },
# }
# print(Server.objects.all())
# response = self.client.post(
# "/posts/{}/comments".format(str(self.p_2.id)), data, content_type="application/json"
# )
# self.assertEqual(response.status_code, 200)
|
python
| 20 | 0.55874 | 99 | 37.75 | 172 |
starcoderdata
|
def download_single_image(self, url_link, pic_prefix_str):
""" Download data according to the url link given.
Args:
url_link (str): url str.
pic_prefix_str (str): pic_prefix_str for unique label the pic
"""
self.download_fault = 0
file_ext = os.path.splitext(url_link)[1] # use for checking valid pic ext
temp_filename = pic_prefix_str + file_ext
temp_filename_full_path = os.path.join(self.gs_raw_dirpath, temp_filename)
temp_filename_full_path = temp_filename_full_path.replace("+", " ")
folder_name = temp_filename_full_path.split("/")
if not os.path.exists(temp_filename_full_path.replace(folder_name[-1], "")):
os.makedirs(temp_filename_full_path.replace(folder_name[-1], ""))
valid_image_ext_list = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff'] # not comprehensive
url = URL(url_link.replace("%2F", "/").replace("%3A", ":"))
try:
if url.redirect:
return # if there is re-direct, return
if file_ext not in valid_image_ext_list:
return # return if not valid image extension
f = open(temp_filename_full_path, 'wb') # save as test.gif
print(url_link)
self.pic_info_list.append(pic_prefix_str + ': ' + url_link)
image = url.download()
# import matplotlib.pyplot as p
# p.imshow(image)
# p.show(image)
f.write(image) # if have problem skip
# if self.__print_download_fault:
print('Problem with processing this data: ', url_link)
self.download_fault = 1
f.close()
except:
pass
|
python
| 12 | 0.552781 | 102 | 44.205128 | 39 |
inline
|
import {Buffer} from 'external:buffer';
import waveHeader from 'external:waveheader';
import BaseEncoder from './BaseEncoder';
const BYTES_PER_SAMPLE = 2;
export default class WaveEncoder extends BaseEncoder {
encode(sampleCount, streams, sampleRate, outputStream) {
const channelCount = streams.length;
if (channelCount !== 1) {
throw new Error('not implemented: encoding multi-channel WAV files');
}
outputStream.write(
waveHeader(
sampleCount * channelCount * BYTES_PER_SAMPLE * 2,
{
bitDepth: BYTES_PER_SAMPLE * 8,
channels: channelCount,
sampleRate,
}
)
);
if (streams.length !== 1) {
throw new Error('not implemented: encoding multi-channel WAV data');
} else if (streams.length === 1) {
const [stream] = streams;
let progress = 0;
const inputSize = sampleCount * BYTES_PER_SAMPLE;
stream.pipe(outputStream);
stream.on('data', chunk => {
progress += chunk.length;
this.sendProgress(progress / inputSize);
});
return new Promise((resolve, reject) => {
stream.once('end', () => {
outputStream.end(() => resolve());
});
stream.once('error', e => reject(e));
});
}
}
};
|
javascript
| 26 | 0.510978 | 81 | 30.978723 | 47 |
starcoderdata
|
from __future__ import absolute_import, unicode_literals
# Optional argcomplete library for CLI (BASH-based) tab completion
try:
from argcomplete import autocomplete
from argcomplete.completers import DirectoriesCompleter, FilesCompleter
except ImportError:
def _argcomplete_noop(*args, **kwargs):
del args, kwargs
autocomplete = _argcomplete_noop
# noinspection PyPep8Naming
FilesCompleter = DirectoriesCompleter = _argcomplete_noop
# Someday add *.meta (once more testing is done with those files
conf_files_completer = FilesCompleter(allowednames=["*.conf"])
|
python
| 8 | 0.76087 | 75 | 34.176471 | 17 |
starcoderdata
|
package com.csye6225.spring2019.util;
import com.google.common.base.Splitter;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import java.io.*;
import java.util.List;
@Log4j2
public class FileUtil {
public static boolean createfolder(String folderPath){
if(Strings.isEmpty(folderPath))
return false;
File file = new File(folderPath);
boolean isSuccess = true;
if(!file.exists()){
isSuccess = file.mkdir();
}
return isSuccess;
}
public static String saveFileToLocal(InputStream input,String folderPath,String fileName,String suffix) throws IOException{
if(input==null||Strings.isEmpty(folderPath)||Strings.isEmpty(fileName)||Strings.isEmpty(suffix)){
log.warn("Invalid params");
return null;
}
if(!createfolder(folderPath)){
log.error("cannot create the folder with path :"+folderPath);
return null;
}
String filePath = String.format("%s/%s.%s",folderPath,fileName,suffix);
File outfile = new File(filePath);
outfile.createNewFile();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(outfile));
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000)){
byte[] b = new byte[1000];
int n;
while ((n = input.read(b)) != -1) {
bos.write(b, 0, n);
}
byte[] buffer = bos.toByteArray();
bf.write(buffer);
bf.flush();
}catch (IOException e){
log.error(e);
return null;
}
return filePath;
}
public static boolean deleteFileFromLocal(String filePath){
File file = new File(filePath);
if(!file.exists()){
log.error("cannot find file with path :"+filePath);
return false;
}
try {
file.delete();
}catch (Exception e){
log.error("Cannot delete file "+filePath);
}
return true;
}
}
|
java
| 14 | 0.588342 | 127 | 30.371429 | 70 |
starcoderdata
|
'use strict';
const uuid = require('uuid').v4;
const express = require('express');
const router = express.Router();
let categoriesDB = {
1: {
'id': 1,
'name': 'Electronics',
'description': 'electronic stuff',
},
2: {
'id': 2,
'name': 'Kitchen',
'description': 'kitchen stuff',
},
};
router.post('/categories', create);
router.get('/categories', getAll);
router.get('/categories/:id', getOne);
router.put('/categories/:id', update);
router.delete('/categories/:id', destroy);
function create(req, res) {
let id = uuid();
let newCategory = {
_id: id,
name: req.body.name,
description: req.body.description,
};
categoriesDB[id] = newCategory;
res.status(201).json(newCategory);
}
function getAll(req, res) {
let output = {
count: Object.values(categoriesDB).length,
results: Object.values(categoriesDB),
};
res.status(200).json(output);
}
function getOne(req, res, next) {
let id = req.params.id;
if(!id){
next('ID is not present within the database');
}
res.status(200).json(categoriesDB[id]);
}
function update(req, res, next) {
let id = req.params.id;
if(!id){
next('ID is not present within the database');
}
let updatedProduct = {
_id: id,
name: req.body.name,
description: req.body.description,
};
categoriesDB[id] = updatedProduct;
res.status(200).json(updatedProduct);
}
function destroy(req, res, next) {
let id = req.params.id;
if(!id){
next('ID is not present within the database');
}
delete categoriesDB[id];
res.status(200).send({});
}
module.exports = router;
|
javascript
| 10 | 0.636137 | 50 | 20.131579 | 76 |
starcoderdata
|
static void test_Jacob_error_point2point()
{
const CPose3D p = CPose3D(
// x y z
normald(10), normald(10), normald(10),
// Yaw pitch roll
rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),
rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));
mrpt::tfest::TMatchingPair pair;
pair.global = {normalf(20), normalf(20), normalf(20)};
pair.local = {normalf(20), normalf(20), normalf(20)};
// Implemented values:
mrpt::math::CMatrixFixed<double, 3, 12> J1;
// const mrpt::math::CVectorFixed<double, 3> error = // (Ignored here)
mp2p_icp::error_point2point(pair, p, J1);
// (12x6 Jacobian)
const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);
const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);
// Numerical Jacobian:
CMatrixDouble numJacob;
{
CVectorFixedDouble<6> x_mean;
x_mean.setZero();
CVectorFixedDouble<6> x_incrs;
x_incrs.fill(1e-6);
mrpt::math::estimateJacobian(
x_mean,
/* Error function to evaluate */
std::function<void(
const CVectorFixedDouble<6>& eps, const CPose3D& D,
CVectorFixedDouble<3>& err)>(
/* Lambda, capturing the pair data */
[pair](
const CVectorFixedDouble<6>& eps, const CPose3D& D,
CVectorFixedDouble<3>& err) {
// SE(3) pose increment on the manifold:
const CPose3D incr = Lie::SE<3>::exp(eps);
const CPose3D D_expEpsilon = D + incr;
err = mp2p_icp::error_point2point(pair, D_expEpsilon);
}),
x_incrs, p, numJacob);
}
if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)
{
std::cerr << "numJacob:\n"
<< numJacob.asEigen() << "\njacob:\n"
<< jacob.asEigen() << "\nDiff:\n"
<< (numJacob - jacob) << "\nJ1:\n"
<< J1.asEigen() << "\n";
THROW_EXCEPTION("Jacobian mismatch, see above.");
}
}
|
c++
| 18 | 0.522477 | 79 | 35.966102 | 59 |
inline
|
#include
#include
using namespace std;
struct Tnode
{
string word;
int count;
Tnode *left;
Tnode *right;
};
class tree
{
private:
Tnode *m_T;
void forShow(Tnode *t);
void forAdd(Tnode *&t, string words);
public:
tree();
void addNode(string words);
void showTree();
};
tree::tree()
{
m_T = NULL;
}
void tree::forShow(Tnode *t)
{
if (t)
{
forShow(t->left);
cout << t->word << " " << t->count << endl;
forShow(t->right);
}
}
void tree::forAdd(Tnode *&t, string words)
{
if (!t)
{
t = new Tnode;
t->word = words;
t->count = 1;
t->left = NULL;
t->right = NULL;
}
else if (words == t->word)
{
t->count += 1;
}
else if (words < t->word)
{
forAdd(t->left, words);
}
else
{
forAdd(t->right, words);
}
return;
}
// Add Node
void tree::addNode(string words)
{
forAdd(m_T, words);
}
// Show the Tree aka sort with
void tree::showTree()
{
if (m_T)
{
forShow(m_T);
}
else
{
cout << "Tree is Empty!" << endl;
}
}
int main()
{
tree T;
string words;
while (cin >> words)
{
T.addNode(words);
}
T.showTree();
return 0;
}
|
c++
| 14 | 0.48392 | 51 | 12.757895 | 95 |
starcoderdata
|
public InputStream openStream(String className) throws IOException {
URL is = loader.runtimeLoader.getResource(className + ".class");
if (is == null) {
throw new IOException("open class failed: " + className);
}
URLConnection connection = is.openConnection();
connection.setUseCaches(false); // ignore jar entry cache, or else you will die
return connection.getInputStream();
}
|
java
| 10 | 0.657596 | 87 | 48.111111 | 9 |
inline
|
var assert = require('assert');
const RNS = artifacts.require('RNS');
var utils = require('./utils.js');
// from https://ethereum.stackexchange.com/questions/11444/web3-js-with-promisified-api
const promisify = (inner) =>
new Promise((resolve, reject) =>
inner((err, res) => {
if (err) { reject(err) }
resolve(res);
})
);
async function getEventsForTx(event, txid) {
const tx = await web3.eth.getTransaction(txid.tx);
return promisify(cb => event({}, {fromBlock: tx.blockNumber, toBlock: tx.blockNumber}).get(cb));
}
contract('RNS', function (accounts) {
var rns = null;
var txids = [];
beforeEach(async function() {
rns = await RNS.new({ gas: 4700000 });
});
after(async function() {
var gas = 0;
for (var n in txids) {
const txid = txids[n];
const tr = txid.receipt;
gas += tr.gasUsed - 21000;
}
console.log("Gas report for RNS.sol: " + gas);
});
it("transfers ownership", async function() {
const txid = await rns.setOwner(0, "0x1234", {from: accounts[0]});
txids.push(txid);
const owner = await rns.owner(0);
assert.equal(owner, "0x0000000000000000000000000000000000001234");
const logs = await getEventsForTx(rns.Transfer, txid);
assert.equal(logs.length, 1);
var args = logs[0].args;
assert.equal(args.node, "0x0000000000000000000000000000000000000000000000000000000000000000");
assert.equal(args.ownerAddress, "0x0000000000000000000000000000000000001234");
});
it("prohibits transfers by non-owners", async function() {
try {
await rns.setOwner(1, "0x1234", {from: accounts[0]});
assert.fail();
}
catch (ex) {
assert.ok(utils.isVMException(ex));
}
const owner = await rns.owner(1);
assert.equal(owner, "0x0000000000000000000000000000000000000000");
});
it("sets resolvers", async function() {
const txid = await rns.setResolver(0, "0x1234", {from: accounts[0]});
txids.push(txid);
const resolver = await rns.resolver(0);
assert.equal(resolver, "0x0000000000000000000000000000000000001234");
const logs = await getEventsForTx(rns.NewResolver, txid);
assert.equal(logs.length, 1);
var args = logs[0].args;
assert.equal(args.node, "0x0000000000000000000000000000000000000000000000000000000000000000");
assert.equal(args.resolverAddress, "0x0000000000000000000000000000000000001234");
});
it("prohibits setting resolver by non-owners", async function() {
try {
await rns.setResolver(1, "0x1234", {from: accounts[0]});
assert.fail();
}
catch (ex) {
assert.ok(utils.isVMException(ex));
}
const resolver = await rns.resolver(1);
assert.equal(resolver, "0x0000000000000000000000000000000000000000");
});
it("permits setting TTL", async function() {
const txid = await rns.setTTL(0, 3600, {from: accounts[0]});
txids.push(txid);
const ttl = await rns.ttl(0);
assert.equal(ttl.toNumber(), 3600);
const logs = await getEventsForTx(rns.NewTTL, txid);
assert.equal(logs.length, 1);
var args = logs[0].args;
assert.equal(args.node, "0x0000000000000000000000000000000000000000000000000000000000000000");
assert.equal(args.ttlValue.toNumber(), 3600);
});
it("prohibits setting TTL by non-owners", async function() {
try {
await rns.setTTL(1, 3600, {from: accounts[0]});
assert.fail();
}
catch (ex) {
assert.ok(utils.isVMException(ex));
}
const ttl = await rns.ttl(1);
assert.equal(ttl.toNumber(), 0);
});
it("creates subnodes", async function() {
const txid = await rns.setSubnodeOwner(0, web3.sha3('eth'), accounts[1], {from: accounts[0]});
txids.push(txid);
const owner = await rns.owner(utils.node);
assert.equal(owner, accounts[1]);
var logs = await getEventsForTx(rns.NewOwner, txid);
assert.equal(logs.length, 1);
var args = logs[0].args;
assert.equal(args.node, "0x0000000000000000000000000000000000000000000000000000000000000000");
assert.equal(args.label, web3.sha3('eth'));
assert.equal(args.ownerAddress, accounts[1]);
});
it("prohibits subnode creation by non-owners", async function() {
try {
await rns.setSubnodeOwner(0, web3.sha3('eth'), accounts[1], {from: accounts[1]});
assert.fail();
}
catch (ex) {
assert.ok(utils.isVMException(ex));
}
const owner = await rns.owner(utils.node);
assert.equal(owner, "0x0000000000000000000000000000000000000000");
});
});
|
javascript
| 20 | 0.68987 | 97 | 28.616438 | 146 |
starcoderdata
|
'use strict';
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
// Redirect all the other resquests
// this.app.get('*', (req: Request, res: Response) => {
// if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
// res.sendFile(path.resolve(`../backend/dist/backend/${req.url}`));
// } else {
// res.sendFile(path.resolve('../backend/dist/backend/index.html'));
// }
// });
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
// // 'use strict';
// // const Hapi = require('hapi');
// // const Hoek = require('hoek');
// // const Settings = require('./settings/');
// // const server = new Hapi.Server({
// // host: Settings.host,
// // port: Settings.port
// // });
// // server.route({
// // method: 'GET',
// // path: '/',
// // handler: (request, reply) => {
// // reply('Hello, world!');
// // }
// // });
// // server.start((err) => {
// // Hoek.assert(!err, err);
// // console.log(`Server running at: ${server.info.uri}`);
// // });
// // 'use strict';
// // const Hapi = require('@hapi/hapi');
// // const Settings = require('./settings/');
// // const init = async () => {
// // const server = Hapi.server({
// // port: Settings.port,
// // host: Settings.host
// // });
// // await server.start();
// // console.log('Server running on %s', server.info.uri);
// // };
// // process.on('unhandledRejection', (err) => {
// // console.log(err);
// // process.exit(1);
// // });
// // init();
// 'use strict';
// const Hapi = require('@hapi/hapi');
// const Settings = require('./settings/');
// console.log(Settings);
// // process.on('unhandledRejection', (err) => {
// // console.log(err);
// // process.exit(1);
// // });
// // init();
|
javascript
| 16 | 0.503408 | 77 | 21.701031 | 97 |
starcoderdata
|
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# Copyright (c) 2018, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------------------------------------------------------------------
import pytest
from enaml.fonts import (coerce_font, Font, _SIZES, _UNITS, _WEIGHTS, _STYLES,
_VARIANTS, _STRETCH)
# The order defining a CSS3 string is:
# style variant weight stretch size line-height family.
# In our case line-height is not supported
@pytest.mark.parametrize('family', ['Helvetica', 'Arial'])
@pytest.mark.parametrize('size', ['small', 'medium', 'large',
'1in', '1cm', '10mm', '10pt', '10pc', '10px']
)
@pytest.mark.parametrize('weight', ['', 'normal', 'bold', '300'])
@pytest.mark.parametrize('style', ['', 'normal', 'italic', 'oblique'])
@pytest.mark.parametrize('variant', ['', 'normal', 'small-caps'])
@pytest.mark.parametrize('stretch', ['', 'condensed', 'normal', 'expanded'])
def test_font_coercion(family, size, weight, style, variant, stretch):
"""Test the font parsing produce the expected font objects.
"""
font = ' '.join([style, variant, weight,
stretch, size, family])
font = ' '.join(font.split()) # Handle multiple whitespaces
print('CSS3 font: ', font)
font = coerce_font(font)
assert isinstance(font, Font)
assert repr(font)
assert font.family == family
if size in _SIZES:
assert font.pointsize == _SIZES[size]
else:
pt_size = (_UNITS[size[-2:]](int(size[:-2])) if len(size) > 2
else int(size))
assert font.pointsize == pt_size
assert font.weight == _WEIGHTS[weight or 'normal']
assert font.style == _STYLES[style or 'normal']
assert font.caps == _VARIANTS[variant or 'normal']
assert font.stretch == _STRETCH[stretch or 'normal']
assert font._tkdata is None
try:
from enaml.qt.q_resource_helpers import get_cached_qfont
except Exception:
return
get_cached_qfont(font)
assert font._tkdata is not None
|
python
| 18 | 0.581818 | 79 | 38.152542 | 59 |
starcoderdata
|
/*
* Copyright 2016-2021 Pnoker. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dc3.center.data.service.impl;
import com.alibaba.fastjson.JSON;
import com.dc3.center.data.service.DataCustomService;
import com.dc3.common.bean.point.PointValue;
import com.dc3.common.bean.point.TsPointValue;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author pnoker
*/
@Slf4j
@Service
public class DataCustomServiceImpl implements DataCustomService {
private static final String putUrl = "";
@Resource
private OkHttpClient okHttpClient;
@Override
public void preHandle(PointValue pointValue) {
// TODO 接收数据之后,存储数据之前的操作
}
@Override
public void postHandle(PointValue pointValue) {
String metric = pointValue.getDeviceId().toString();
List tsPointValues = convertToTsPointValues(metric, pointValue);
savePointValueToOpenTsdb(tsPointValues);
}
@Override
public void postHandle(Long deviceId, List pointValues) {
String metric = deviceId.toString();
List tsPointValues = pointValues.stream()
.map(pointValue -> convertToTsPointValues(metric, pointValue))
.reduce(new ArrayList<>(), (first, second) -> {
first.addAll(second);
return first;
});
List partition = Lists.partition(tsPointValues, 100);
partition.forEach(this::savePointValueToOpenTsdb);
}
@Override
public void afterHandle(PointValue pointValue) {
// TODO 接收数据之后,存储数据的时候的操作,此处可以自定义逻辑,将数据存放到别的数据库,或者发送到别的地方
}
/**
* convert point value to opentsdb point value
*
* @param metric Metric Name
* @param pointValue Point Value
* @return TsPointValue Array
*/
private List convertToTsPointValues(String metric, PointValue pointValue) {
String point = pointValue.getPointId().toString();
String value = pointValue.getValue();
Long timestamp = pointValue.getOriginTime().getTime();
List tsPointValues = new ArrayList<>(4);
TsPointValue tsValue = new TsPointValue(metric, value);
tsValue.setTimestamp(timestamp)
.addTag("point", point)
.addTag("valueType", "value");
tsPointValues.add(tsValue);
TsPointValue tsRawValue = new TsPointValue(metric, value);
tsRawValue.setTimestamp(timestamp)
.addTag("point", point)
.addTag("valueType", "rawValue");
tsPointValues.add(tsRawValue);
return tsPointValues;
}
/**
* send point value to opentsdb
*
* @param tsPointValues TsPointValue Array
*/
private void savePointValueToOpenTsdb(List tsPointValues) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JSON.toJSONString(tsPointValues));
Request request = new Request.Builder()
.url(putUrl)
.post(requestBody)
.build();
try {
Response response = okHttpClient.newCall(request).execute();
ResponseBody body = response.body();
if (null != body) {
log.debug("send pointValue to opentsdb {}: {}", response.message(), body.string());
body.close();
}
response.close();
} catch (IOException e) {
log.error("send pointValue to opentsdb error: {}", e.getMessage());
}
}
}
|
java
| 14 | 0.659258 | 138 | 33.362205 | 127 |
starcoderdata
|
#pragma once
#include "Interfaces/filesystem/path.h"
namespace Engine {
namespace Ini {
struct INI_EXPORT IniFile {
IniFile();
~IniFile();
IniFile &operator=(const IniFile &) = delete;
IniSection &operator[](const std::string &key);
void clear();
void saveToDisk(const Filesystem::Path &path) const;
bool loadFromDisk(const Filesystem::Path &path);
std::map<std::string, IniSection>::iterator begin();
std::map<std::string, IniSection>::iterator end();
std::map<std::string, IniSection>::const_iterator begin() const;
std::map<std::string, IniSection>::const_iterator end() const;
private:
std::map<std::string, IniSection> mSections;
};
}
}
|
c
| 13 | 0.620335 | 72 | 22.575758 | 33 |
starcoderdata
|
// --- JavaScript Document --- //
window.onload = maxWindow;
function maxWindow() {
window.moveTo(0, 0);
window.resizeTo(screen.width, screen.height);
window.focus();
/*
if (document.all) {
top.window.resizeTo(screen.availWidth, screen.availHeight);
}
else if (document.layers || document.getElementById) {
if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth) {
top.window.outerHeight = screen.availHeight;
top.window.outerWidth = screen.availWidth;
}
}
*/
}
function showscreen(){
var windowWidth = 850;
var windowHeight = 800;
window.resizeTo(windowWidth,windowHeight);
var xPos = (screen.width/2) - (windowWidth/2);
var yPos = (screen.height/2) - (windowHeight/2);
window.moveTo(xPos, yPos);
window.focus();
}
function checkKey(n){
if (window.event.keyCode == 13){ //Enter
schstock();
}else if(window.event.keyCode == 37){ //Left
//ChkKeyLeft(n,i)
}else if(window.event.keyCode == 38){ //Up
//ChkKeyUp(n,i);
}else if(window.event.keyCode == 39){ //Right
//ChkKeyRight(n,i);
}else if(window.event.keyCode == 40){ //Down
//ChkKeyDown(n,i);
}
}
function test(){
alert('ok');
}
function schsale(){
var slbrch = $("#slbrch").val();
var datepicker1 = $("#datepicker1").val();
var datepicker2 = $("#datepicker2").val();
if((slbrch == '0') || (datepicker1 == '') || (datepicker2 == '') || (datepicker1>datepicker2)){
alert ("Not selected branches Or Not Enter dates !!!");
}else{
//alert(slbrch + "," + datepicker1 + "," + datepicker2 );
//document.getElementById('a1').innerHTML = " Loading..." + "<img src='images/preloader-01.gif' />";
$("#a1").html(" Loading..." + "<img src='images/preloader-01.gif' />");
$("#a2").html("");
$("#a3").html("");
$("#a4").html("");
$("#m1").html("");
$("#m1").hide();
$.post(
"sumofprovice.php",
{
slbrch: slbrch,
datepicker1: datepicker1,
datepicker2: datepicker2
},
function(data){
$("#a1").html(data);
}
);
//showchart
//showchart1(slbrch,datepicker1,datepicker2);
}
}
function showchart1(){
var slbrch = $("#slbrch").val();
var datepicker1 = $("#datepicker1").val();
var datepicker2 = $("#datepicker2").val();
if((slbrch == '0') || (datepicker1 == '') || (datepicker2 == '') || (datepicker1>datepicker2)){
//
}else{
$("#a2").html("");
$("#m1").html("");
$("#m1").hide();
$.post(
"chart1.php",
{
slbrch : slbrch,
datepicker1: datepicker1,
datepicker2: datepicker2
},
function (data){
$("#a2").html(data);
}
);
}
}
function schsumdistrict(pv,totalpv){
var slbrch = $("#slbrch").val();
var datepicker1 = $("#datepicker1").val();
var datepicker2 = $("#datepicker2").val();
if((slbrch == '0') || (datepicker1 == '') || (datepicker2 == '') || (datepicker1>datepicker2)){
//alert ("Not selected branches Or Not Enter dates !!!");
}else{
$("#a3").html(" Loading..." + "<img src='images/preloader-01.gif' />");
$("#a4").html("");
$("#m1").html("");
$("#m1").hide();
$.post(
"sumofdistrict.php",
{
slbrch: slbrch,
datepicker1: datepicker1,
datepicker2: datepicker2,
pv: pv,
totalpv: totalpv
},
function(data){
$("#a3").html(data);
}
);
}
}
function showchart2(pv,totalpv){
var slbrch = $("#slbrch").val();
var datepicker1 = $("#datepicker1").val();
var datepicker2 = $("#datepicker2").val();
if((slbrch == '0') || (datepicker1 == '') || (datepicker2 == '') || (datepicker1>datepicker2)){
//alert ("Not selected branches Or Not Enter dates !!!");
}else{
//$("#a4").html(" Loading..." + "<img src='images/preloader-01.gif' />");
$("#m1").html("");
$("#m1").hide();
$.post(
"chart2.php",
{
slbrch: slbrch,
datepicker1: datepicker1,
datepicker2: datepicker2,
pv: pv,
totalpv: totalpv
},
function(data){
$("#a4").html(data);
}
);
}
}
function showpdf(){
$("#m1").show();
$("#m1").html(" Loading..." + "<img src='images/preloader-01.gif' />");
$("#a1").html("");
$("#a2").html("");
$("#a3").html("");
$("#a4").html("");
$("#m1").html("<iframe src='Manual.pdf' style='width:900px; height:550px;' frameborder='0'>
}
function exportpiechart(){
var chart = $('#container').highcharts();
chart.exportChart({
type: 'image/png',
filename: 'my_chart_pie'
});
setTimeout("",3000);
exportbarchart();
}
function exportbarchart(){
var chart2 = $('#container2').highcharts();
chart2.exportChart({
type: 'image/png',
filename: 'my_chart_bar'
});
}
/*
function schstock(){
var sj = document.getElementById('sj');
var sb = document.getElementById('sb');
var st = document.getElementById('st');
var data = 'sj=' + sj.value + '&sb=' + sb.value + '&st=' + st.value;
//alert(data);
if(st.value != ''){
if(sb.value=='1'){
document.getElementById('a2').innerHTML = " Loading..." + "<img src='images/preloader-01.gif' />";
ajaxLoad('post', 'schstock.php', data,'a2');
}
if(sb.value=='2'){
document.getElementById('a2').innerHTML = " Loading..." + "<img src='images/preloader-01.gif' />";
ajaxLoad('post', 'schstockbyname2.php', data,'a2');
}
}else{
alert("กรุณาตรวจสอบ ข้อมูลคำค้นหา ให้ครบถ้วน");
st.focus();
st.select();
}
}
function toggledetail(){
var dt1 = document.getElementById('sd1');
if(dt1.style.display == 'block'){
dt1.style.display = 'none';
}else{
dt1.style.display = 'block';
}
}
function toggledetail2(numi){
var nametbody = 'sd' + numi;
var nmaediv = 'sdt' + numi;
var dt2 = document.getElementById(nametbody);
var dt3 = document.getElementById(nmaediv);
if(dt2.style.display == 'block'){
dt2.style.display = 'none';
}else{
dt2.style.display = 'block';
var sj = document.getElementById('sj');
var sb = document.getElementById('sb');
var st = document.getElementById('st');
var data = 'sj=' + sj.value + '&sb=' + sb.value + '&st=' + st.value;
if(sb.value=='2'){
dt3.innerHTML = " Loading..." + "<img src='images/preloader-01.gif' />";
ajaxLoad('post', 'detailstock.php', data,nmaediv);
}
}
}
function selectcode(containerid){
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
}
}
*/
// --- End javascript --- //
|
javascript
| 17 | 0.58515 | 104 | 23.373626 | 273 |
starcoderdata
|
<?php
use models\UserAccountModel;
use models\SiteModel;
use models\GroupModel;
use models\EventModel;
use repositories\UserAccountRepository;
use repositories\SiteRepository;
use repositories\GroupRepository;
use repositories\EventRepository;
use repositories\builders\EventRepositoryBuilder;
/**
*
* @link https://opentechcalendar.co.uk/ This is the software for Open Tech Calendar!
* @link https://gitlab.com/opentechcalendar You will find it's source here!
* @license https://gitlab.com/opentechcalendar/opentechcalendar/blob/master/LICENSE.txt 3-clause BSD
* @copyright (c) JMB Technology Limited, https://www.jmbtechnology.co.uk/
*/
class EventDuplicateTest extends \BaseAppWithDBTest
{
public function test1()
{
$this->app['timesource']->mock(2014, 5, 1, 7, 0, 0);
$user = new UserAccountModel();
$user->setEmail("
$user->setUsername("test");
$user->setPassword("password");
$user1 = new UserAccountModel();
$user1->setEmail("
$user1->setUsername("test1");
$user1->setPassword("password");
$user2 = new UserAccountModel();
$user2->setEmail("
$user2->setUsername("test2");
$user2->setPassword("password");
$userRepo = new UserAccountRepository($this->app);
$userRepo->create($user);
$userRepo->create($user1);
$userRepo->create($user2);
$site = new SiteModel();
$site->setTitle("Test");
$site->setSlug("test");
$siteRepo = new SiteRepository($this->app);
$siteRepo->create($site, $user, array(), $this->getSiteQuotaUsedForTesting());
$event1 = new EventModel();
$event1->setSummary("test");
$event1->setDescription("test test");
$event1->setStartAt(getUTCDateTime(2014, 5, 10, 19, 0, 0));
$event1->setEndAt(getUTCDateTime(2014, 5, 10, 21, 0, 0));
$event1->setUrl("http://www.info.com");
$event1->setTicketUrl("http://www.tickets.com");
$event2 = new EventModel();
$event2->setSummary("test this looks similar");
$event2->setDescription("test test");
$event2->setStartAt(getUTCDateTime(2014, 5, 10, 19, 0, 0, 'Europe/London'));
$event2->setEndAt(getUTCDateTime(2014, 5, 10, 21, 0, 0, 'Europe/London'));
$event2->setUrl("http://www.info.com");
$event2->setTicketUrl("http://www.tickets.com");
$eventRepository = new EventRepository($this->app);
$eventRepository->create($event1, $site, $user);
$eventRepository->create($event2, $site, $user);
$userAtEventRepo = new \repositories\UserAtEventRepository($this->app);
$user1AtEvent1 = $userAtEventRepo->loadByUserAndEventOrInstanciate($user1, $event1);
$user1AtEvent1->setIsPlanAttending(true);
$user1AtEvent1->setIsPlanPublic(true);
$userAtEventRepo->save($user1AtEvent1);
$user1AtEvent2 = $userAtEventRepo->loadByUserAndEventOrInstanciate($user1, $event2);
$user1AtEvent2->setIsPlanMaybeAttending(true);
$userAtEventRepo->save($user1AtEvent2);
$user2AtEvent2 = $userAtEventRepo->loadByUserAndEventOrInstanciate($user2, $event2);
$user2AtEvent2->setIsPlanMaybeAttending(true);
$userAtEventRepo->save($user2AtEvent2);
//=============================================== Test before
$event2 = $eventRepository->loadBySlug($site, $event2->getSlug());
$this->assertFalse($event2->getIsDeleted());
$this->assertNull($event2->getIsDuplicateOfId());
$user1AtEvent1 = $userAtEventRepo->loadByUserAndEvent($user1, $event1);
$this->assertNotNull($user1AtEvent1);
$this->assertEquals(true, $user1AtEvent1->getIsPlanAttending());
$this->assertEquals(false, $user1AtEvent1->getIsPlanMaybeAttending());
$this->assertEquals(true, $user1AtEvent1->getIsPlanPublic());
$user1AtEvent2 = $userAtEventRepo->loadByUserAndEvent($user1, $event2);
$this->assertNotNull($user1AtEvent2);
$this->assertEquals(false, $user1AtEvent2->getIsPlanAttending());
$this->assertEquals(true, $user1AtEvent2->getIsPlanMaybeAttending());
$this->assertEquals(false, $user1AtEvent2->getIsPlanPublic());
$user2AtEvent1 = $userAtEventRepo->loadByUserAndEvent($user2, $event1);
$this->assertNull($user2AtEvent1);
$user2AtEvent2 = $userAtEventRepo->loadByUserAndEvent($user2, $event2);
$this->assertNotNull($user2AtEvent2);
$this->assertEquals(false, $user2AtEvent2->getIsPlanAttending());
$this->assertEquals(true, $user2AtEvent2->getIsPlanMaybeAttending());
$this->assertEquals(false, $user2AtEvent2->getIsPlanPublic());
//==================================================== Mark
$this->app['timesource']->mock(2014, 5, 1, 8, 0, 0);
$eventRepository->markDuplicate($event2, $event1, $user);
//==================================================== Test Duplicate
$event2 = $eventRepository->loadBySlug($site, $event2->getSlug());
$this->assertTrue($event2->getIsDeleted());
$this->assertEquals($event1->getId(), $event2->getIsDuplicateOfId());
// This should not have changed; as there already was data here we don't change it.
$user1AtEvent1 = $userAtEventRepo->loadByUserAndEvent($user1, $event1);
$this->assertNotNull($user1AtEvent1);
$this->assertEquals(true, $user1AtEvent1->getIsPlanAttending());
$this->assertEquals(false, $user1AtEvent1->getIsPlanMaybeAttending());
$this->assertEquals(true, $user1AtEvent1->getIsPlanPublic());
$user1AtEvent2 = $userAtEventRepo->loadByUserAndEvent($user1, $event2);
$this->assertNotNull($user1AtEvent2);
$this->assertEquals(false, $user1AtEvent2->getIsPlanAttending());
$this->assertEquals(true, $user1AtEvent2->getIsPlanMaybeAttending());
$this->assertEquals(false, $user1AtEvent2->getIsPlanPublic());
// This should now change, the mark dupe function should have copied it.
$user2AtEvent1 = $userAtEventRepo->loadByUserAndEvent($user2, $event1);
$this->assertNotNull($user2AtEvent1);
$this->assertEquals(false, $user2AtEvent1->getIsPlanAttending());
$this->assertEquals(true, $user2AtEvent1->getIsPlanMaybeAttending());
$this->assertEquals(false, $user2AtEvent1->getIsPlanPublic());
$user2AtEvent2 = $userAtEventRepo->loadByUserAndEvent($user2, $event2);
$this->assertNotNull($user2AtEvent2);
$this->assertEquals(false, $user2AtEvent2->getIsPlanAttending());
$this->assertEquals(true, $user2AtEvent2->getIsPlanMaybeAttending());
$this->assertEquals(false, $user2AtEvent2->getIsPlanPublic());
}
}
|
php
| 13 | 0.647351 | 101 | 42.360759 | 158 |
starcoderdata
|
import datetime
import os
import staticstorage
def debug_dump(filename, content, storage=None):
"""Create debug dump file with specified name and content"""
ts = datetime.datetime.utcnow().strftime('%d-%m-%Y_%H-%M-%S')
path, suffix = os.path.splitext(filename)
filename = "{}_{}{}".format(path, ts, suffix)
if type(content) is unicode:
content = content.encode('utf-8')
store = storage or staticstorage.GCSStorage()
store.put(filename, content)
|
python
| 10 | 0.68381 | 65 | 29.882353 | 17 |
starcoderdata
|
// Copyright (c) and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Web.Memory;
using Xunit;
namespace SixLabors.ImageSharp.Web.Tests.Memory
{
public class PooledBufferManagerTests
{
private readonly IBufferManager manager = new PooledBufferManager();
[Theory]
[InlineData(32)]
[InlineData(512)]
[InlineData(PooledBufferManager.DefaultMaxLength - 1)]
public void BuffersArePooled(int size)
{
Assert.True(this.CheckIsRentingPooledBuffer
}
[Theory]
[InlineData(32, 0)]
[InlineData(0, 25)]
public void PooledBufferManagerThrowsWhenParamsAreInvalid(int maxLength, int maxArraysPerBucket)
{
Assert.Throws =>
{
var m = new PooledBufferManager(maxLength, maxArraysPerBucket);
});
}
[Theory]
[InlineData(32)]
[InlineData(512)]
[InlineData(PooledBufferManager.DefaultMaxLength - 1)]
public void BufferLengthIsCorrect(int size)
{
using (IByteBuffer buffer = this.manager.Allocate(size))
{
Assert.Equal(size, buffer.Length);
}
}
///
/// Rent a buffer -> return it -> re-rent -> verify if it's array points to the previous location
///
private bool CheckIsRentingPooledBuffer length)
where T : struct
{
IByteBuffer buffer = this.manager.Allocate(length);
ref byte ptrToPreviousPosition0 = ref MemoryMarshal.GetReference
buffer.Dispose();
buffer = this.manager.Allocate(length);
bool sameBuffers = Unsafe.AreSame(ref ptrToPreviousPosition0, ref MemoryMarshal.GetReference
buffer.Dispose();
return sameBuffers;
}
}
}
|
c#
| 20 | 0.617898 | 126 | 31.492308 | 65 |
starcoderdata
|
using System;
using System.IO;
using System.Net;
using System.Text;
using Uno.UXNinja.PerformanceTests.Core.Loggers.LoggersEntities;
namespace Uno.UXNinja.PerformanceTests.Core.Loggers
{
public class ResultFtpLogger : BaseResultLogger
{
public ResultFtpLogger(string logDirectoryName, string branchName, string buildNumber)
: base(logDirectoryName, branchName, buildNumber)
{
CreateDirectory(_logDirectoryPath);
}
#region Override Methods
public override void ProjectStarted(string projectName)
{
base.ProjectStarted(projectName);
DeleteFileIfExists(_logFileName);
}
public override void ProjectFinished()
{
if (_project != null)
UploadFile(_logFileName);
}
protected override string GetLogDirectoryFullPath(DateTime currDate, string logDirectoryName, string buildNumber)
{
var sessionDirectoryName = string.IsNullOrEmpty(buildNumber) ? currDate.Ticks.ToString() : buildNumber;
var baseUri = new Uri(logDirectoryName);
var dateDirectoryUri = string.IsNullOrEmpty(_branchName) ? new Uri(baseUri, string.Format("unnamed/{0}/", currDate.ToString("MM_dd_yyy")))
: new Uri(baseUri, string.Format("{0}/{1}/", _branchName, currDate.ToString("MM_dd_yyy")));
var num = GetNumberOfSessionDirectories(dateDirectoryUri.ToString());
return new Uri(dateDirectoryUri, string.Format("{0}__{1}/", num + 1, sessionDirectoryName)).ToString();
}
#endregion
#region Private Methods
private void DeleteFileIfExists(string path)
{
var request = GetFtpWebRequest(path);
request.Method = WebRequestMethods.Ftp.DeleteFile;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
response.Close();
if (response.StatusCode != FtpStatusCode.ActionNotTakenFileUnavailable)
{
throw ex;
}
}
}
private void CreateDirectory(string path)
{
var request = GetFtpWebRequest(path);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
response.Close();
if (response.StatusCode != FtpStatusCode.ActionNotTakenFileUnavailable)
{
throw ex;
}
}
}
private void UploadFile(string path)
{
var content = Encoding.UTF8.GetBytes(XmlTools.ToXmlString
var request = GetFtpWebRequest(path);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.ContentLength = content.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(content, 0, content.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
private int GetNumberOfSessionDirectories(string path)
{
var res = 0;
var request = GetFtpWebRequest(path);
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
res = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Length;
}
response.Close();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
response.Close();
if (response.StatusCode != FtpStatusCode.ActionNotTakenFileUnavailable)
{
throw ex;
}
}
return res;
}
private FtpWebRequest GetFtpWebRequest(string requestUri)
{
return (FtpWebRequest)FtpWebRequest.Create(requestUri);
}
#endregion
}
}
|
c#
| 22 | 0.575426 | 160 | 34.73913 | 138 |
starcoderdata
|
/* Communication Networks - Project Phase C
- 4-3258
- 4-1805
This is the private chat.
*/
package client;
import javax.swing.*; /* gui */
import java.awt.*; /* gui */
import java.awt.event.*; /* gui */
public class private_chat extends JPanel implements ActionListener,KeyListener {
public JTextArea private_chat_area = new JTextArea();
JTextField private_message_text = new JTextField();
JButton private_send_button = new JButton("Send");
JButton private_close_button;
client main_client;
chat parent;
public String private_nickname;
/* private panel constructor */
public private_chat(String pn, client c, chat ch, int width, int height) {
init_components(this,width,height,1);
repaint();
validate();
private_nickname = pn;
main_client = c;
parent = ch;
}
/* another constructor, for the public panel only,
* this is a little confusing, the constructor's parameters
* are the same but with different order so we can have another
* signature to the method.
*/
public private_chat(client c, String pn, chat ch,int width,int height){
init_components(this,width,height,0);
parent=ch;
private_nickname = pn;
main_client=c;
validate();
repaint();
}
/* to add the components to the frame */
public void init_components(private_chat parent , int w , int h , int type){
parent.setSize(w, h);
setLayout(null);
if(type == 0) {
private_chat_area.setBounds(0, 0, parent.getWidth()-160, parent.getHeight()-30);
}
else {
private_chat_area.setBounds(0, 0, parent.getWidth()-10, parent.getHeight()-30);
}
private_chat_area.setBorder(BorderFactory.createLineBorder(Color.gray));
private_chat_area.setAutoscrolls(true);
private_chat_area.setEditable(false);
parent.add(private_chat_area);
private_chat_area.setVisible(true);
private_message_text.setBounds(0, parent.getHeight()-20, parent.getWidth()-200, 20);
parent.add(private_message_text);
// private_message_text.requestFocus();
private_message_text.addKeyListener(this);
private_message_text.setVisible(true);
private_send_button.setBounds(private_message_text.getWidth()+5,
private_chat_area.getHeight()+5,
90, 25);
private_send_button.addActionListener(parent);
parent.add(private_send_button);
private_send_button.setVisible(true);
if(type==0) private_close_button = new JButton("Exit");
else private_close_button = new JButton("Close");
private_close_button.setBounds(private_send_button.getLocation().x+private_send_button.getWidth()+5,
private_chat_area.getHeight()+5,
90, 25);
private_close_button.addActionListener(parent);
parent.add(private_close_button);
private_close_button.setVisible(true);
parent.setVisible(true);
}
/* a key listener used to detect the "enter" press */
public void keyPressed(KeyEvent e){
if(e.getKeyCode()=='\n'){sending();}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void actionPerformed(ActionEvent event) {
String action_event = event.getActionCommand();
if(action_event.equals("Send")) {
sending();
}
/* to just close a tab of private chat */
else if(action_event.equals("Close")) {
parent.remove_private_chat_tab(private_nickname);
}
/* to disconnect and exit */
else if(action_event.equals("Exit")){
main_client.disconnect();
System.exit(0);
}
}
/* to send a message to the server */
public void sending(){
if(!private_message_text.getText().trim().equals("")) {
try {
if(parent.chat_tabs.getSelectedIndex()==0)
main_client.data_out.writeBytes("MTA," + parent.nickname + "," +
private_message_text.getText() + "\n");
else{
main_client.data_out.writeBytes("MSG," + private_nickname + "," +
private_message_text.getText() + "\n");
private_chat_area.setText(private_chat_area.getText()+ " "+
private_message_text.getText() + "\n");
}
private_message_text.setText("");
}
catch(Exception e) {
System.out.println("[error] private_chat_action_send - exception: " + e);
}
}
else {
parent.status_text.setText("Cannot send empty message.");
}
}
}
|
java
| 19 | 0.677525 | 103 | 29.049296 | 142 |
starcoderdata
|
func (c *Client) Do(method, endpoint string, requestData, responseData interface{}) error {
// Throw an error if the user tries to make a request if the client is
// logged out/unauthenticated, but make an exemption for when the
// caller is trying to log in.
if !c.LoggedIn() && method != "POST" && endpoint != "Session" {
return errors.New("Will not perform request; httpclient is closed")
}
var err error
// Marshal the request data into a byte slice.
if c.verbose {
log.Println("Marshaling request data")
}
var js []byte
if requestData != nil {
js, err = json.Marshal(requestData)
} else {
js = []byte("")
}
if err != nil {
return err
}
// Create a new http.Request object, and set the necessary headers to
// authorize the request, and specify the content type.
url := fmt.Sprintf("%s/%s", DynAPIPrefix, endpoint)
var req *http.Request
req, err = http.NewRequest(method, url, bytes.NewReader(js))
if err != nil {
return err
}
req.Header.Set("Auth-Token", c.Token)
req.Header.Set("Content-Type", "application/json")
if c.verbose {
log.Printf("Making %s request to %q", method, url)
}
var resp *http.Response
resp, err = c.httpclient.Do(req)
if err != nil {
if c.verbose {
respBody, _ := ioutil.ReadAll(resp.Body)
log.Printf("%s", string(respBody))
}
return err
} else if resp.StatusCode != 200 {
if c.verbose {
// Print out the response body.
respBody, _ := ioutil.ReadAll(resp.Body)
log.Printf("%s", string(respBody))
}
return errors.New(fmt.Sprintf("Bad response, got %q", resp.Status))
}
// Unmarshal the response data into the provided struct.
if c.verbose {
log.Println("Reading in response data")
}
var respBody []byte
respBody, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if c.verbose {
log.Println("Unmarshaling response data")
}
err = json.Unmarshal(respBody, &responseData)
if err != nil {
respBody, _ := ioutil.ReadAll(resp.Body)
if resp.ContentLength == 0 || resp.ContentLength == -1 {
log.Println("Zero-length content body")
} else {
log.Printf("%s", string(respBody))
}
}
return err
}
|
go
| 13 | 0.669325 | 91 | 25.333333 | 81 |
inline
|
package com.github.sd4324530.fastweixin.api;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.api.response.BaseResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.github.sd4324530.fastweixin.util.BeanUtil;
import com.github.sd4324530.fastweixin.util.JSONUtil;
import com.github.sd4324530.fastweixin.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* 网页授权API
*
* @author peiyu
*/
public class OauthAPI extends BaseAPI {
private static final Logger LOG = LoggerFactory.getLogger(OauthAPI.class);
public OauthAPI(ApiConfig config) {
super(config);
}
/**
* 生成回调url,这个结果要求用户在微信中打开,即可获得token,并指向redirectUrl
*
* @param redirectUrl 用户自己设置的回调地址
* @param scope 授权作用域
* @param state 用户自带参数
* @return 回调url,用户在微信中打开即可开始授权
*/
public String getOauthPageUrl(String redirectUrl, OauthScope scope, String state) {
BeanUtil.requireNonNull(redirectUrl, "redirectUrl is null");
BeanUtil.requireNonNull(scope, "scope is null");
String userState = StrUtil.isBlank(state) ? "STATE" : state;
String url = null;
try {
url = URLEncoder.encode(redirectUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.error("异常", e);
}
StringBuilder stringBuilder = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
stringBuilder.append("appid=").append(this.config.getAppid())
.append("&redirect_uri=").append(url)
.append("&response_type=code&scope=").append(scope.toString())
.append("&state=")
.append(userState)
.append("#wechat_redirect");
return stringBuilder.toString();
}
/**
* 用户同意授权后在回调url中会得到code,调用此方法用code换token以及openid,所以如果仅仅是授权openid,到这步就结束了
*
* @param code 授权后得到的code
* @return token对象
*/
public OauthGetTokenResponse getToken(String code) {
BeanUtil.requireNonNull(code, "code is null");
OauthGetTokenResponse response = null;
String url = BASE_API_URL + "sns/oauth2/access_token?appid=" + this.config.getAppid() + "&secret=" + this.config.getSecret() + "&code=" + code + "&grant_type=authorization_code";
BaseResponse r = executeGet(url);
String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
response = JSONUtil.toBean(resultJson, OauthGetTokenResponse.class);
return response;
}
/**
* 刷新token
*
* @param refreshToken token对象中会包含refreshToken字段,通过这个字段再次刷新token
* @return 全新的token对象
*/
public OauthGetTokenResponse refreshToken(String refreshToken) {
BeanUtil.requireNonNull(refreshToken, "refreshToken is null");
OauthGetTokenResponse response = null;
String url = BASE_API_URL + "sns/oauth2/refresh_token?appid=" + this.config.getAppid() + "&grant_type=refresh_token&refresh_token=" + refreshToken;
BaseResponse r = executeGet(url);
String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
response = JSONUtil.toBean(resultJson, OauthGetTokenResponse.class);
return response;
}
/**
* 获取用户详细信息
*
* @param token token
* @param openid 用户openid
* @return 用户信息对象
*/
public GetUserInfoResponse getUserInfo(String token, String openid) {
BeanUtil.requireNonNull(token, "token is null");
BeanUtil.requireNonNull(openid, "openid is null");
GetUserInfoResponse response = null;
String url = BASE_API_URL + "sns/userinfo?access_token=" + token + "&openid=" + openid + "&lang=zh_CN";
BaseResponse r = executeGet(url);
String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
response = JSONUtil.toBean(resultJson, GetUserInfoResponse.class);
return response;
}
/**
* 校验token是否合法有效
*
* @param token token
* @param openid 用户openid
* @return 是否合法有效
*/
public boolean validToken(String token, String openid) {
BeanUtil.requireNonNull(token, "token is null");
BeanUtil.requireNonNull(openid, "openid is null");
String url = BASE_API_URL + "sns/auth?access_token=" + token + "&openid=" + openid;
BaseResponse r = executeGet(url);
return isSuccess(r.getErrcode());
}
}
|
java
| 17 | 0.664832 | 186 | 37.713115 | 122 |
starcoderdata
|
#include <bits/stdc++.h>
#include <algorithm>
#define Freopen(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout);
#define int long long
using namespace std;
int a[10010],n,k;
signed main()
{
scanf("%lld%lld",&n,&k);
for(int i=1;i<=k;i++)
{
int di,A;
scanf("%lld\n",&di);
for(int j=1;j<=di;j++)
scanf("%lld\n",&A),a[A]++;
}
int ans=0;
for(int i=1;i<=n;i++)
if(!a[i])ans++;
printf("%lld\n",ans);
return 0;
}
|
c++
| 11 | 0.56713 | 75 | 18.681818 | 22 |
codenet
|
void FwCommonPlantSmbiosAndDmiHdrs(PPDMDEVINS pDevIns, uint8_t *pHdr, uint16_t cbDmiTables, uint16_t cNumDmiTables)
{
RT_NOREF(pDevIns);
struct
{
struct SMBIOSHDR smbios;
struct DMIMAINHDR dmi;
}
aBiosHeaders =
{
// The SMBIOS header
{
{ 0x5f, 0x53, 0x4d, 0x5f}, // "_SM_" signature
0x00, // checksum
0x1f, // EPS length, defined by standard
VBOX_SMBIOS_MAJOR_VER, // SMBIOS major version
VBOX_SMBIOS_MINOR_VER, // SMBIOS minor version
VBOX_SMBIOS_MAXSS, // Maximum structure size
0x00, // Entry point revision
{ 0x00, 0x00, 0x00, 0x00, 0x00 } // padding
},
// The DMI header
{
{ 0x5f, 0x44, 0x4d, 0x49, 0x5f }, // "_DMI_" signature
0x00, // checksum
0, // DMI tables length
VBOX_DMI_TABLE_BASE, // DMI tables base
0, // DMI tables entries
VBOX_DMI_TABLE_VER, // DMI version
}
};
aBiosHeaders.dmi.u16TablesLength = cbDmiTables;
aBiosHeaders.dmi.u16TableEntries = cNumDmiTables;
aBiosHeaders.smbios.u8Checksum = fwCommonChecksum((uint8_t*)&aBiosHeaders.smbios, sizeof(aBiosHeaders.smbios));
aBiosHeaders.dmi.u8Checksum = fwCommonChecksum((uint8_t*)&aBiosHeaders.dmi, sizeof(aBiosHeaders.dmi));
memcpy(pHdr, &aBiosHeaders, sizeof(aBiosHeaders));
}
|
c++
| 10 | 0.499707 | 117 | 41.65 | 40 |
inline
|
//
// NSNumber+SafeKit.h
// JMBFramework
//
// Created by zhangyu on 14-6-12.
// Copyright (c) 2014年 jion-cheer. All rights reserved.
//
#import
@interface NSNumber (SafeKit)
@end
|
c
| 11 | 0.73064 | 83 | 20.214286 | 14 |
starcoderdata
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Fan.Web.TagHelpers
{
///
/// Base tag helper for plugins and widgets.
///
public class AreaTagHelper : TagHelper
{
///
/// Helper used to invoke ViewComponent.
///
///
/// This injected helper is "neutral", not specific for our view, so we have to "contextualize" it
/// for the current view ViewContext before using.
/// https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2#perform-synchronous-work
/// https://github.com/aspnet/Mvc/issues/5504#issuecomment-258671545
///
protected readonly IViewComponentHelper viewComponentHelper;
public AreaTagHelper(IViewComponentHelper viewComponentHelper)
{
this.viewComponentHelper = viewComponentHelper;
}
///
/// Initializes the ViewContext of the executing page.
///
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
}
}
|
c#
| 11 | 0.656056 | 127 | 34.777778 | 36 |
starcoderdata
|
<?php
/*
* This file is part of the Behat Testwork.
* (c)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Testwork\Call;
use Behat\Testwork\Call\Exception\CallHandlingException;
use Behat\Testwork\Call\Exception\FatalThrowableError;
use Behat\Testwork\Call\Filter\CallFilter;
use Behat\Testwork\Call\Filter\ResultFilter;
use Behat\Testwork\Call\Handler\CallHandler;
use Behat\Testwork\Call\Handler\ExceptionHandler;
use Exception;
use Throwable;
/**
* Makes calls and handles results using registered handlers.
*
* @author
*/
final class CallCenter
{
/**
* @var CallFilter[]
*/
private $callFilters = array();
/**
* @var CallHandler[]
*/
private $callHandlers = array();
/**
* @var ResultFilter[]
*/
private $resultFilters = array();
/**
* @var ExceptionHandler[]
*/
private $exceptionHandlers = array();
/**
* Registers call filter.
*
* @param CallFilter $filter
*/
public function registerCallFilter(CallFilter $filter)
{
$this->callFilters[] = $filter;
}
/**
* Registers call handler.
*
* @param CallHandler $handler
*/
public function registerCallHandler(CallHandler $handler)
{
$this->callHandlers[] = $handler;
}
/**
* Registers call result filter.
*
* @param ResultFilter $filter
*/
public function registerResultFilter(ResultFilter $filter)
{
$this->resultFilters[] = $filter;
}
/**
* Registers result exception handler.
*
* @param ExceptionHandler $handler
*/
public function registerExceptionHandler(ExceptionHandler $handler)
{
$this->exceptionHandlers[] = $handler;
}
/**
* Handles call and its result using registered filters and handlers.
*
* @param Call $call
*
* @return CallResult
*/
public function makeCall(Call $call)
{
try {
return $this->filterResult($this->handleCall($this->filterCall($call)));
} catch (Throwable $exception) {
return new CallResult($call, null, $this->handleException($exception), null);
}
}
/**
* Filters call using registered filters and returns a filtered one.
*
* @param Call $call
*
* @return Call
*/
private function filterCall(Call $call)
{
foreach ($this->callFilters as $filter) {
if (!$filter->supportsCall($call)) {
continue;
}
$call = $filter->filterCall($call);
}
return $call;
}
/**
* Handles call using registered call handlers.
*
* @param Call $call
*
* @return CallResult
*
* @throws CallHandlingException If call handlers didn't produce call result
*/
private function handleCall(Call $call)
{
foreach ($this->callHandlers as $handler) {
if (!$handler->supportsCall($call)) {
continue;
}
return $handler->handleCall($call);
}
throw new CallHandlingException(sprintf(
'None of the registered call handlers could handle a `%s` call.',
$call->getCallee()->getPath()
), $call);
}
/**
* Filters call result using registered filters and returns a filtered one.
*
* @param CallResult $result
*
* @return CallResult
*/
private function filterResult(CallResult $result)
{
foreach ($this->resultFilters as $filter) {
if (!$filter->supportsResult($result)) {
continue;
}
$result = $filter->filterResult($result);
}
return $result;
}
/**
* Handles exception using registered handlers and returns a handled one.
*
* @param Throwable $exception
*
* @return Throwable
*/
private function handleException($exception)
{
foreach ($this->exceptionHandlers as $handler) {
if (!$handler->supportsException($exception)) {
continue;
}
$exception = $handler->handleException($exception);
}
if ($exception instanceof Throwable) {
return new FatalThrowableError($exception);
}
return $exception;
}
}
|
php
| 18 | 0.582142 | 89 | 22.806283 | 191 |
starcoderdata
|
def imshow(img, mask, frame_img, count=0):
img = img.cpu()
mask = mask.detach().cpu()
# Directory to save the frames
frame = frame_img + "frame" + str(count) + ".jpg"
resize = transforms.Resize((360, 640))
mask = resize(mask)
img = resize(img)
mask = mask.squeeze(0)
img = img / 2 + 0.5
fig, axs = plt.subplots(2, sharex=True, sharey=True)
axs[0].axis('off')
axs[1].axis('off')
axs[0].imshow(img[0].permute(1, 2, 0), cmap='gray')
axs[1].imshow(mask[0], cmap='hot', alpha=0.9, interpolation='nearest')
plt.savefig(frame, bbox_inches='tight', pad_inches=0)
# plt.show()
|
python
| 9 | 0.59588 | 74 | 36.176471 | 17 |
inline
|
<?php
namespace Aldrumo\Core\Models;
use Aldrumo\Blocks\Concerns\HasBlocks;
use Illuminate\Database\Eloquent\Model;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Page extends Model
{
use HasSlug, HasBlocks;
protected $fillable = [
'title',
'slug',
'template',
'is_active',
];
protected $casts = [
'is_active' => 'boolean',
];
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
$slugOptions = SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug')
->slugsShouldBeNoLongerThan(250);
if ($this->slug === '/') {
$slugOptions = $slugOptions->doNotGenerateSlugsOnUpdate();
}
return $slugOptions;
}
public function delete(): bool
{
$this->blocks()->delete();
return parent::delete();
}
}
|
php
| 13 | 0.573333 | 70 | 19.3125 | 48 |
starcoderdata
|
//
// Created by davis on 2021/4/21.
//
#ifndef OPENBHOS_PER_CPU_H
#define OPENBHOS_PER_CPU_H
#include "config.h"
#define DEFINE_PER_CPU(type, name) type name[PLATFORM_CPUS]
#ifdef CONFIG_PREEMPT
// PREEMPT
#define get_cpu_var(name) \
({ \
preempt_disable(); \
&name[get_cpu_id_raw()]; \
})
#define put_cpu_var(name) preempt_enable()
#else
//NO PREEMPT
#define get_cpu_var(name) (&name[r_tp()])
#define put_cpu_var(name)
#endif
#define get_cpu_var_no_preempt(name) (&name[get_cpu_id_raw()])
#define put_cpu_var_no_preempt(name)
#endif //OPENBHOS_PER_CPU_H
|
c
| 6 | 0.619355 | 62 | 18.375 | 32 |
starcoderdata
|
bool BaseScene::transitionIn( float delay , float transitionTime )
{
if ( bTransitionIn == true )
return false ;
activate() ;
bTransitionIn = true ;
bTransitionOut = false ;
//Tweenzor is in seconds, ofxSimpleTimer is in milliseconds...
sceneTransitionTimer.setup( (delay + transitionTime) * 1000.0f ) ;
sceneTransitionTimer.start( false , true ) ;
ofLogNotice() << " BaseScene :: " << name << " transition IN ! " << endl ;
//tweenArgs = 0.0f ;
/*
TODO : how to get BaseScene to trigger it's own tween with compelte listener
baseTweenArgs = 0.0f ;
Tweenzor::add( &baseTweenArgs , 0.0f , 1.0f , delay , transitionTime ) ;
Tweenzor::addCompleteListener( Tweenzor::getTween( &baseTweenArgs ) , this , &BaseScene::transitionInComplete ) ;
*/
return true ;
}
|
c++
| 10 | 0.638955 | 117 | 37.318182 | 22 |
inline
|
import { Observable, Subject, empty, of, merge } from "rxjs";
import {
mergeMap,
first,
timeoutWith,
delay,
takeUntil,
map,
groupBy,
filter,
pairwise
} from "rxjs/operators";
export default ({
triggerPressEventBefore = 200,
triggerLongPressEventAfter = 700
}) => {
return touches => {
let touchStart = new Subject().pipe(
map(e => ({ id: e.identifier, type: "start", event: e }))
);
let touchMove = new Subject().pipe(
map(e => ({ id: e.identifier, type: "move", event: e }))
);
let touchEnd = new Subject().pipe(
map(e => ({ id: e.identifier, type: "end", event: e }))
);
let touchPress = touchStart.pipe(
mergeMap(e =>
touchEnd.pipe(
first(x => x.id === e.id),
timeoutWith(triggerPressEventBefore, empty())
)
),
map(e => ({ ...e, type: "press" }))
);
let longTouch = touchStart.pipe(
mergeMap(e =>
of(e).pipe(
delay(triggerLongPressEventAfter),
takeUntil(
merge(touchMove, touchEnd).pipe(
first(x => x.id === e.id)
)
)
)
),
map(e => ({ ...e, type: "long-press" }))
);
let touchMoveDelta = merge(touchStart, touchMove, touchEnd).pipe(
groupBy(e => e.id),
mergeMap(group =>
group.pipe(
pairwise(),
map(([e1, e2]) => {
if (e1.type !== "end" && e2.type === "move") {
return {
id: group.key,
type: "move",
event: e2.event,
delta: {
locationX: e2.event.locationX - e1.event.locationX,
locationY: e2.event.locationY - e1.event.locationY,
pageX: e2.event.pageX - e1.event.pageX,
pageY: e2.event.pageY - e1.event.pageY,
timestamp: e2.event.timestamp - e1.event.timestamp
}
};
}
}),
filter(x => x)
)
)
);
let subscriptions = [
touchStart,
touchEnd,
touchPress,
longTouch,
touchMoveDelta
].map(x => x.subscribe(y => touches.push(y)));
return {
process(type, event) {
switch (type) {
case "start":
touchStart.next(event);
break;
case "move":
touchMove.next(event);
break;
case "end":
touchEnd.next(event);
break;
}
},
end() {
subscriptions.forEach(x => x.unsubscribe());
touchStart.unsubscribe();
touchMove.unsubscribe();
touchEnd.unsubscribe();
touchPress.unsubscribe();
longTouch.unsubscribe();
}
};
};
};
|
javascript
| 28 | 0.559983 | 67 | 20.508929 | 112 |
starcoderdata
|
#if UNITY_ANDROID
#endif
using UnityEngine;
using System.Collections;
namespace com.google.game
{
public class IGoogleServiceListenerProxy : AndroidJavaProxy {
private IGoogleServiceListener listener;
internal IGoogleServiceListenerProxy(IGoogleServiceListener listener)
: base("com.google.service.IGoogleServiceListener")
{
this.listener = listener;
}
void onServiceEvent(string eventName,string eventData){
// Debug.Log("c# gamelisterproxy "+eventGroup+" "+eventName+" "+eventData);
if(listener!=null)
listener.onServiceEvent(eventName,eventData);
}
}
}
|
c#
| 12 | 0.702492 | 91 | 28.181818 | 22 |
starcoderdata
|
using System;
using System.Collections.Generic;
using DarkRoom.AI;
using DarkRoom.Core;
using DarkRoom.Game;
using DarkRoom.Utility;
using UnityEngine;
namespace Sword
{
[RequireComponent(typeof(HeroEntity))]
public class HeroController : ActorController
{
private HeroEntity m_entity => m_pawn as HeroEntity;
protected override void Start()
{
base.Start();
m_entity.Mover.MaxSpeed = 5f;
}
protected override void SetupInputComponent()
{
base.SetupInputComponent();
CMouseInput.Instance.AddClickListener(OnClickMap);
}
protected override void Update()
{
base.Update();
}
private void OnClickMap(CEvent evt)
{
if (!gameState.InHeroRound)
{
Debug.Log(" Not In Hero Round");
return;
}
if (m_entity.IsFollowingPath)
{
Debug.Log(" Hero IsFollowingPath");
return;
}
CMouseEvent e = evt as CMouseEvent;
var tile = CMapUtil.GetTileByPos(e.WorldPosition);
if (!TMap.Instance.Walkable(tile.x, tile.y))
{
Debug.Log(" Click UnWalkable Tile");
return;
}
var pos = m_entity.TilePosition;
var dist = tile.ManhattanMagnitude(pos);
if (dist > m_entity.AttributeSet.MoveRange)
{
Debug.Log(" Click Tile Out Of Range");
return;
}
var target = CMapUtil.GetTileByPos(e.WorldPosition);
var waypoints = CTileNavigationSystem.Instance.GetWayPointBetween(pos, target);
if (dist > waypoints.Count)
{
Debug.Log(" Click Tile Out Of Range");
return;
}
m_entity.OnClickMap();
m_entity.ShowMoveRange(false);
MoveToLocation(waypoints, result => m_entity.ShowMoveRange(true));
}
}
}
|
c#
| 16 | 0.693699 | 82 | 21.552632 | 76 |
starcoderdata
|
/**
*
*/
package com.hpe.calEStore.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* @author sangaras
*
*/
public class ProductDM {
/**
*
*/
public ProductDM() {
// TODO Auto-generated constructor stub
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
public float getMsrpPerUnit() {
return msrpPerUnit;
}
public void setMsrpPerUnit(float msrpPerUnit) {
this.msrpPerUnit = msrpPerUnit;
}
public Float getDiscPercent() {
return discPercent;
}
public void setDiscPercent(Float discPercent) {
this.discPercent = discPercent;
}
public float getPricePerUnit() {
return pricePerUnit;
}
public void setPricePerUnit(float pricePerUnit) {
this.pricePerUnit = pricePerUnit;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
public String getIsPublishedInd() {
return isPublishedInd;
}
public void setIsPublishedInd(String isPublishedInd) {
this.isPublishedInd = isPublishedInd;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public ProductDM[] getSelectedUserBox() {
return selectedUserBox;
}
@JsonIgnore
public void setSelectedUserBox(ProductDM[] selectedUserBox) {
this.selectedUserBox = selectedUserBox;
}
public String getSelectPreference() {
return selectPreference;
}
@JsonIgnore
public void setSelectPreference(String selectPreference) {
this.selectPreference = selectPreference;
}
@JsonIgnore
public List getUserCheckBoxList() {
return userCheckBoxList;
}
public void setUserCheckBoxList(List userCheckBoxList) {
this.userCheckBoxList = userCheckBoxList;
}
private Integer productId;
private String category;
private String brand;
private String productName;
private String productDesc;
private String productType;
private String imgPath;
private float msrpPerUnit;
private Float discPercent;
private float pricePerUnit;
private Integer rating;
private String isPublishedInd;
private Date publishedDate;
ProductDM[] selectedUserBox;
private String selectPreference = "";
List userCheckBoxList = new ArrayList
}
|
java
| 8 | 0.744602 | 68 | 17.420455 | 176 |
starcoderdata
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
using System.IO;
using System.Net.Sockets;
using System;
namespace Statoscope
{
class SocketLogBinaryDataStream : BinaryLogDataStream
{
BinaryWriter m_binaryWriter;
protected override void Dispose(bool disposing)
{
if (m_binaryWriter != null)
{
m_binaryWriter.Close();
m_binaryWriter = null;
}
base.Dispose(disposing);
}
public bool FileWriterNeedsClosing { get { return m_binaryWriter != null; } }
public SocketLogBinaryDataStream(NetworkStream netStream, string logWriteFilename)
{
m_binaryReader = new BinaryReader(netStream);
m_binaryWriter = null;
if (logWriteFilename != "")
{
m_binaryWriter = new BinaryWriter(File.Open(logWriteFilename, FileMode.Create, FileAccess.Write, FileShare.Read));
}
}
public void CloseNetStream()
{
if (m_binaryReader.BaseStream != null)
{
m_binaryReader.BaseStream.Close();
}
}
public override byte[] ReadBytes(int nBytes)
{
byte[] bytes = base.ReadBytes(nBytes);
if (m_binaryWriter != null)
{
m_binaryWriter.Write(bytes);
}
return bytes;
}
public override byte ReadByte()
{
byte b = m_binaryReader.ReadByte();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(b);
}
return b;
}
public override bool ReadBool()
{
bool b = m_binaryReader.ReadBoolean();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(b);
}
return b;
}
public override short ReadInt16()
{
Int16 i = m_binaryReader.ReadInt16();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(i);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian2((ushort*)&i);
}
}
return i;
}
public override ushort ReadUInt16()
{
UInt16 i = m_binaryReader.ReadUInt16();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(i);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian2(&i);
}
}
return i;
}
public override int ReadInt32()
{
int i = m_binaryReader.ReadInt32();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(i);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian4((uint*)&i);
}
}
return i;
}
public override uint ReadUInt32()
{
uint i = m_binaryReader.ReadUInt32();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(i);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian4(&i);
}
}
return i;
}
public override long ReadInt64()
{
long l = m_binaryReader.ReadInt64();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(l);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian8((ulong*)&l);
}
}
return l;
}
public override ulong ReadUInt64()
{
ulong l = m_binaryReader.ReadUInt64();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(l);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian8(&l);
}
}
return l;
}
public override float ReadFloat()
{
UInt32 p = m_binaryReader.ReadUInt32();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(p);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian4((uint*)&p);
}
return *(float*)&p;
}
}
public override double ReadDouble()
{
UInt64 p = m_binaryReader.ReadUInt64();
if (m_binaryWriter != null)
{
m_binaryWriter.Write(p);
}
unsafe
{
if (m_bSwapEndian)
{
EndianBitConverter.SwapEndian8(&p);
}
return *(double*)&p;
}
}
public override bool IsEndOfStream
{
get
{
// if the socket closes, the Read operation will thrown an exception
return false;
}
}
public override void FlushWriteStream()
{
if (m_binaryWriter != null)
{
m_binaryWriter.Flush();
}
}
public override void CloseWriteStream()
{
if (m_binaryWriter != null)
{
m_binaryWriter.Close();
}
}
}
}
|
c#
| 18 | 0.624758 | 118 | 15.952555 | 274 |
starcoderdata
|
public static List<Category> sortCategoryListByFieldReference(List<Category> categories, Deque<Category> accumulator, String leafId) {
Objects.requireNonNull(categories);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(leafId);
// find next sequence element
Category nextCategory = categories.stream()
.filter(category -> Objects.equals(leafId, category.getId()))
.findFirst()
.orElseThrow(CategoryNotFoundException::new);
// add element to path
accumulator.addFirst(nextCategory);
String parentId = nextCategory.getParentId();
if (parentId == null) {
return List.of(accumulator.toArray(new Category[]{}));
}
sortCategoryListByFieldReference(categories, accumulator, parentId);
return List.of(accumulator.toArray(new Category[]{}));
}
|
java
| 14 | 0.655702 | 134 | 37.041667 | 24 |
inline
|
<?php
//example of sending an sms using an API key / secret
require_once '../vendor/autoload.php';
//create client with api key and secret
$client = new Nexmo\Client(new Nexmo\Client\Credentials\Basic(API_KEY, API_SECRET));
//send message using simple api params
$message = $client->message()->send([
'to' => NEXMO_TO,
'from' => NEXMO_FROM,
'text' => 'Test message from the Nexmo PHP Client'
]);
//array access provides response data
echo "Sent message to " . $message['to'] . ". Balance is now " . $message['remaining-balance'] . PHP_EOL;
sleep(1);
//send message using object support
$text = new \Nexmo\Message\Text(NEXMO_TO, NEXMO_FROM, 'Test message using PHP client library');
$text->setClientRef('test-message')
->setClass(\Nexmo\Message\Text::CLASS_FLASH);
$client->message()->send($text);
//method access
echo "Sent message to " . $text->getTo() . ". Balance is now " . $text->getRemainingBalance() . PHP_EOL;
sleep(1);
//sending a message over 160 characters
$longwinded = <<<EOF
But soft! What light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,
That thou, her maid, art far more fair than she.
EOF;
$text = new \Nexmo\Message\Text(NEXMO_TO, NEXMO_FROM, $longwinded);
$client->message()->send($text);
echo "Sent message to " . $text->getTo() . ". Balance is now " . $text->getRemainingBalance() . PHP_EOL;
echo "Message was split into " . count($text) . " messages, those message ids are: " . PHP_EOL;
for($i = 0; $i < count($text); $i++){
echo $text[$i]['message-id'] . PHP_EOL;
}
echo "The account balance after each message was: " . PHP_EOL;
for($i = 0; $i < count($text); $i++){
echo $text->getRemainingBalance($i) . PHP_EOL;
}
//easier iteration, can use methods or array access
foreach($text as $index => $data){
echo "Balance was " . $text->getRemainingBalance($index) . " after message " . $data['message-id'] . " was sent." . PHP_EOL;
}
//an invalid request
try{
$text = new \Nexmo\Message\Text('not valid', NEXMO_FROM, $longwinded);
$client->message()->send($text);
} catch (Nexmo\Client\Exception\Request $e) {
//can still get the API response
$text = $e->getEntity();
$request = $text->getRequest(); //PSR-7 Request Object
$response = $text->getResponse(); //PSR-7 Response Object
$data = $text->getResponseData(); //parsed response object
$code = $e->getCode(); //nexmo error code
error_log($e->getMessage()); //nexmo error message
}
|
php
| 13 | 0.662886 | 128 | 34.513889 | 72 |
starcoderdata
|
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelController : MonoBehaviour
{
public CinemachineVirtualCamera vcam;
public ShipPart mainShipPrefab;
public Spawner meteorSpawnerPrefab;
public Spawner shipPartSpawnerPrefab;
public Goal goalPrefab;
public GameUI gameUI;
public GameObject pauseMenu;
public GameObject gameOverMenu;
private Transform goalTransform;
private MainShip mainShip;
private GameObject mainShipInstance;
private GameObject meteorSpawnerInstance;
private GameObject shipPartSpawnerInstance;
public TextMeshProUGUI finalScore;
private float baseGoalDistance = 30f;
private float goalDistanceIncrement = 20f;
private int baseGoalScore = 200;
private int goalScoreIncrement = 150;
private int level = 1;
[SerializeField]
AudioClip BGM;
private void Start()
{
MusicManager instance = MusicManager.getInstance();
if (instance != null)
{
instance.updateMusic(BGM);
}
// Spawn main ship
mainShipInstance = Instantiate(mainShipPrefab.gameObject);
mainShip = mainShipInstance.GetComponent
vcam.Follow = mainShipInstance.transform;
// Start spawners
meteorSpawnerInstance = Instantiate(meteorSpawnerPrefab.gameObject);
meteorSpawnerInstance.transform.SetParent(mainShipInstance.transform);
shipPartSpawnerInstance = Instantiate(shipPartSpawnerPrefab.gameObject);
shipPartSpawnerInstance.transform.SetParent(mainShipInstance.transform);
// Spawn stars / Background?
// instantiate a victory location
Goal goal = Goal.Create(mainShipInstance.transform.position, baseGoalDistance + (goalDistanceIncrement * level), baseGoalScore);
goal.OnGoalReached += LevelController_GoalReached;
// Setup UI
gameUI.SetGoal(goal);
gameUI.SetMainShip(mainShip);
// Register for events
mainShipInstance.GetComponent += LevelController_OnDied;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Escape))
{
Pause();
}
}
private void LevelController_GoalReached(object sender, System.EventArgs e)
{
LevelWon();
}
private void LevelController_OnDied(object sender, System.EventArgs e)
{
LevelLost();
}
public void LevelLost()
{
Time.timeScale = 0;
int totalWeightDelivered = mainShip.GetTotalWeightDelivered();
string scoreMsg = totalWeightDelivered > 0 ? $"{totalWeightDelivered} Kg Delivered" : "None...";
//gameOverMenu.transform.Find("scoreText").GetComponent
finalScore.SetText(scoreMsg);
gameOverMenu.SetActive(true);
}
public void LevelWon()
{
// Destroy all attached objects
mainShip.Jettison();
// Spawn next planet
Goal goal = Goal.Create(mainShipInstance.transform.position, baseGoalDistance + (goalDistanceIncrement * level), baseGoalScore + (goalScoreIncrement * level));
goal.OnGoalReached += LevelController_GoalReached;
gameUI.SetGoal(goal);
// Increase difficulty
level++;
meteorSpawnerPrefab.minSpawnDelay -= 0.5f;
if (meteorSpawnerPrefab.minSpawnDelay <= 0.5f)
{
meteorSpawnerPrefab.minSpawnDelay = 0.5f;
}
meteorSpawnerPrefab.maxSpawnDelay -= 1;
if (meteorSpawnerPrefab.minSpawnDelay <= 1f)
{
meteorSpawnerPrefab.minSpawnDelay = 1f;
}
// TODO: Increase spawn rates on spawners?
}
public void RestartGame()
{
Time.timeScale = 1;
SceneManager.LoadScene(0);
}
public void Pause()
{
Time.timeScale = 0;
pauseMenu.SetActive(true);
}
public void Resume()
{
Time.timeScale = 1;
pauseMenu.SetActive(false);
}
}
|
c#
| 15 | 0.664743 | 167 | 25.653846 | 156 |
starcoderdata
|
<?php
namespace spec\Omniphx\Forrest\Repositories;
use Omniphx\Forrest\Repositories\InstanceURLRepository;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Omniphx\Forrest\Interfaces\RepositoryInterface;
class InstanceURLRepositorySpec extends ObjectBehavior
{
protected $settings = [];
function it_is_initializable()
{
$this->shouldHaveType(InstanceURLRepository::class);
}
public function let(
RepositoryInterface $mockedTokenRepo)
{
$this->beConstructedWith($mockedTokenRepo, $this->settings);
$mockedTokenRepo->get()->willReturn(['instance_url' => 'tokenInstanceURL']);
}
public function it_should_return_when_put(RepositoryInterface $mockedTokenRepo)
{
$mockedTokenRepo->get()->shouldBeCalled()->willReturn([]);
$mockedTokenRepo->put(['instance_url'=>'this'])->shouldBeCalled();
$this->put('this')->shouldReturn(null);
}
public function it_should_return_instance_url_when_setting_is_set(RepositoryInterface $mockedTokenRepo)
{
$this->settings['instanceURL'] = 'settingInstanceURL';
$this->beConstructedWith($mockedTokenRepo, $this->settings);
$this->get()->shouldReturn('settingInstanceURL');
}
public function it_should_return_instance_url_when_setting_is_not_set()
{
$this->get()->shouldReturn('tokenInstanceURL');
}
}
|
php
| 13 | 0.695865 | 107 | 28.729167 | 48 |
starcoderdata
|
package io.innofang.mvvmdemo.sign_in;
import android.support.v4.app.Fragment;
import io.innofang.mvvmdemo.R;
import io.innofang.mvvmdemo.SingleFragmentActivity;
public class SignInActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return SignInFragment.newInstance();
}
@Override
protected int getLayoutResId() {
return R.layout.activity_sign_in;
}
@Override
protected int getFragmentContainerId() {
return R.id.fragment_container;
}
}
|
java
| 6 | 0.724258 | 60 | 21.92 | 25 |
starcoderdata
|
// ? Given a fixed array and multiple queries of following types on the array, how to efficiently perform these queries.
#include
using namespace std;
int getSum(int *arr, int l, int r)
{
if (l != 0)
return arr[r] - arr[l - 1];
else
return arr[r];
}
int main()
{
// Prefix Sum
int arr[7] = {2, 8, 3, 9, 6, 5, 4};
int size = 7;
int *a = new int[size]{0};
int sum = arr[0];
a[0] = arr[0];
for (int i = 1; i < size; i++)
{
sum += arr[i];
a[i] = sum;
}
cout << getSum(a, 3, 5) << endl;
delete[] a;
return 0;
}
|
c++
| 9 | 0.506557 | 120 | 17.515152 | 33 |
starcoderdata
|
# coding=utf-8
from lxml import etree
from tornado.escape import json_encode
def _escape(value):
return json_encode(value)[1: -1] if value else ''
def escape_json(_, value):
if isinstance(value, list):
if not value:
return ''
value = value[0].text if etree.iselement(value[0]) else value[0]
return _escape(value)
def etree_enrich_hh_namespace():
ns = etree.FunctionNamespace('http://schema.reintegration.hh.ru/types')
ns.prefix = 'hh'
ns['escape-json'] = escape_json
|
python
| 11 | 0.646503 | 75 | 20.16 | 25 |
starcoderdata
|
const std::string QueryEditorModule::GetCurrentArgAsString()
{
auto query = GetCurrentSelectionQuery();
if (query != nullptr)
{
rapidjson::Document doc;
if (query->structureType == QueryType::WAQLQUERY)
{
RapidJsonUtils::ToRapidJson(query->arg["waql"], doc, doc.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
std::string rawArg = buffer.GetString();
//remove " in the front and back
rawArg.erase(0, 1);
rawArg.erase(rawArg.size() - 1);
std::string processedArg = "";
for (int i = 0; i < rawArg.size(); i++)
{
if (rawArg.at(i) == '\\')
{
int nextSlot = i + 1;
if (rawArg.at(nextSlot) == '\\')
{
processedArg += "\\";
i++;
}
}
else
{
processedArg += rawArg.at(i);
}
}
return processedArg;
}
else if (query->structureType == QueryType::WAAPIQUERY)
{
RapidJsonUtils::ToRapidJson(query->arg, doc, doc.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
return buffer.GetString();
}
}
return "";
}
|
c++
| 16 | 0.463369 | 85 | 30.333333 | 51 |
inline
|
#!/usr/bin/env python3
import utils
utils.check_version((3,7))
utils.clear()
print('Hello, my name is
print('my favourite game is Mario')
print ('i am conncerned that it will be too fast paced for me')
print ('i am excited to make games')
stack_id = '12004299'
print ('my stackopverflow user number = ',stack_id)
print ('my github profile URL is https://github.com/sabdllah')
|
python
| 5 | 0.718346 | 63 | 26.714286 | 14 |
starcoderdata
|
def test_nested_type_hints_4(self):
"""Problem here: return type is actually float"""
@pedantic
def calc(n: List[List[float]]) -> int:
return n[0][0]
with self.assertRaises(expected_exception=PedanticTypeCheckException):
calc(n=[[42.0]])
|
python
| 14 | 0.595238 | 78 | 35.875 | 8 |
inline
|
def index():
with open('index.html') as idex_page:
return idex_page.read()
def blog():
with open('blog.html') as blog_page:
return blog_page.read()
|
python
| 10 | 0.61658 | 41 | 20.444444 | 9 |
starcoderdata
|
void CAppHandler::SetAppListL(struct TAppObject** aAppList, TInt aLength)
{
// Size of the array
iNumAppObjs = aLength;
if(iAppList) {
delete[] iAppList;
iAppList = NULL;
}
// Allocate necessary space
iAppList = new(ELeave) TAppObject*[iNumAppObjs];
// Build a list of installed applications.
RApaLsSession apaSession;
User::LeaveIfError(apaSession.Connect());
CleanupClosePushL(apaSession);
TInt ret = apaSession.GetAllApps();
if(ret != KErrNone) {
GenerateEventL(EFailedToInitList);
return;
}
TApaAppInfo appInfo;
TInt appIndex = 0;
while (apaSession.GetNextApp(appInfo)==KErrNone) {
for(TInt i = 0; i < iNumAppObjs; ++i) {
if(appInfo.iFullName.CompareF(*aAppList[i]->appName) == 0) {
// We found a matching app, add to our list
TAppObject* appObj = new(ELeave) TAppObject();
appObj->appName = appInfo.iFullName.AllocL();
appObj->appUid = appInfo.iUid.iUid;
appObj->appAction = aAppList[i]->appAction;
appObj->pendingAction = ENonePending;
iAppList[appIndex] = appObj;
appIndex++;
}
}
}
iNumAppObjs = appIndex;
CleanupStack::PopAndDestroy(&apaSession);
}
|
c++
| 16 | 0.607498 | 73 | 31.564103 | 39 |
inline
|
using System;
using System.Collections.Generic;
namespace VzaarApi
{
public class LinkUpload
{
internal Record record;
public LinkUpload ()
{
record = new Record ("link_uploads");
}
public LinkUpload (Client client)
{
record = new Record ("link_uploads", client);
}
internal Video LinkCreate(Dictionary tokens) {
if (tokens.ContainsKey ("uploader") == false) {
tokens.Add ("uploader", Client.UPLOADER + Client.VERSION);
}
record.Create (tokens);
record.RecordEndpoint = "videos";
var video = new Video (record);
return video;
}
//create from url
public static Video Create(string url) {
var link = new LinkUpload ();
var tokens = new Dictionary<string, object> ();
tokens.Add ("url", url);
var video = link.LinkCreate (tokens);
return video;
}
public static Video Create(string url, Client client) {
var link = new LinkUpload (client);
var tokens = new Dictionary<string, object> ();
tokens.Add ("url", url);
var video = link.LinkCreate (tokens);
return video;
}
//create from url with additional parameters
public static Video Create(Dictionary tokens) {
var link = new LinkUpload ();
var video = link.LinkCreate (tokens);
return video;
}
public static Video Create(Dictionary tokens, Client client){
var link = new LinkUpload (client);
var video = link.LinkCreate (tokens);
return video;
}
}
}
|
c#
| 15 | 0.669074 | 78 | 17.802469 | 81 |
starcoderdata
|
// Generated by CoffeeScript 1.10.0
(function() {
var com, pack;
com = require('commander');
pack = require('../package.json');
com.version(pack.version).parse(process.argv);
}).call(this);
|
javascript
| 13 | 0.648515 | 48 | 17.363636 | 11 |
starcoderdata
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import econml.orf as orf
from .utilities import deprecated
@deprecated("The econml.ortho_forest.DMLOrthoForest class has been moved to econml.orf.DMLOrthoForest; "
"an upcoming release will remove support for the old name")
class DMLOrthoForest(orf.DMLOrthoForest):
pass
@deprecated("The econml.ortho_forest.DiscreteTreatmentOrthoForest class has been "
"moved to econml.orf.DROrthoForest; "
"an upcoming release will remove support for the old name")
class DROrthoForest(orf.DROrthoForest):
pass
@deprecated("The econml.ortho_forest.ContinuousTreatmentOrthoForest class has been "
"renamed to econml.orf.DMLOrthoForest; "
"an upcoming release will remove support for the old name")
class ContinuousTreatmentOrthoForest(orf.DMLOrthoForest):
pass
@deprecated("The econml.ortho_forest.DiscreteTreatmentOrthoForest class has been "
"renamed to econml.orf.DROrthoForest; "
"an upcoming release will remove support for the old name")
class DiscreteTreatmentOrthoForest(orf.DROrthoForest):
pass
|
python
| 7 | 0.724673 | 104 | 36.25 | 32 |
starcoderdata
|
from __future__ import annotations
import httpx
from intent_deployer import config
from intent_deployer.hosts import Hosts
from intent_deployer.switches import Switches
class Links:
switch_links: list[tuple[str, str]]
host_links: list[tuple[str, str]]
def __init__(self, links, hosts):
self.switch_links = [
(
Switches.name_from_id(l["src"]["device"]),
Switches.name_from_id(l["dst"]["device"]),
)
for l in links["links"]
]
self.host_links = [
(Hosts.name_from_mac(h["mac"]), Switches.name_from_id(s["elementId"]))
for h in hosts["hosts"]
for s in h["locations"]
]
@property
def links(self) -> list[tuple[str, str]]:
return self.switch_links + self.host_links
@classmethod
async def from_api(cls) -> Links:
async with httpx.AsyncClient() as client:
resp = await client.get(
config.links_url, auth=(config.login, config.password)
)
resp.raise_for_status()
links = resp.json()
resp = await client.get(
config.hosts_url, auth=(config.login, config.password)
)
resp.raise_for_status()
hosts = resp.json()
return cls(links, hosts)
# links response example:
# {
# "links": [
# {
# "src": {
# "port": "4",
# "device": "of:000000000000000b"
# },
# "dst": {
# "port": "4",
# "device": "of:000000000000000d"
# },
# "type": "DIRECT",
# "state": "ACTIVE"
# },
# {
# "src": {
# "port": "6",
# "device": "of:000000000000000a"
# },
# "dst": {
# "port": "3",
# "device": "of:000000000000000d"
# },
# "type": "DIRECT",
# "state": "ACTIVE"
# },
# ...
# ]
# }
|
python
| 16 | 0.495748 | 82 | 23.378049 | 82 |
starcoderdata
|
'use strict';
var fs = require('fs');
var path = require('path');
module.exports = function (filename, options, callback) {
var filePath = path.resolve(filename);
if (typeof options === 'function') {
callback = options;
options = {};
} else {
options = options || {};
}
fs.readFile(filePath, function (error, contents) {
if (error) {
return callback(error);
}
var contentsArray = fileToArray(contents, options);
callback(null, contentsArray);
});
};
function fileToArray(contents, options) {
var seperator = /\r?\n/;
var results = [];
var currentLine = 0;
var lines;
var lineCount;
contents = String(contents);
if (haz(options, 'seperator')) {
seperator = options.seperator;
}
lines = contents.split(seperator);
lineCount = lines.length;
for (currentLine; currentLine < lineCount; currentLine++) {
var line = lines[currentLine].trim();
if (haz(options, 'emptyLines') && options.emptyLines === false) {
if (line.length === 0) {
continue;
}
}
if (haz(options, 'trimLines') && options.trimLines === false) {
line += lines[currentLine];
}
if (haz(options, 'withSeperator') && options.withSeperator === true) {
line += seperator;
}
results.push(line);
}
return results;
}
function haz(obj, key) {
function _haz() {
var keys = key.split('.');
while (!!keys.length) {
var _key = keys.shift();
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
obj = obj[_key];
}
return true;
}
return (obj !== null && _haz());
}
|
javascript
| 15 | 0.590354 | 74 | 19.475 | 80 |
starcoderdata
|
import "./App.css";
import React from "react";
import useElementSize from "react-element-size";
export default function App() {
const app = useElementSize();
const box = useElementSize();
return (
<div className="App" ref={app.setRef}>
<div className="Box" ref={box.setRef}>
);
}
|
javascript
| 13 | 0.626794 | 48 | 23.588235 | 17 |
starcoderdata
|
func TestStdSchnorrThresholdSigImpl(t *testing.T) {
const MAX_SIGNATORIES = 10
const NUM_TEST = 5
tRand := rand.New(rand.NewSource(543212345))
curve := new(TwistedEdwardsCurve)
curve.InitParam25519()
msg, _ := hex.DecodeString(
"d04b98f48e8f8bcc15c6ae5ac050801cd6dcfd428fb5f9e65c4e16e7807340fa")
for i := 0; i < NUM_TEST; i++ {
numKeysForTest := tRand.Intn(MAX_SIGNATORIES-2) + 2
schnorrKeyVec := mockUpSchnorrKeyVec(curve, numKeysForTest, msg)
combinedSignature, err := mockUpSchnorrMultiSign(curve, msg, schnorrKeyVec)
if nil != err {
t.Fatal(err)
}
// Make sure the combined signatures are the same as the
// signatures that would be generated by simply adding
// the private keys and private nonces.
combinedPrivkeysD := new(big.Int).SetInt64(0)
for _, priv := range schnorrKeyVec.skVec {
combinedPrivkeysD = ScalarAdd(combinedPrivkeysD, priv.GetD())
combinedPrivkeysD = combinedPrivkeysD.Mod(combinedPrivkeysD, curve.N)
}
combinedNonceD := new(big.Int).SetInt64(0)
for _, priv := range schnorrKeyVec.secNonceVec {
combinedNonceD.Add(combinedNonceD, priv.GetD())
combinedNonceD.Mod(combinedNonceD, curve.N)
}
// convert the scalar to a valid secret key for curve
combinedPrivkey, _, err := PrivKeyFromScalar(curve,
copyBytes(combinedPrivkeysD.Bytes())[:])
if err != nil {
t.Fatalf("unexpected error %s", err)
}
// convert the scalar to a valid nonce for curve
combinedNonce, _, err := PrivKeyFromScalar(curve,
copyBytes(combinedNonceD.Bytes())[:])
if err != nil {
t.Fatalf("unexpected error %s", err)
}
// sign with the combined secret key and nonce
cSigR, cSigS, err := SignFromScalar(curve, combinedPrivkey,
combinedNonce.Serialize(), msg)
sumSig := NewSignature(cSigR, cSigS)
if err != nil {
t.Fatalf("unexpected error %s", err)
}
if !bytes.Equal(sumSig.Serialize(), combinedSignature.Serialize()) {
t.Fatalf("want %s, got %s",
hex.EncodeToString(combinedSignature.Serialize()),
hex.EncodeToString(sumSig.Serialize()))
}
}
}
|
go
| 14 | 0.711988 | 77 | 31.587302 | 63 |
inline
|
package com.redhat.syseng.serverless.orchestrator.process;
import java.util.Optional;
import com.redhat.syseng.serverless.orchestrator.model.Message;
import org.jbpm.process.core.datatype.impl.type.ObjectDataType;
import org.jbpm.process.core.datatype.impl.type.StringDataType;
import org.jbpm.ruleflow.core.RuleFlowProcessFactory;
import org.kie.api.definition.process.Process;
import org.serverless.workflow.api.Workflow;
public class WorkflowProcessBuilder {
public static final String BACKUP_DATA_VAR = "backup-data";
private static final String PACKAGE_NAME = "org.kiegroup.kogito.workflow";
private static final Boolean DYNAMIC = Boolean.TRUE;
private static final String VISIBILITY = "Public";
private static final ObjectDataType WORKFLOW_DATA_TYPE = new ObjectDataType();
private static final StringDataType STRING_DATA_TYPE = new StringDataType();
private final RuleFlowProcessFactory factory;
private Long count = 0l;
private final Workflow workflow;
private WorkflowProcessBuilder(Workflow workflow) {
this.workflow = workflow;
this.factory = RuleFlowProcessFactory
.createProcess(workflow.getName())
.name(workflow.getName())
.dynamic(DYNAMIC)
.packageName(PACKAGE_NAME)
.visibility(VISIBILITY)
.version(workflow.getVersion())
.variable(Message.DATA_PARAM, WORKFLOW_DATA_TYPE)
.variable(Message.ERROR_PARAM, WORKFLOW_DATA_TYPE)
.variable(Message.CORRELATION_TOKEN_PARAM, STRING_DATA_TYPE)
.variable(Message.STATUS_PARAM, STRING_DATA_TYPE)
.variable(BACKUP_DATA_VAR, WORKFLOW_DATA_TYPE);
}
private Process getProcess() {
return this.factory.validate().getProcess();
}
public static Process build(Workflow workflow) {
return new WorkflowProcessBuilder(workflow).getProcess();
}
}
|
java
| 21 | 0.716364 | 82 | 36.745098 | 51 |
starcoderdata
|
fn unmanaged_window_types_are_not_added_to_workspaces() {
// Setting the unmanaged window IDs here sets the return of
// MockXConn.is_managed_window to false for those IDs
let mut wm = wm_with_mock_conn(vec![], vec![10]);
wm.handle_map_request(10).unwrap(); // should not be tiled
assert!(wm.clients.get(10).is_some());
assert!(wm.workspaces[0].is_empty());
wm.handle_map_request(20).unwrap(); // should be tiled
assert!(wm.clients.get(20).is_some());
assert!(wm.workspaces[0].len() == 1);
}
|
rust
| 8 | 0.608084 | 67 | 42.846154 | 13 |
inline
|
#include
#include
#include
#include
#include
#include
#include
/********************************************************************************
* *
* Function to create a annular cylinder EB. *
* *
********************************************************************************/
void incflo::make_eb_annulus()
{
// Initialise annulus parameters
int direction = 0;
Real outer_radius = 0.0002;
Real inner_radius = 0.0001;
Vector outer_centervec(3);
Vector inner_centervec(3);
// Get annulus information from inputs file. *
ParmParse pp("annulus");
pp.query("direction", direction);
pp.query("outer_radius", outer_radius);
pp.query("inner_radius", inner_radius);
pp.getarr("outer_center", outer_centervec, 0, 3);
pp.getarr("inner_center", inner_centervec, 0, 3);
Array<Real, 3> outer_center = {outer_centervec[0], outer_centervec[1], outer_centervec[2]};
Array<Real, 3> inner_center = {inner_centervec[0], inner_centervec[1], inner_centervec[2]};
// make_eb_annulus: outer and inner cylinders must have same center coordinate per direction
AMREX_ASSERT(outer_center[direction] == inner_center[direction]);
// Compute distance between cylinder centres
Real offset = 0.0;
for(int i = 0; i < 3; i++)
offset += pow(outer_center[i] - inner_center[i], 2);
offset = sqrt(offset);
// Check that the inner cylinder is fully contained in the outer one
Real smallest_gap_width = outer_radius - inner_radius - offset;
AMREX_ASSERT(smallest_gap_width >= 0.0);
// Compute standoff - measure of eccentricity
Real standoff = 100 * smallest_gap_width / (outer_radius - inner_radius);
AMREX_ASSERT((standoff >= 0) && (standoff <= 100));
// Print info about annulus
amrex::Print() << " " << std::endl;
amrex::Print() << " Direction: " << direction << std::endl;
amrex::Print() << " Outer radius: " << outer_radius << std::endl;
amrex::Print() << " Inner radius: " << inner_radius << std::endl;
amrex::Print() << " Outer center: "
<< outer_center[0] << ", " << outer_center[1] << ", " << outer_center[2] << std::endl;
amrex::Print() << " Inner center: "
<< inner_center[0] << ", " << inner_center[1] << ", " << inner_center[2] << std::endl;
amrex::Print() << " Offset: " << offset << std::endl;
amrex::Print() << " Smallest gap: " << smallest_gap_width << std::endl;
amrex::Print() << " Standoff: " << standoff << std::endl;
// Build the annulus implifict function as a union of two cylinders
EB2::CylinderIF outer_cyl(outer_radius, direction, outer_center, true);
EB2::CylinderIF inner_cyl(inner_radius, direction, inner_center, false);
auto annulus = EB2::makeUnion(outer_cyl, inner_cyl);
// Generate GeometryShop
auto gshop = EB2::makeShop(annulus);
// Build index space
int max_level_here = 0;
int max_coarsening_level = 100;
EBSupport m_eb_support_level = EBSupport::full;
EB2::Build(gshop, geom.back(), max_level_here, max_level_here + max_coarsening_level);
const EB2::IndexSpace& eb_is = EB2::IndexSpace::top();
// Make the EBFabFactory
for(int lev = 0; lev <= max_level; lev++)
{
const EB2::Level& eb_is_lev = eb_is.getLevel(geom[lev]);
eb_level = &eb_is_lev;
ebfactory[lev].reset(new EBFArrayBoxFactory(*eb_level,
geom[lev],
grids[lev],
dmap[lev],
{m_eb_basic_grow_cells,
m_eb_volume_grow_cells,
m_eb_full_grow_cells},
m_eb_support_level));
}
}
|
c++
| 13 | 0.525893 | 96 | 43.052083 | 96 |
starcoderdata
|
<?php
/**
* @author ryan
* @desc sso接口控制器
*/
namespace Controller\SSO;
use OneFox\ApiController as BaseController;
use OneFox\Request;
use OneFox\Config;
use SSO\Code;
use SSO\Session;
use SSO\Ticket;
class ApiController extends BaseController {
protected function _init() {
if (Request::method() != 'post') {
$this->json(self::CODE_FAIL, 'error');
}
}
/**
* 校验code[POST]
*/
public function check_codeAction() {
$code = $this->post('code');
$appKey = $this->post('app_key');
$appId = $this->post('app_id', 0, 'string');
if (!$code || !$appKey || !$appId) {
$this->json(self::CODE_FAIL, 'params error');
}
$apps = Config::get('sso.apps');
$appId = (string)$appId;
if (!isset($apps[$appId])) {
$this->json(self::CODE_FAIL, 'params error');
}
$appInfo = $apps[$appId];
if (strtolower($appKey) != strtolower($appInfo['app_key'])) {
$this->json(self::CODE_FAIL, 'params error');
}
$codeObj = new Code();
$res = $codeObj->checkCode($code);//返回session id
if (empty($res)) {
$this->json(self::CODE_FAIL, 'check code error');
}
//获取session
$sessObj = new Session();
$sessionData = $sessObj->getSession($res);
//生成子系统ticket
$ticketObj = new Ticket();
$ticket = $ticketObj->genSubTicket($res);
//返回数据
$data = array(
'ticket' => $ticket,
'username' => $sessionData['username']
);
$this->json(self::CODE_SUCCESS, 'ok', $data);
}
/**
* 校验ticket[POST]
*/
public function check_ticketAction() {
$ticket = $this->post('ticket');
$appId = $this->post('app_id', 0, 'string');
if (!$appId || !$ticket) {
$this->json(self::CODE_FAIL, 'params error');
}
$ticketObj = new Ticket();
$sessionId = $ticketObj->originData($ticket);
$sessObj = new Session();
//session超时或不存在
if (!$sessObj->isExists($sessionId)) {
$this->json(self::CODE_FAIL, 'check ticket error');
}
//重置session过期时间
$r = $sessObj->extendedTime($sessionId);
$this->json(self::CODE_SUCCESS, 'ok');
}
}
|
php
| 13 | 0.513629 | 69 | 24.247312 | 93 |
starcoderdata
|
package com.company.project.system.service;
import com.company.project.system.model.UserOnline;
import java.util.List;
public interface SessionService {
List list();
void forceLogout(String sessionId);
}
|
java
| 7 | 0.785714 | 51 | 16.230769 | 13 |
starcoderdata
|
from django.urls import path
from django.conf.urls import url
from django.urls import include
from rest_framework import routers
from . import views
from .viewsets import MaskDetectorViewSet
# app_name = 'api'
# router = routers.DefaultRouter()
# router.register('', MaskDetectorViewSet, basename='predict')
urlpatterns = [
# url(r'^', include(router.urls)),
path('predict/', views.MaskDetectionAPI.as_view(), name='predict'),
path('get_stats/', views.GetStats.as_view(), name='get_stats'),
path('feedback/', views.SaveFeedback.as_view(), name='feedback')
]
|
python
| 9 | 0.716753 | 71 | 27.95 | 20 |
starcoderdata
|
int UTIL_CountPlayers()
{
int num = 0;
for( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBaseEntity *pEnt = UTIL_PlayerByIndex( i );
//TODO: this can be wrong if the client has disconnected. - Solokiller
if( pEnt )
{
num = num + 1;
}
}
return num;
}
|
c++
| 10 | 0.600733 | 72 | 15.117647 | 17 |
inline
|
public void save(Context context)
{
try
{
// Make an ObjectOutputStream that writes objects to scrumSave.txt
File savefile = new File(context.getFilesDir().getPath() + "/" + "scrumSave.txt");
FileOutputStream fos = new FileOutputStream(savefile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// Write the object
oos.writeObject(this);
// Clean up
oos.flush();
oos.close();
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
|
java
| 14 | 0.51811 | 94 | 27.909091 | 22 |
inline
|
// <copyright file="IConnectionChannel.cs" company="Rnwood.SmtpServer project contributors">
// Copyright (c) Rnwood.SmtpServer project contributors. All rights reserved.
// Licensed under the BSD license. See LICENSE.md file in the project root for full license information.
//
namespace Rnwood.SmtpServer
{
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
///
/// Represents a channel connecting the client and server.
///
/// <seealso cref="System.IDisposable" />
public interface IConnectionChannel : IDisposable
{
///
/// Occurs when the channel is closed.
///
event AsyncEventHandler ClosedEventHandler;
///
/// Gets the client ip address.
///
///
/// The client ip address.
///
IPAddress ClientIPAddress { get; }
///
/// Gets a value indicating whether this instance is connected.
///
///
/// if this instance is connected; otherwise,
///
bool IsConnected { get; }
///
/// Gets or sets the receive timeout after which if data is expected but not received, the connection will be terminated.
///
///
/// The receive timeout.
///
TimeSpan ReceiveTimeout { get; set; }
///
/// Gets or sets the send timeout after which is data is being attempted to be sent but not completed, the connection will be terminated.
///
///
/// The send timeout.
///
TimeSpan SendTimeout { get; set; }
///
/// Applies the a filter to the stream which is used to read data from the channel.
///
/// <param name="filter">The filter.
/// <see cref="Task{T}"/> representing the async operation.
Task ApplyStreamFilter(Func<Stream, Task filter);
///
/// Closes the channel and notifies users via the <see cref="ClosedEventHandler"/> event.
///
/// <see cref="Task{T}"/> representing the async operation.
Task Close();
///
/// Flushes outgoing data.
///
/// <see cref="Task{T}"/> representing the async operation.
Task Flush();
///
/// Reads the next line from the channel.
///
/// <see cref="Task{T}"/> representing the async operation.
Task ReadLine();
///
/// Writes a line of text to the client.
///
/// <param name="text">The text<see cref="string"/>.
/// <see cref="Task{T}"/> representing the async operation.
Task WriteLine(string text);
}
}
|
c#
| 12 | 0.660014 | 139 | 30.52809 | 89 |
starcoderdata
|
def cmd_plot_image(self):
"""
To plot the original picture
@return: Nothing
"""
# Destroy the previous plots
for widget in self.frame1.winfo_children():
widget.destroy()
# If there is at least one picture to plot
if self.picN > 0:
img = self.image
fig = Figure(figsize=(5, 5))
# 2D plot
if self.chk_3D_var.get() == 0:
subplot = fig.add_subplot(111)
subplot.imshow(img)
subplot.set_xlabel('pixels', fontsize=fontsize)
subplot.set_ylabel('pixels', fontsize=fontsize)
y = len(img)
x = len(np.transpose(img))
# To change the label of the plot from pixels to mm if the ratio has been defined
if self.mcp_param.check_ratio_is_set():
self.plot_label_in_mm(subplot, x, y)
# To plot the circle if all the MCP parameters have been set
if self.mcp_param.check_all_set():
self.plot_circle(subplot, x, y)
# To plot a square if the auto-reshape checkbox is on
if len(self.auto_reshape) == 3 and self.chk_reshape_mcp_var.get() == 1:
self.plot_square(img, subplot)
# To plot the rectangle is reshaping parameters have been defined by the user
elif len(self.reshape_parameters) == 4:
self.plot_rectangle(subplot)
fig.tight_layout()
# 3D plot
else:
self.plot_3d(fig)
canvas = FigureCanvasTkAgg(fig, master=self.frame1)
canvas.mpl_connect('motion_notify_event', self.print_x_y_position)
canvas.draw()
canvas.get_tk_widget().pack()
|
python
| 13 | 0.524688 | 97 | 45.1 | 40 |
inline
|
package me.m1dnightninja.midnightcore.fabric.text;
import me.m1dnightninja.midnightcore.api.player.MPlayer;
import me.m1dnightninja.midnightcore.api.text.MScoreboard;
import me.m1dnightninja.midnightcore.api.text.MComponent;
import me.m1dnightninja.midnightcore.fabric.MidnightCore;
import me.m1dnightninja.midnightcore.fabric.player.FabricPlayer;
import me.m1dnightninja.midnightcore.fabric.util.ConversionUtil;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientboundSetDisplayObjectivePacket;
import net.minecraft.network.protocol.game.ClientboundSetObjectivePacket;
import net.minecraft.network.protocol.game.ClientboundSetPlayerTeamPacket;
import net.minecraft.network.protocol.game.ClientboundSetScorePacket;
import net.minecraft.server.ServerScoreboard;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.PlayerTeam;
import net.minecraft.world.scores.Score;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
import java.util.ArrayList;
import java.util.List;
public class FabricScoreboard extends MScoreboard {
private final PlayerTeam[] teams = new PlayerTeam[15];
private final ServerScoreboard board;
private final Objective objective;
private final boolean[] updated = new boolean[15];
private Component mcName;
public FabricScoreboard(String id, MComponent title) {
super(id, title);
mcName = ConversionUtil.toMinecraftComponent(title);
board = MidnightCore.getServer().getScoreboard();
objective = new Objective(board, id, ObjectiveCriteria.DUMMY, mcName, ObjectiveCriteria.RenderType.INTEGER);
for(int i = 0 ; i < teams.length ; i++) {
if(id.length() > 15) {
id = id.substring(0,14);
}
teams[i] = new PlayerTeam(board, id + Integer.toHexString(i));
teams[i].getPlayers().add("§" + Integer.toHexString(i));
}
}
@Override
public void setName(MComponent cmp) {
super.setName(cmp);
mcName = ConversionUtil.toMinecraftComponent(cmp);
objective.setDisplayName(mcName);
}
public void setLine(int line, MComponent message) {
if(line < 1 || line > 15) return;
if(message == null) {
teams[line].setPlayerPrefix(null);
board.resetPlayerScore("§" + Integer.toHexString(line), objective);
} else {
Component mcLine = ConversionUtil.toMinecraftComponent(message);
board.getOrCreatePlayerScore("§" + Integer.toHexString(line), objective).setScore(line);
teams[line].setPlayerPrefix(mcLine);
}
updated[line] = true;
}
@Override
protected void onPlayerAdded(MPlayer u) {
ServerPlayer player = ((FabricPlayer) u).getMinecraftPlayer();
if(player == null) return;
player.connection.send(new ClientboundSetObjectivePacket(objective, 0));
for(int i = 0 ; i < teams.length ; i++) {
player.connection.send(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(teams[i], true));
String name = "§" + Integer.toHexString(i);
Score s = board.getOrCreatePlayerScore(name, objective);
if(s.getScore() > 0) {
player.connection.send(new ClientboundSetScorePacket(ServerScoreboard.Method.CHANGE, objective.getName(), name, s.getScore()));
}
}
player.connection.send(new ClientboundSetDisplayObjectivePacket(1, objective));
}
@Override
protected void onPlayerRemoved(MPlayer u) {
ServerPlayer player = ((FabricPlayer) u).getMinecraftPlayer();
if(player == null) return;
player.connection.send(new ClientboundSetDisplayObjectivePacket(1, null));
for(int i = 0 ; i < teams.length ; i++) {
player.connection.send(ClientboundSetPlayerTeamPacket.createRemovePacket(teams[i]));
String name = "§" + Integer.toHexString(i);
player.connection.send(new ClientboundSetScorePacket(ServerScoreboard.Method.REMOVE, objective.getName(), name, 0));
}
player.connection.send(new ClientboundSetObjectivePacket(objective, 1));
}
public void update() {
List packets = new ArrayList<>();
if(objective.getDisplayName() != mcName) {
objective.setDisplayName(mcName);
packets.add(new ClientboundSetObjectivePacket(objective, 2));
}
for(int i = 0 ; i < teams.length ; i++) {
if(updated[i]) {
packets.add(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(teams[i], false));
if(teams[i].getPlayerPrefix() == null) {
packets.add(new ClientboundSetScorePacket(ServerScoreboard.Method.REMOVE, objective.getName(), "§" + Integer.toHexString(i), 0));
} else {
packets.add(new ClientboundSetScorePacket(ServerScoreboard.Method.CHANGE, objective.getName(), "§" + Integer.toHexString(i), i));
}
updated[i] = false;
}
}
for(MPlayer u : players) {
ServerPlayer player = ((FabricPlayer) u).getMinecraftPlayer();
if(player == null) continue;
for(Packet pck : packets) {
player.connection.send(pck);
}
}
}
}
|
java
| 19 | 0.662921 | 149 | 33.273292 | 161 |
starcoderdata
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
setup_box_plots.py
Functions to draw boxplots of the features with the worst parity from the data
output by openSMILE_dir_to_csv for recorder comparisons.
Author:
– 2017 (
© 2017, Child Mind Institute, Apache v2.0 License
"""
import os, sys
if os.path.abspath('../..') not in sys.path:
sys.path.append(os.path.abspath('../..'))
from test_recording_equipment.utilities import cmi_color_pallette as ccp
import openSMILE_dir_to_csv as odtc, pandas as pd, matplotlib.pyplot as plt, \
seaborn as sns, subprocess
sns.set_palette(ccp.cmi_colors())
def plot(dataframe, directory):
dataframe = dataframe.drop(['mean', 'median', 'std', 'mad'], axis=1)
dataframe = dataframe.T
indices = list(dataframe.index)
distances = []
screen = []
for index in indices:
distance, on_off = index.split('_', 1)
distances.append(distance)
screen.append(on_off)
dataframe.insert(0, "distance", distances)
dataframe.insert(0, "screen", screen)
dataframe = dataframe.drop([dataframe.columns[len(dataframe.columns)-1],
dataframe.columns[len(dataframe.columns)-2]], axis=1)
df_long = pd.melt(dataframe, ["distance", "screen"], var_name="features",
value_name="openSMILE outputs")
print(df_long.head(140))
plt.xticks(rotation=300, ha="left")
plt.figsize=(22,17)
plt.dpi=200
g = sns.boxplot(x="features", y="openSMILE outputs", data=
df_long.head(n=140), palette=cmi_colors)
plt.title(''.join(["Worst parity: ", os.path.basename(directory)]))
plt.tight_layout()
fig = g.get_figure()
fig.savefig(os.path.join(directory, "collected/boxplot.png"), dpi=300)
plt.close()
def main():
tippy_top = input("Top directory for recorder setup test: ")
# tippy_top = "PMAV"
top_dirs = [os.path.join(tippy_top, "ComParE_2016"),
os.path.join(tippy_top, "emobase")]
for directory in top_dirs:
if os.path.exists(os.path.join(directory, ".DS_Store")):
shell_command = ''.join(['rm ', os.path.join(directory,
".DS_Store")])
print(shell_command)
subprocess.run(shell_command, shell = True)
plot(odtc.oS_dir_to_csv(directory), directory)
# ============================================================================
if __name__ == '__main__':
main()
|
python
| 15 | 0.613482 | 78 | 37 | 66 |
starcoderdata
|
void CubeRenderer::render(QWindow *w, QOpenGLContext *share, uint texture)
{
if (!m_context)
init(w, share);
if (!m_context->makeCurrent(w))
return;
QOpenGLFunctions *f = m_context->functions();
f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (texture) {
f->glBindTexture(GL_TEXTURE_2D, texture);
f->glFrontFace(GL_CW); // because our cube's vertex data is such
f->glEnable(GL_CULL_FACE);
f->glEnable(GL_DEPTH_TEST);
m_program->bind();
QOpenGLVertexArrayObject::Binder vaoBinder(m_vao);
// If VAOs are not supported, set the vertex attributes every time.
if (!m_vao->isCreated())
setupVertexAttribs();
static GLfloat angle = 0;
QMatrix4x4 m;
m.translate(0, 0, -2);
m.rotate(90, 0, 0, 1);
m.rotate(angle, 0.5, 1, 0);
angle += 0.5f;
m_program->setUniformValue(m_matrixLoc, m_proj * m);
// Draw the cube.
f->glDrawArrays(GL_TRIANGLES, 0, 36);
}
m_context->swapBuffers(w);
}
|
c++
| 10 | 0.578704 | 75 | 27.447368 | 38 |
inline
|
/*-------------------------------------------------------------------------
*
* visibilitymapdefs.h
* macros for accessing contents of visibility map pages
*
*
* Copyright (c) 2021, PostgreSQL Global Development Group
*
* src/include/access/visibilitymapdefs.h
*
*-------------------------------------------------------------------------
*/
#ifndef VISIBILITYMAPDEFS_H
#define VISIBILITYMAPDEFS_H
/* Number of bits for one heap page */
#define BITS_PER_HEAPBLOCK 2
/* Flags for bit map */
#define VISIBILITYMAP_ALL_VISIBLE 0x01
#define VISIBILITYMAP_ALL_FROZEN 0x02
#define VISIBILITYMAP_VALID_BITS 0x03 /* OR of all valid visibilitymap
* flags bits */
#endif /* VISIBILITYMAPDEFS_H */
|
c
| 3 | 0.568846 | 75 | 27.76 | 25 |
starcoderdata
|
// @flow
import React from 'react';
import type { ComponentType } from 'react';
const connect = (mapUiToProps: Function) => (
(WrappedComponent: ComponentType => {
const uiComponents = mapUiToProps();
return ({
location, navigation, match, ...other
}: Object) => (
<WrappedComponent
{...uiComponents}
{...other}
navigation={navigation}
location={location || { pathname: navigation ? navigation.state.routeName : null }}
match={match || { params: { id: navigation ? navigation.getParam('id') : undefined } }}
/>
);
}
);
export default connect;
|
javascript
| 18 | 0.61756 | 95 | 28.217391 | 23 |
starcoderdata
|
/*******************************************************************************
* Copyright 2020-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef GPU_JIT_JIT_ELTWISE_INJECTOR_HPP
#define GPU_JIT_JIT_ELTWISE_INJECTOR_HPP
#include
#include "common/c_types_map.hpp"
#include "common/utils.hpp"
#include "gpu/jit/jit_generator.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
namespace jit {
inline bool jit_eltwise_injector_f32_is_supported(alg_kind_t alg) {
using namespace alg_kind;
// TODO Enable eltwise_gelu_tanh once accuracy is improved.
return utils::one_of(alg, eltwise_elu, eltwise_elu_use_dst_for_bwd,
eltwise_exp, eltwise_exp_use_dst_for_bwd, eltwise_gelu_erf,
eltwise_hardsigmoid, eltwise_hardswish, eltwise_log,
eltwise_logsigmoid, eltwise_mish, eltwise_pow, eltwise_relu,
eltwise_relu_use_dst_for_bwd, eltwise_bounded_relu,
eltwise_soft_relu, eltwise_sqrt, eltwise_sqrt_use_dst_for_bwd,
eltwise_square, eltwise_swish, eltwise_tanh,
eltwise_tanh_use_dst_for_bwd, eltwise_abs, eltwise_round,
eltwise_linear, eltwise_clip, eltwise_clip_v2,
eltwise_clip_v2_use_dst_for_bwd, eltwise_logistic,
eltwise_logistic_use_dst_for_bwd);
}
template <gpu_gen_t hw>
struct jit_eltwise_injector_f32 {
jit_eltwise_injector_f32(jit_generator *host, alg_kind_t alg,
float alpha, float beta, float scale,
const ngen::GRFRange &scratch = ngen::GRFRange(),
bool is_fwd = true)
: alg_(alg)
, alpha_(alpha)
, beta_(beta)
, scale_(scale)
, is_fwd_(is_fwd)
, h(host)
, scratch_(scratch) {
assert(jit_eltwise_injector_f32_is_supported(alg_));
assert(scratch_.isEmpty() || (scratch_.getLen() >= min_scratch_regs()));
}
int min_scratch_regs();
int preferred_scratch_regs();
void set_scratch(const ngen::GRFRange &scratch) { scratch_ = scratch; }
void prepare();
void compute(const ngen::GRF ®) { compute(reg - reg); }
void compute(const ngen::GRFRange ®s);
private:
const alg_kind_t alg_;
const float alpha_;
const float beta_;
const float scale_;
const bool is_fwd_;
jit_generator *h;
ngen::GRFRange scratch_;
int max_batch_size();
int phase_count(alg_kind_t alg);
void relu_prepare_bwd();
void abs_prepare_bwd();
void clip_prepare_bwd();
void relu_zero_ns_compute_fwd(int simd, const ngen::GRF &r);
void relu_compute_fwd(int simd, const ngen::GRF &r, int phase, int off);
void abs_compute_fwd(int simd, const ngen::GRF &r);
void exp_compute_fwd(int simd, const ngen::GRF &r, int phase);
void elu_compute_fwd(int simd, const ngen::GRF &r, int phase, int off);
void gelu_erf_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off, int batch);
void hardsigmoid_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off);
void hardswish_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off);
void log_compute_fwd(int simd, const ngen::GRF &r, int phase);
void logsigmoid_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off);
void mish_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off, int batch);
void pow_compute_fwd(int simd, const ngen::GRF &r, int phase, int off);
void soft_relu_compute_fwd_inner(int simd, const ngen::GRF &input,
const ngen::GRF &temp, const ngen::GRF &dest, int phase, int off);
void soft_relu_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off);
void sqrt_compute_fwd(int simd, const ngen::GRF &r);
void square_compute_fwd(int simd, const ngen::GRF &r);
void round_compute_fwd(int simd, const ngen::GRF &r);
void swish_compute_fwd(int simd, const ngen::GRF &r, int phase, int off);
void tanh_compute_fwd(int simd, const ngen::GRF &r, int phase, int off);
void linear_compute_fwd(int simd, const ngen::GRF &r, int phase);
void clip_compute_fwd(
int simd, const ngen::GRF &r, int phase, float alpha, float beta);
void gelu_tanh_compute_fwd(
int simd, const ngen::GRF &r, int phase, int off);
void logistic_compute_fwd(int simd, const ngen::GRF &r, int phase);
void relu_compute_bwd(int simd, const ngen::GRF &r);
void abs_compute_bwd(int simd, const ngen::GRF &r, int phase);
void square_compute_bwd(int simd, const ngen::GRF &r);
void linear_compute_bwd(int simd, const ngen::GRF &r);
void clip_compute_bwd(
int simd, const ngen::GRF &r, int phase, float alpha, float beta);
void gelu_tanh_compute_bwd(
int simd, const ngen::GRF &r, int phase, int off, int batch);
const ngen::InstructionModifier le = jit_generator
const ngen::InstructionModifier lt = jit_generator
const ngen::InstructionModifier ge = jit_generator
const ngen::InstructionModifier gt = jit_generator
const ngen::InstructionModifier eq = jit_generator
const ngen::InstructionModifier sat = jit_generator
const ngen::FlagRegister f0 = jit_generator
};
} // namespace jit
} // namespace gpu
} // namespace impl
} // namespace dnnl
#endif // GPU_JIT_JIT_ELTWISE_INJECTOR_HPP
|
c++
| 23 | 0.641965 | 80 | 40.121622 | 148 |
starcoderdata
|
console.log('Hello');
const funfunfun = (x,y,z) => {
if (true) {
return z
}
}
|
javascript
| 8 | 0.517241 | 30 | 11.428571 | 7 |
starcoderdata
|
def get(self):
'''
This shows the admin page.
'''
if not self.current_user:
self.redirect('/users/login')
current_user = self.current_user
# only allow in staff and superuser roles
if current_user and current_user['user_role'] in ('staff', 'superuser'):
# ask the authnzerver for a user list
reqtype = 'user-list'
reqbody = {'user_id': None}
ok, resp, msgs = yield self.authnzerver_request(
reqtype, reqbody
)
if not ok:
LOGGER.error('no user list returned from authnzerver')
user_list = []
else:
user_list = resp['user_info']
self.render('admin.html',
flash_messages=self.render_flash_messages(),
user_account_box=self.render_user_account_box(),
page_title="LCC-Server admin",
lccserver_version=__version__,
siteinfo=self.siteinfo,
userlist=user_list)
# anything else is probably the locked user, turn them away
else:
self.render_blocked_message()
|
python
| 12 | 0.498809 | 80 | 29.731707 | 41 |
inline
|
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* File:CommandImpl.java
****/
package com.microsoft.pmod;
public class CommandImpl extends BaseCommandImpl implements Command {
/**
* Internal constructor invoked by JNI
* @param interfaceValue
*/
CommandImpl(long interfaceValue) {
super(interfaceValue);
}
@SuppressWarnings("unchecked")
public TResult execute(TParameter parameter) {
return (TResult)super.executeInternal(parameter);
}
public boolean canExecute(TParameter parameter) {
return super.canExecuteInternal(parameter);
}
}
|
java
| 9 | 0.72423 | 109 | 25.666667 | 27 |
starcoderdata
|
int main (int argc, char **argv)
{
// initSPHInXCOM ();
SxCLI cli(argc, argv);
cli.setLoopSeparator ("-e"); // abuse looping feature
cli.stickyDefault = false;
SxString logFile = cli.option("-o", "file", "log file name").toString ();
bool join = cli.option ("-j|--join","join output and error channels")
.toBool ();
// declared, but not parsed here, parsed manually below
cli.option ("-e", "command", "command to execute").required ();
if (!cli.error && cli.last ().exists ()) {
cout << "-e option must be given after -o option!" << endl;
cli.setError ();
}
// now we finish CLI parsing, the rest is manual
cli.finalize ();
if (cli.arguments.getSize () < 1) {
cout << "SxTee: Missing -e option" << endl;
cli.printUsage ();
SX_QUIT;
}
cli.looping ();
// parse SxCLI option
SxString cmd = cli.option("-e","command","command to execute").toString ();
if (cli.error) { SX_QUIT; }
if (cmd == argv[0]) {
cerr << "Self-tee detected. Stopping to prevent infinite loop." << endl;
SX_QUIT;
}
// join higher loops
for (int iLoop = 2; iLoop < cli.arguments.getSize (); ++iLoop)
cli.arguments(1).append (cli.arguments(iLoop));
SxTee tee(logFile, cmd, cli.arguments(1));
if (join)
tee.setCommunication (SxProcess::Channels( SxProcess::Stdout
| SxProcess::Stderr));
// sxtee's internal error exit code
int status = -126;
try {
status = tee.start ();
} catch (SxException e) {
e.print ();
SX_EXIT;
}
return status;
}
|
c++
| 11 | 0.568485 | 78 | 30.150943 | 53 |
inline
|
namespace AluraCar.TestDrive.Models
{
public class Brake : AccessoryDecorator
{
private readonly Vehicle _vehicle;
public Brake(Vehicle vehicle)
{
_vehicle = vehicle;
}
public override string Name => $"{_vehicle.Name}, Brake";
public override decimal Price => _vehicle.Price + 800;
}
}
|
c#
| 8 | 0.596817 | 65 | 21.176471 | 17 |
starcoderdata
|
static protected List<Collection<TypedDependency>> readDeps(String filename) throws IOException {
BufferedReader breader = new BufferedReader(new FileReader(filename));
List<Collection<TypedDependency>> readDeps = new ArrayList<Collection<TypedDependency>>();
Collection<TypedDependency> deps = new ArrayList<TypedDependency>();
for (String line = breader.readLine(); line != null; line = breader.readLine()) {
if (line.equals("")) {
if (deps.size() != 0) {
//System.out.println(deps);
readDeps.add(deps);
deps = new ArrayList<TypedDependency>();
}
continue;
}
int firstParen = line.indexOf("(");
int commaSpace = line.indexOf(", ");
String depName = line.substring(0, firstParen);
String govName = line.substring(firstParen + 1, commaSpace);
String childName = line.substring(commaSpace+2, line.length() - 1);
GrammaticalRelation grel = EnglishGrammaticalRelations.valueOf(depName);
if (depName.startsWith("prep_")) {
String prep = depName.substring(5);
grel = EnglishGrammaticalRelations.getPrep(prep);
}
if (depName.startsWith("prepc_")) {
String prepc = depName.substring(6);
grel = EnglishGrammaticalRelations.getPrepC(prepc);
}
if (depName.startsWith("conj_")) {
String conj = depName.substring(5);
grel = EnglishGrammaticalRelations.getConj(conj);
}
if (grel == null) {
throw new RuntimeException("Unknown grammatical relation '" + depName+"'");
}
int govDash = govName.lastIndexOf("-");
int childDash = childName.lastIndexOf("-");
//Word govWord = new Word(govName.substring(0, govDash));
Word govWord = new Word(govName);
//Word childWord = new Word(childName.substring(0, childDash));
Word childWord = new Word(childName);
TypedDependency dep = new TypedDependencyStringEquality(grel, new TreeGraphNode(govWord), new TreeGraphNode(childWord));
deps.add(dep);
}
if (deps.size() != 0) {
readDeps.add(deps);
}
return readDeps;
}
|
java
| 14 | 0.628951 | 126 | 40.843137 | 51 |
inline
|
@Test
public void testSingleMultiEachGZIP() throws Exception {
Job job = new Job();
Stage one = new Stage("one");
one.addOutput("conn-1-2", new TupleflowString.ValueOrder(), CompressionType.GZIP);
one.add(new StepInformation(NullSource.class));
job.add(one);
Stage two = new Stage("two");
two.addInput("conn-1-2", new TupleflowString.ValueOrder());
two.addOutput("conn-2-3", new TupleflowString.ValueOrder(), CompressionType.GZIP);
two.add(new StepInformation(Generator.class, Parameters.parseString("{\"name\":\"two\", \"conn\":[\"conn-2-3\"]}")));
job.add(two);
Stage three = new Stage("three");
three.addInput("conn-2-3", new TupleflowString.ValueOrder());
// should recieve 10 items from each create of two (20 total)
three.add(new StepInformation(Receiver.class, Parameters.parseString("{\"expectedCount\":20, \"connIn\" : [\"conn-2-3\"]}")));
job.add(three);
job.connect("one", "two", ConnectionAssignmentType.Each);
job.connect("two", "three", ConnectionAssignmentType.Combined);
job.properties.put("hashCount", "2");
ErrorStore err = new ErrorStore();
Verification.verify(job, err);
JobExecutor.runLocally(job, err, Parameters.parseString("{\"server\":false}"));
if (err.hasStatements()) {
throw new RuntimeException(err.toString());
}
}
|
java
| 11 | 0.669623 | 130 | 40.030303 | 33 |
inline
|
package com.example.kaich.nvmotiondetection;
import android.util.DisplayMetrics;
public class PhotoTools {
public static final int RESULT_LOAD_VIDEO = 0;
public static final String ANALZYED_VIDEO_FILE_TAG = "_analyzedNVMD";
public static final String FOURCC = "H265";
public static final String FILE_EXTENSION = ".mp4"; //Don't know if these work yet
private DisplayMetrics displayMetrics;
public PhotoTools(DisplayMetrics displayMetrics){
this.displayMetrics = displayMetrics;
}
public int dpToPx(int dp){
return Math.round(dp * displayMetrics.density);
}
public int pxToDp(int px){
return Math.round(px / displayMetrics.density);
}
}
|
java
| 10 | 0.70547 | 86 | 25.407407 | 27 |
starcoderdata
|
const R = require('ramda')
const DEPENDENCIES = {
APP_BAR: [ 'BUTTON' ],
AUTOCOMPLETE: [ 'CHIP', 'INPUT' ],
AVATAR: [],
BUTTON: [ 'RIPPLE' ],
CARD: [ 'AVATAR' ],
CHECKBOX: [ 'RIPPLE' ],
CHIP: [ 'AVATAR' ],
DATE_PICKER: [ 'INPUT', 'DIALOG' ],
DIALOG: [ 'OVERLAY', 'BUTTON' ],
DRAWER: [ 'OVERLAY' ],
DROPDOWN: [ 'INPUT' ],
INPUT: [],
LAYOUT: [ 'APP_BAR', 'DRAWER' ],
LINK: [],
LIST: [ 'RIPPLE', 'AVATAR', 'CHECKBOX' ],
MENU: [ 'RIPPLE', 'BUTTON' ],
NAVIGATION: [ 'BUTTON', 'LINK' ],
OVERLAY: [],
PROGRESS_BAR: [],
RADIO: [ 'RIPPLE' ],
RIPPLE: [],
SLIDER: [ 'INPUT', 'PROGRESS_BAR' ],
SNACKBAR: [ 'BUTTON' ],
SWITCH: [ 'RIPPLE' ],
TABLE: [ 'CHECKBOX' ],
TABS: [],
TIME_PICKER: [ 'INPUT', 'DIALOG' ],
TOOLTIP: []
}
module.exports = function getDependencies(component) {
return R.uniq(R.flatten(_getDependencies(component, [ component ])))
}
function _getDependencies(component, dependencies) {
if (!DEPENDENCIES[component]) return dependencies
return R.concat(dependencies, R.map(function (id) {
return _getDependencies(id, [ id ])
}, DEPENDENCIES[component]))
}
|
javascript
| 13 | 0.598452 | 70 | 25.431818 | 44 |
starcoderdata
|
<?php
use yii\widgets\Breadcrumbs;
echo Breadcrumbs::widget([
'links' => array(
'Install Site Structure mosule',
)
]);
?>
Site Structure module
<?php
if (!$installed)
echo Html::a('Install database', array('install/installDatabase'));
else
echo 'Module table . $this->tableName . ' already exists';
?>
if ($result) echo $result; ?>
<?php
?>
|
php
| 10 | 0.591286 | 75 | 16.851852 | 27 |
starcoderdata
|
<?php
declare(strict_types=1);
namespace j45l\maybe;
use j45l\maybe\Context\Context;
use j45l\maybe\DoTry\ThrowableReason;
use Throwable;
/**
* @deprecated Move to v3
* @template T
* @extends Maybe
*/
class Deferred extends Maybe
{
/** @var callable */
protected $callable;
/** @param Context $context */
protected function __construct(callable $value, Context $context)
{
parent::__construct($context);
$this->callable = $value;
}
/**
* @return Deferred
*/
public static function create(callable $value): Deferred
{
return new self($value, Context::create());
}
/**
* @return Maybe
*/
protected function doResolve(): Maybe
{
try {
return Maybe::build(
($this->callable)(...$this->context()->parameters()->asArray()),
$this->context()
)->doResolve();
} catch (Throwable $throwable) {
return Maybe::buildFailure(ThrowableReason::fromThrowable($throwable), $this->context())->doResolve();
}
}
/**
* @param mixed $default
* @return mixed
*/
public function getOrElse($default)
{
return $this->doResolve()->getOrElse($default);
}
/**
* @param mixed $default
* @param string|int|array $propertyName
* @return mixed
*/
public function takeOrElse($propertyName, $default)
{
return $this->doResolve()->takeOrElse($propertyName, $default);
}
}
|
php
| 20 | 0.577143 | 114 | 21.5 | 70 |
starcoderdata
|
def get_section_by_title(header: str, soup: BeautifulSoup) -> element.Tag:
"""
Takes in a header string and returns the parent element of that header
"""
header_tag = soup.find(lambda tag: tag.name == 'h3' and header in tag.get_text())
if not header_tag:
raise FormatError('The header "{0}" no longer corresponds to a section'.format(header))
return header_tag.find_parent()
|
python
| 12 | 0.678133 | 95 | 44.333333 | 9 |
inline
|
using System.Threading;
using System.Threading.Tasks;
namespace NetStreams
{
public abstract class PipelineStep<TKey, TMessage>
{
public PipelineStep<TKey, TMessage> Next { get; set; }
public virtual async Task Execute(IConsumeContext<TKey, TMessage> consumeContext, CancellationToken token, NetStreamResult result = null)
{
if (this.Next != null)
{
return await this.Next.Execute(consumeContext, token, result);
}
return new NetStreamResult(null);
}
}
}
|
c#
| 15 | 0.635897 | 162 | 28.25 | 20 |
starcoderdata
|
"""
tags: Microsoft, Matrix, DFS, BFS
URL: https://leetcode.com/problems/shortest-bridge/discuss/374415/python-easy-to-understand-with-key-comments
"""
from typing import List
class Solution:
def shortestBridge(self, A: List[List[int]]) -> int:
found = False
stack = []
n, m = len(A), len(A[0])
# -----------
# find the first island
# -----------
for i in range(n):
for j in range(m):
if A[i][j]:
# -----------
# using depth first search to find all connected ('1') locations, since we already know there are only two islands. so we only need to find the first one
# -----------
self.dfs(A, i, j, n, m, stack)
found = True
break
if found:
break
steps = 0
# -----------
# breadth first search, once we find next '1', that is our final answer
# -----------
dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while stack:
size = len(stack)
level = []
while(size):
temp = stack.pop()
size-=1
x, y = temp[0], temp[1]
for dx, dy in dirs:
tx = x+dx
ty = y+dy
if tx<0 or ty<0 or tx>=n or ty>=m or A[tx][ty]==2:
continue
if A[tx][ty]==1:
return steps
A[tx][ty]=2
level.append((tx, ty))
steps+=1
stack = level
return -1
def dfs(self, A, row, col, n, m, stack):
# -----------
# we only need to find connected '1's. that's why we need A[row][col]==1
# -----------
if row<0 or col<0 or row>=n or col>=m or A[row][col]!=1:
return
A[row][col]=2
# -----------
# use stack for breath first search
# -----------
stack.append((row, col))
self.dfs(A, row+1, col, n, m, stack)
self.dfs(A, row-1, col, n, m, stack)
self.dfs(A, row, col+1, n, m, stack)
self.dfs(A, row, col-1, n, m, stack)
abc = Solution()
abc.shortestBridge([
[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 1]
])
|
python
| 17 | 0.405405 | 174 | 31.513514 | 74 |
starcoderdata
|
const router = require('express').Router()
const usersController = require('../controller/user.controller')
router.get('/me', usersController.me)
.get('/:id', usersController.getById)
module.exports = router
|
javascript
| 8 | 0.735849 | 64 | 25.5 | 8 |
starcoderdata
|
import LegacyAnalyticsContext from './LegacyAnalyticsContext';
import ModernAnalyticsContext from './ModernAnalyticsContext';
var ExportedAnalyticsContext;
if (process.env['ANALYTICS_NEXT_MODERN_CONTEXT']) {
ExportedAnalyticsContext = ModernAnalyticsContext;
}
else {
ExportedAnalyticsContext = LegacyAnalyticsContext;
}
export default ExportedAnalyticsContext;
//# sourceMappingURL=AnalyticsContext.js.map
|
javascript
| 6 | 0.828502 | 62 | 36.727273 | 11 |
starcoderdata
|
/*
* The MIT License
*
* Copyright (c) 2020 Jitcijk Inc.
*
* 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.
*/
package org.jitcijk.pryst.nodes;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.NodeInfo;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.source.SourceSection;
import org.jitcijk.pryst.PrystLanguage;
import org.jitcijk.pryst.builtins.PrystBuiltinNode;
import org.jitcijk.pryst.nodes.controlflow.PrystFunctionBodyNode;
/**
* The root of all Pryst execution trees. It is a Truffle requirement that the tree root extends the
* class {@link RootNode}. This class is used for both builtin and user-defined functions. For
* builtin functions, the {@link #bodyNode} is a subclass of {@link PrystBuiltinNode}. For user-defined
* functions, the {@link #bodyNode} is a {@link PrystFunctionBodyNode}.
*/
@NodeInfo(language = "Pryst", description = "The root of all Pryst execution trees")
public class PrystRootNode extends RootNode {
/** The function body that is executed, and specialized during execution. */
@Child private PrystExpressionNode bodyNode;
/** The name of the function, for printing purposes only. */
private final String name;
private boolean isCloningAllowed;
private final SourceSection sourceSection;
public PrystRootNode(PrystLanguage language, FrameDescriptor frameDescriptor, PrystExpressionNode bodyNode, SourceSection sourceSection, String name) {
super(language, frameDescriptor);
this.bodyNode = bodyNode;
this.name = name;
this.sourceSection = sourceSection;
}
@Override
public SourceSection getSourceSection() {
return sourceSection;
}
@Override
public Object execute(VirtualFrame frame) {
assert lookupContextReference(PrystLanguage.class).get() != null;
return bodyNode.executeGeneric(frame);
}
public PrystExpressionNode getBodyNode() {
return bodyNode;
}
@Override
public String getName() {
return name;
}
public void setCloningAllowed(boolean isCloningAllowed) {
this.isCloningAllowed = isCloningAllowed;
}
@Override
public boolean isCloningAllowed() {
return isCloningAllowed;
}
@Override
public String toString() {
return "root " + name;
}
}
|
java
| 11 | 0.735141 | 155 | 35.87234 | 94 |
starcoderdata
|
package com.zcswl.jta.mapper.db1;
import com.zcswl.jta.entity.Order;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* @author zhoucg
* @date 2021-01-15 14:21
*/
@Repository
public interface TOrderMapper {
int insertList(@Param("order") Order order);
}
|
java
| 10 | 0.747604 | 49 | 19.866667 | 15 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.