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 |
---|---|---|---|---|---|---|---|
func (h *TransactionReceiptWorker) QueueJob(transactions []string, blockNumber uint64, baseFee *big.Int, updateCache bool) ([]uint64, *big.Int, *big.Int, *big.Int) {
// Open a channel to maka sure all the receipts are processed and we block on the result.
results := make(chan transactionReceiptResult, len(transactions))
// Enqueue the jobs.
for _, tHash := range transactions {
h.jobs <- transactionReceiptJob{
Results: results,
BlockNumber: blockNumber,
TransactionHash: tHash,
BaseFee: baseFee,
UpdateCache: updateCache,
}
}
var allPriorityFeePerGasMwei []uint64
blockBurned := big.NewInt(0)
blockTips := big.NewInt(0)
type2count := int64(0)
// Wait for all the jobs to be processed.
for a := 0; a < len(transactions); a++ {
response := <-results
if response.Error != nil {
log.Errorln(response.Error)
continue
}
if response.Result == nil {
continue
}
if response.Result.Type == "0x2" {
type2count++
}
allPriorityFeePerGasMwei = append(allPriorityFeePerGasMwei, response.Result.PriorityFeePerGas.Uint64())
blockBurned.Add(blockBurned, response.Result.Burned)
blockTips.Add(blockTips, response.Result.Tips)
}
// Return the aggregated results.
return allPriorityFeePerGasMwei, blockBurned, blockTips, big.NewInt(type2count)
} | go | 13 | 0.709215 | 165 | 28.444444 | 45 | inline |
public synchronized void startIndexingTimer(String indexingStartTime, String indexingDaysOfWeek) throws Exception {
_indexingDaysOfWeek = null;
_indexingStartTimeDate = null;
if (indexingStartTime == null) {
stopIndexingTimer();
return;
}
Date currentTime = new Date();
try {
int dayInYear = Integer.parseInt(Utils.convertDateToString(currentTime, "D"));
int year = Integer.parseInt(Utils.convertDateToString(currentTime, "yyyy"));
_indexingStartTimeDate = Utils.convertStringToDate(year + " " + dayInYear + " " + indexingStartTime, "yyyy D H:mm");
Calendar startCal = new GregorianCalendar();
//prtln("Current day-of-week is: " + Utils.getDayOfWeekString(startCal.get(Calendar.DAY_OF_WEEK)));
// If this time has already passed today, increment to start tomorrow:
if (_indexingStartTimeDate.before(currentTime)) {
startCal = new GregorianCalendar();
startCal.setTime(_indexingStartTimeDate);
startCal.add(Calendar.DAY_OF_YEAR, 1);
_indexingStartTimeDate = startCal.getTime();
}
} catch (Throwable t) {
String msg = "Error parsing indexingStartTime value: " + t;
_indexingStartTimeDate = null;
throw new Exception(msg);
}
// Parse the days-of-week:
try {
_indexingDaysOfWeek = null;
if (indexingDaysOfWeek != null && indexingDaysOfWeek.trim().length() > 0) {
String[] indexingDaysOfWeekStrings = indexingDaysOfWeek.split(",");
if (indexingDaysOfWeekStrings.length > 0)
_indexingDaysOfWeek = new int[indexingDaysOfWeekStrings.length];
for (int i = 0; i < indexingDaysOfWeekStrings.length; i++) {
_indexingDaysOfWeek[i] = Integer.parseInt(indexingDaysOfWeekStrings[i].trim());
if (_indexingDaysOfWeek[i] < 1 || _indexingDaysOfWeek[i] > 7)
throw new Exception("Value must be an integer from 1 to 7 but found " + _indexingDaysOfWeek[i]);
}
}
} catch (Throwable t) {
String msg = "Error parsing indexingDaysOfWeek value: " + t.getMessage();
_indexingStartTimeDate = null;
_indexingDaysOfWeek = null;
throw new Exception(msg);
}
String daysOfWeekMsg = "all days.";
if (_indexingDaysOfWeek != null) {
daysOfWeekMsg = "these days of the week: ";
for (int i = 0; i < _indexingDaysOfWeek.length; i++)
daysOfWeekMsg += Utils.getDayOfWeekString(_indexingDaysOfWeek[i]) + (i == _indexingDaysOfWeek.length - 1 ? "" : ", ");
}
// 24 hours, in milliseconds:
long hours24 = 60 * 60 * 24 * 1000;
// Make sure the (previous) indexing timer is stopped before starting...
stopIndexingTimer();
_doPerformContinuousIndexing = false;
// Make a new timer, with daemon set to true
_indexingTimer = new Timer(true);
// Start the indexer at regular intervals beginning at the specified time
try {
prtln("Indexing timer is scheduled to start " +
Utils.convertDateToString(_indexingStartTimeDate, "EEE, MMM d, yyyy h:mm a zzz") +
", and run at that time on " + daysOfWeekMsg);
} catch (ParseException e) {}
_indexingTimer.scheduleAtFixedRate(new IndexingManagerTimerTask(), _indexingStartTimeDate, hours24);
prtln("IndexingManager indexing timer started");
} | java | 15 | 0.702556 | 122 | 38.1375 | 80 | inline |
const { VERSION } = require("eris");
const { version } = require("../../package.json");
exports.run = async function (client, msg, args) {
let user = msg.author;
let wsPING = new Date().getTime() - msg.timestamp;
msg.channel.createMessage("Pinging..").then(message => {
let msgEmbed = {
embed: {
color: client.config.colors.success,
description: `
🏓 **Discord API Ping:** \`${message.timestamp - msg.timestamp}ms\`
🌐 **WebSocket Ping:** \`${msg.channel.guild.shard.latency}ms\`
`,
footer: {
text: `Powered by Eris v${VERSION} | Bot version v${version}`
}
}
}
setTimeout(() => { message.edit(msgEmbed) }, 1000)
});
}
/*
msg.channel.createMessage(msgEmbed).then((message) => {
message.addReaction("✅");
})
*/
exports.help = {
cooldown: 5,
ratelimit: 1,
userPerms: [],
clientPerms: [],
description: "Testing Latency of Discord API",
usage: `j!ping (no argument)`,
example: `j!ping`,
aliases: []
} | javascript | 22 | 0.560606 | 81 | 25.738095 | 42 | starcoderdata |
<?php
/**
* Returns true if it's one of the applications and false if not
*
* @return boolean
*/
function is_application () {
return ( isset($_SERVER["HTTP_USER_AGENT"]) && ($_SERVER["HTTP_USER_AGENT"] == "CI/Windows" || $_SERVER["HTTP_USER_AGENT"] == "CI/Android"));
}
function is_ajax () {
return (! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
/**
* Returns true if it's the windows application that request or sends data
*
* @return boolean
*/
function is_windows () {
return ( isset($_SERVER["HTTP_USER_AGENT"]) && $_SERVER["HTTP_USER_AGENT"] == "CI/Windows");
}
?> | php | 12 | 0.636637 | 142 | 26.791667 | 24 | starcoderdata |
from django.db import models
from common.models import Lang
FEMALE = 1
MALE = 2
GENDER_CHOICES = (
(FEMALE, "Female"),
(MALE, "Male")
)
class Person(models.Model):
"""
`Person` represents a person that work in the cinema world could be
an actor, producer, director ...
Attributes:
"""
name = models.CharField(max_length=100)
birthday = models.DateField(null=True, blank=True)
death = models.DateField(null=True, blank=True)
gender = models.IntegerField(choices=GENDER_CHOICES, null=True, blank=True)
place_of_birthday = models.CharField(max_length=100, null=True, blank=True)
image = models.URLField(null=True, blank=True)
homepage = models.URLField(null=True, blank=True)
langs = models.ManyToManyField(Lang, through='Person_lang', blank=True)
def __str__(self):
return self.name
class Person_lang(models.Model):
"""
`Person_lan` is a extension to Person for language translation.
Attributes:
"""
person = models.ForeignKey(Person, on_delete=models.CASCADE)
lang = models.ForeignKey(Lang, on_delete=models.CASCADE)
biography = models.TextField()
class Job (models.Model):
"""
`Job` presents diferents movie jobs.
Attributes:
"""
langs = models.ManyToManyField(Lang, through='Job_lang')
class Job_lang(models.Model):
"""
`Job_lang` is a extension to Jon where translate some params.
Attributes:
"""
job = models.name = models.ForeignKey(Job, on_delete=models.CASCADE)
lang = models.ForeignKey(Lang, on_delete=models.CASCADE)
name = models.CharField(max_length=100) | python | 10 | 0.675229 | 79 | 26.25 | 60 | starcoderdata |
void OT_inc(T_Occurrence_table * t,byte r,byte g,byte b)
{
int index;
// Drop bits as needed
r=(r>>t->red_r);
g=(g>>t->red_g);
b=(b>>t->red_b);
// Compute the address
index=(r<<t->dec_r) | (g<<t->dec_g) | (b<<t->dec_b);
t->table[index]++;
} | c | 10 | 0.531008 | 56 | 18.923077 | 13 | inline |
"""Scale Bar visual."""
import bisect
import numpy as np
from vispy.scene.visuals import Line, Text
from vispy.visuals.transforms import STTransform
from ..components._viewer_constants import Position
from ..utils._units import PREFERRED_VALUES, get_unit_registry
from ..utils.colormaps.standardize_color import transform_color
from ..utils.theme import get_theme
from ..utils.translations import trans
class VispyScaleBarVisual:
"""Scale bar in world coordinates."""
def __init__(self, viewer, parent=None, order=0):
self._viewer = viewer
self._data = np.array(
[
[0, 0, -1],
[1, 0, -1],
[0, -5, -1],
[0, 5, -1],
[1, -5, -1],
[1, 5, -1],
]
)
self._default_color = np.array([1, 0, 1, 1])
self._target_length = 150
self._scale = 1
self._quantity = None
self._unit_reg = None
self.node = Line(
connect='segments', method='gl', parent=parent, width=3
)
self.node.order = order
self.node.transform = STTransform()
# In order for the text to always appear centered on the scale bar,
# the text node should use the line node as the parent.
self.text_node = Text(pos=[0.5, -1], parent=self.node)
self.text_node.order = order
self.text_node.transform = STTransform()
self.text_node.font_size = 10
self.text_node.anchors = ("center", "center")
self.text_node.text = f"{1}px"
# Note:
# There are issues on MacOS + GitHub action about destroyed
# C/C++ object during test if those don't get disconnected.
def set_none():
self.node._set_canvas(None)
self.text_node._set_canvas(None)
# the two canvas are not the same object, better be safe.
self.node.canvas._backend.destroyed.connect(set_none)
self.text_node.canvas._backend.destroyed.connect(set_none)
assert self.node.canvas is self.text_node.canvas
# End Note
self._viewer.events.theme.connect(self._on_data_change)
self._viewer.scale_bar.events.visible.connect(self._on_visible_change)
self._viewer.scale_bar.events.colored.connect(self._on_data_change)
self._viewer.scale_bar.events.ticks.connect(self._on_data_change)
self._viewer.scale_bar.events.position.connect(
self._on_position_change
)
self._viewer.camera.events.zoom.connect(self._on_zoom_change)
self._viewer.scale_bar.events.font_size.connect(self._on_text_change)
self._viewer.scale_bar.events.unit.connect(self._on_dimension_change)
self._on_visible_change(None)
self._on_data_change(None)
self._on_dimension_change(None)
self._on_position_change(None)
@property
def unit_registry(self):
"""Get unit registry.
Rather than instantiating UnitRegistry earlier on, it is instantiated
only when it is needed. The reason for this is that importing `pint`
at module level can be time consuming.
Notes
-----
https://github.com/napari/napari/pull/2617#issuecomment-827716325
https://github.com/napari/napari/pull/2325
"""
if self._unit_reg is None:
self._unit_reg = get_unit_registry()
return self._unit_reg
def _on_dimension_change(self, event):
"""Update dimension."""
if not self._viewer.scale_bar.visible and self._unit_reg is None:
return
unit = self._viewer.scale_bar.unit
self._quantity = self.unit_registry(unit)
self._on_zoom_change(None, True)
def _calculate_best_length(self, desired_length: float):
"""Calculate new quantity based on the pixel length of the bar.
Parameters
----------
desired_length : float
Desired length of the scale bar in world size.
Returns
-------
new_length : float
New length of the scale bar in world size based
on the preferred scale bar value.
new_quantity : pint.Quantity
New quantity with abbreviated base unit.
"""
current_quantity = self._quantity * desired_length
# convert the value to compact representation
new_quantity = current_quantity.to_compact()
# calculate the scaling factor taking into account any conversion
# that might have occurred (e.g. um -> cm)
factor = current_quantity / new_quantity
# select value closest to one of our preferred values
index = bisect.bisect_left(PREFERRED_VALUES, new_quantity.magnitude)
if index > 0:
# When we get the lowest index of the list, removing -1 will
# return the last index.
index -= 1
new_value = PREFERRED_VALUES[index]
# get the new pixel length utilizing the user-specified units
new_length = (
(new_value * factor) / self._quantity.magnitude
).magnitude
new_quantity = new_value * new_quantity.units
return new_length, new_quantity
def _on_zoom_change(self, event, force: bool = False):
"""Update axes length based on zoom scale."""
if not self._viewer.scale_bar.visible:
return
# If scale has not changed, do not redraw
scale = 1 / self._viewer.camera.zoom
if abs(np.log10(self._scale) - np.log10(scale)) < 1e-4 and not force:
return
self._scale = scale
scale_canvas2world = self._scale
target_canvas_pixels = self._target_length
# convert desired length to world size
target_world_pixels = scale_canvas2world * target_canvas_pixels
# calculate the desired length as well as update the value and units
target_world_pixels_rounded, new_dim = self._calculate_best_length(
target_world_pixels
)
target_canvas_pixels_rounded = (
target_world_pixels_rounded / scale_canvas2world
)
scale = target_canvas_pixels_rounded
sign = (
-1
if self._viewer.scale_bar.position
in [Position.TOP_RIGHT, Position.BOTTOM_RIGHT]
else 1
)
# Update scalebar and text
self.node.transform.scale = [sign * scale, 1, 1, 1]
self.text_node.text = f'{new_dim:~}'
def _on_data_change(self, event):
"""Change color and data of scale bar."""
if self._viewer.scale_bar.colored:
color = self._default_color
else:
# the reason for using the `as_hex` here is to avoid
# `UserWarning` which is emitted when RGB values are above 1
background_color = get_theme(
self._viewer.theme, False
).canvas.as_hex()
background_color = transform_color(background_color)[0]
color = np.subtract(1, background_color)
color[-1] = background_color[-1]
if self._viewer.scale_bar.ticks:
data = self._data
else:
data = self._data[:2]
self.node.set_data(data, color)
self.text_node.color = color
def _on_visible_change(self, event):
"""Change visibility of scale bar."""
self.node.visible = self._viewer.scale_bar.visible
self.text_node.visible = self._viewer.scale_bar.visible
# update unit if scale bar is visible and quantity
# has not been specified yet or current unit is not
# equivalent
if self._viewer.scale_bar.visible and (
self._quantity is None
or self._quantity.units != self._viewer.scale_bar.unit
):
self._quantity = self.unit_registry(self._viewer.scale_bar.unit)
# only force zoom update if the scale bar is visible
self._on_zoom_change(None, self._viewer.scale_bar.visible)
def _on_text_change(self, event):
"""Update text information"""
self.text_node.font_size = self._viewer.scale_bar.font_size
def _on_position_change(self, event):
"""Change position of scale bar."""
position = self._viewer.scale_bar.position
x_bar_offset, y_bar_offset = 10, 30
canvas_size = list(self.node.canvas.size)
if position == Position.TOP_LEFT:
sign = 1
bar_transform = [x_bar_offset, 10, 0, 0]
elif position == Position.TOP_RIGHT:
sign = -1
bar_transform = [canvas_size[0] - x_bar_offset, 10, 0, 0]
elif position == Position.BOTTOM_RIGHT:
sign = -1
bar_transform = [
canvas_size[0] - x_bar_offset,
canvas_size[1] - y_bar_offset,
0,
0,
]
elif position == Position.BOTTOM_LEFT:
sign = 1
bar_transform = [x_bar_offset, canvas_size[1] - 30, 0, 0]
else:
raise ValueError(
trans._(
'Position {position} not recognized.',
deferred=True,
position=self._viewer.scale_bar.position,
)
)
self.node.transform.translate = bar_transform
scale = abs(self.node.transform.scale[0])
self.node.transform.scale = [sign * scale, 1, 1, 1]
self.text_node.transform.translate = (0, 20, 0, 0) | python | 17 | 0.586478 | 78 | 35.976744 | 258 | starcoderdata |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/SearchFoundation.framework/SearchFoundation
*/
@interface _SFPBMediaItem : PBCodable <NSSecureCoding, _SFPBMediaItem> {
NSArray * _buyOptions;
NSString * _contentAdvisory;
_SFPBImage * _contentAdvisoryImage;
_SFPBImage * _overlayImage;
_SFPBPunchout * _punchout;
_SFPBImage * _reviewGlyph;
NSString * _reviewText;
NSArray * _subtitleCustomLineBreakings;
_SFPBText * _subtitleText;
_SFPBImage * _thumbnail;
NSString * _title;
}
@property (nonatomic, copy) NSArray *buyOptions;
@property (nonatomic, copy) NSString *contentAdvisory;
@property (nonatomic, retain) _SFPBImage *contentAdvisoryImage;
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (nonatomic, readonly) NSData *jsonData;
@property (nonatomic, retain) _SFPBImage *overlayImage;
@property (nonatomic, retain) _SFPBPunchout *punchout;
@property (nonatomic, retain) _SFPBImage *reviewGlyph;
@property (nonatomic, copy) NSString *reviewText;
@property (nonatomic, copy) NSArray *subtitleCustomLineBreakings;
@property (nonatomic, retain) _SFPBText *subtitleText;
@property (readonly) Class superclass;
@property (nonatomic, retain) _SFPBImage *thumbnail;
@property (nonatomic, copy) NSString *title;
- (void).cxx_destruct;
- (void)addBuyOptions:(id)arg1;
- (void)addSubtitleCustomLineBreaking:(id)arg1;
- (id)buyOptions;
- (id)buyOptionsAtIndex:(unsigned long long)arg1;
- (unsigned long long)buyOptionsCount;
- (void)clearBuyOptions;
- (void)clearSubtitleCustomLineBreaking;
- (id)contentAdvisory;
- (id)contentAdvisoryImage;
- (id)dictionaryRepresentation;
- (unsigned long long)hash;
- (id)initWithDictionary:(id)arg1;
- (id)initWithFacade:(id)arg1;
- (id)initWithJSON:(id)arg1;
- (bool)isEqual:(id)arg1;
- (id)jsonData;
- (id)overlayImage;
- (id)punchout;
- (bool)readFrom:(id)arg1;
- (id)reviewGlyph;
- (id)reviewText;
- (void)setBuyOptions:(id)arg1;
- (void)setContentAdvisory:(id)arg1;
- (void)setContentAdvisoryImage:(id)arg1;
- (void)setOverlayImage:(id)arg1;
- (void)setPunchout:(id)arg1;
- (void)setReviewGlyph:(id)arg1;
- (void)setReviewText:(id)arg1;
- (void)setSubtitleCustomLineBreaking:(id)arg1;
- (void)setSubtitleCustomLineBreakings:(id)arg1;
- (void)setSubtitleText:(id)arg1;
- (void)setThumbnail:(id)arg1;
- (void)setTitle:(id)arg1;
- (id)subtitleCustomLineBreakingAtIndex:(unsigned long long)arg1;
- (unsigned long long)subtitleCustomLineBreakingCount;
- (id)subtitleCustomLineBreakings;
- (id)subtitleText;
- (id)thumbnail;
- (id)title;
- (void)writeTo:(id)arg1;
@end | c | 6 | 0.752981 | 87 | 33.410256 | 78 | starcoderdata |
package info.xiancloud.core.distribution.res;
import info.xiancloud.core.init.Destroyable;
import info.xiancloud.core.util.Reflection;
import java.util.List;
import java.util.Properties;
/**
* @author happyyangyuan
* 定制统一的接口规范,资源变动感知接口
*/
public interface IResAware extends Destroyable {
List resAwares = Reflection.getSubClassInstances(IResAware.class);
IResAware singleton = resAwares.isEmpty() ? null : resAwares.get(0);
/**
* @param pluginName 插件名
* @param key 配置key名
* @return 资源配置的取值,如果当前节点尚未连接到注册中心,那么返回null,如果key插件或者key不存在,那么返回null。
* If the key exists but value is empty, then an empty string is returned.
*/
String get(String pluginName, String key);
/**
* 读取整个配置
*
* @param pluginName 插件名
* @return 整个配置,如果当前节点尚未连接到注册中心,那么返回size=0的properties对象,如果key插件不存在,那么返回size=0的properties对象
*/
Properties getAll(String pluginName);
/**
* @param pluginName 插件名
* @return 注册中心内的插件版本号,目前的版本号规则见build.gradle配置;如果当前节点尚未连接到注册中心,那么返回null;如果注册中心中没有该插件配置,那么返回null
*/
String getVersion(String pluginName);
} | java | 8 | 0.718563 | 99 | 26.833333 | 42 | starcoderdata |
package com.hys.exam.service.local.impl;
import java.util.List;
import com.hys.exam.dao.local.ReplyManageDAO;
import com.hys.exam.model.Reply;
import com.hys.exam.service.local.ReplyManage;
import com.hys.framework.service.impl.BaseMangerImpl;
/**
* @author weeho
*
*/
public class ReplyManageImpl extends BaseMangerImpl implements ReplyManage {
private ReplyManageDAO replyManageDAO;
public ReplyManageDAO getReplyManageDAO() {
return replyManageDAO;
}
public void setReplyManageDAO(ReplyManageDAO replyManageDAO) {
this.replyManageDAO = replyManageDAO;
}
@Override
public boolean addReply(Reply reply) {
return replyManageDAO.addReply(reply);
}
@Override
public List getReplyById(Long id) {
return replyManageDAO.getReplyById(id);
}
} | java | 8 | 0.782353 | 77 | 21.368421 | 38 | starcoderdata |
/*
Copyright 2012 http://www.pdfclown.org
Contributors:
* (original code developer, http://www.stefanochizzolini.it)
This file should be part of the source code distribution of "PDF Clown library" (the
Program): see the accompanying README files for more info.
This Program is free software; you can redistribute it and/or modify it under the terms
of the GNU Lesser General Public License as published by the Free Software Foundation;
either version 3 of the License, or (at your option) any later version.
This Program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY,
either expressed or implied; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the License for more details.
You should have received a copy of the GNU Lesser General Public License along with this
Program (see README files); if not, go to the GNU website (http://www.gnu.org/licenses/).
Redistribution and use, with or without modification, are permitted provided that such
redistributions retain the above copyright notice, license and disclaimer, along with
this list of conditions.
*/
using System;
using System.Text;
using PasswordProtectedChecker.Pdf.Interfaces;
namespace PasswordProtectedChecker.Pdf
{
/**
utility.
*/
public static class VersionUtils
{
public static int CompareTo(IVersion version1, IVersion version2)
{
var comparison = 0;
{
var version1Numbers = version1.Numbers;
var version2Numbers = version2.Numbers;
for (
int index = 0,
length = Math.Min(version1Numbers.Count, version2Numbers.Count);
index < length;
index++
)
{
comparison = version1Numbers[index] - version2Numbers[index];
if (comparison != 0)
break;
}
if (comparison == 0) comparison = version1Numbers.Count - version2Numbers.Count;
}
return Math.Sign(comparison);
}
public static string ToString(IVersion version)
{
var versionStringBuilder = new StringBuilder();
foreach (var number in version.Numbers)
{
if (versionStringBuilder.Length > 0) versionStringBuilder.Append('.');
versionStringBuilder.Append(number);
}
return versionStringBuilder.ToString();
}
}
} | c# | 16 | 0.633925 | 96 | 35.777778 | 72 | starcoderdata |
package stepDefinitions;
import org.junit.Assert;
import selenium.Wait;
import cucumber.TestContext;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageObjects.AssessmentPage;
import pageObjects.Homepage;
public class AssessmentStepDefinitions{
TestContext testContext;
AssessmentPage assessmentPage;
Wait wait;
Homepage home;
public AssessmentStepDefinitions(TestContext context) {
testContext = context;
assessmentPage = testContext.getPageObjectManager().getAssessmentPage();
home = testContext.getPageObjectManager().getHomePage();
}
@Then("^I should be navigated to Assessment page$")
public void i_should_be_navigated_to_Assessment_Page() throws Throwable{
Thread.sleep(3000);
String URL = home.getUrl();
Assert.assertTrue("Url does not consist of Assessment", URL.contains("http://localhost:3000/assessment"));
Assert.assertTrue("User is not navigated to Assessment Page", assessmentPage.assessmentPageTitle.isDisplayed());
}
@Given("^I am on Assessment page$")
public void i_am_on_Assessment_page() throws Throwable{
Thread.sleep(3000);
home.clickAssessmentLink();
}
@Then("^I should see header image and title$")
public void i_should_see_header_image_and_title() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Assessment header image is not displayed", assessmentPage.headerImage.isDisplayed());
Assert.assertTrue("Assessment page title is not displayed", assessmentPage.assessmentPageTitle.isDisplayed());
}
@Then("^Why Assessment sections is displayed$")
public void why_assessment_section_is_displayed() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Why Assessment section is not displayed", assessmentPage.whyAssessmentSection.isDisplayed());
}
@Then("^What are the different types of Assessment Section is displayed$")
public void what_are_the_different_types_of_Assessment_Section_is_displayed() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("What are the different types of Assessment section is not displayed",
assessmentPage.whatAreTheDifferentTypesOfAssessment.isDisplayed());
}
@When("^I view Why Assessment section$")
public void i_view_Why_Assessment_section() throws Throwable{
assessmentPage.whyAssessmentSection.isDisplayed();
}
@Then("^I should see title and description$")
public void i_should_see_title_and_description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Why Assessment title is not displayed", assessmentPage.whyAssessmentTitle.isDisplayed());
Assert.assertTrue("Why Assessment description is not displayed", assessmentPage.whyAssessmentSection.isDisplayed());
}
@Then("^I should see contact us button$")
public void i_should_see_contact_us_button() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Contact Us button is not displayed", assessmentPage.whyAssessmentContactUs.isDisplayed());
}
@When("^I view What are different types of Assessment section$")
public void i_view_What_are_different_types_of_Assessment_section() throws Throwable{
assessmentPage.whatAreTheDifferentTypesOfAssessment.isDisplayed();
}
@Then("^I should see there Leadership Assessment section$")
public void i_should_see_there_Leadership_Assessment_section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Leadership Assessment section is not displayed", assessmentPage.leadershipAssessmentSection.isDisplayed());
}
@Then("^I should see Organization Assessment section$")
public void i_should_see_Organizational_Assessment_section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Organization Assessment section is not displayed", assessmentPage.organizationAssessmentSection.isDisplayed());
}
@Then("^I should see Portfolio Assessment section$")
public void i_should_see_Portfolio_Assessment_section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Portfolio Assessment section is not displayed", assessmentPage.organizationAssessmentSection.isDisplayed());
}
@Then("^I should see Program Assessment section$")
public void i_should_see_program_Assessment_Section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Program Assessment section is not displayed", assessmentPage.programAssessmentSection.isDisplayed());
}
@Then("^I should see Team Assessment section$")
public void i_should_see_Team_Assessment_Section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Team Assessment section is not displayed", assessmentPage.teamAssessmentSection.isDisplayed());
}
@Then("^I should see Individual Role or Talent section$")
public void i_should_see_Individual_Role_or_talent_Section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Individual role or Talent section is not displayed", assessmentPage.individualRoleSection.isDisplayed());
}
@Then("^I should see contact us below what are different types of Assessment section$")
public void i_should_see_contact_us_below_what_are_different_types_of_Assessment_Section() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Contact us button below what are different types of Assessment section is not displayed",
assessmentPage.whyAssessmentContactUs.isDisplayed());
}
@When("^I view Leadership Assessment section$")
public void i_view_Leadership_Assessment_Section() throws Throwable{
assessmentPage.leadershipAssessmentSection.isDisplayed();
}
@Then("^I should see leadership title and description$")
public void i_should_see_leadership_title_and_description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Leadership title is not displayed", assessmentPage.leadershipAssessmentTitle.isDisplayed());
Assert.assertTrue("Leadership description is not displayed", assessmentPage.leadershipAssessmentDescription.isDisplayed());
}
@Then("^I should see leadership image$")
public void i_should_see_leadership_image() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Leadership image is not displayed", assessmentPage.leadershipAssessmentImage.isDisplayed());
}
@When("^I view Organization Assessment section$")
public void i_view_Organization_Assessment_section() throws Throwable{
assessmentPage.organizationAssessmentSection.isDisplayed();
}
@Then("^I should see organization title and description$")
public void i_should_see_organization_title_and_description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Organization title is not displayed", assessmentPage.organizationAssessmentTitle.isDisplayed());
Assert.assertTrue("Organization description is not displayed", assessmentPage.organizationAssessmentDescription.isDisplayed());
}
@Then("^I should see organization image$")
public void i_should_see_organization_image() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Organization image is not displayed", assessmentPage.organizationAssessmentImage.isDisplayed());
}
@When("^I view Portfolio Assessment section$")
public void i_view_Portfolio_Assessment_section() throws Throwable{
assessmentPage.portfolioAssessmentSection.isDisplayed();
}
@Then("^I should see portfolio title and description$")
public void i_should_see_portfolio_title_And_Description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Portfolio title is not displayed", assessmentPage.portfolioAssessmentTitle.isDisplayed());
Assert.assertTrue("Portfolio description is not displayed", assessmentPage.portfolioAssessmentDescription.isDisplayed());
}
@Then("^I should see portfolio image$")
public void i_should_see_portfolio_image() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Portfolio image is not displayed", assessmentPage.portfolioAssessmentImage.isDisplayed());
}
@When("^I view Program Assessment section$")
public void i_view_Program_Assessment_Section() throws Throwable{
assessmentPage.programAssessmentSection.isDisplayed();
}
@Then("^I should see program title and description$")
public void i_should_see_program_title_and_description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Program title is not displayed", assessmentPage.programAssessmentTitle.isDisplayed());
Assert.assertTrue("Program description is not displayed", assessmentPage.programAssessmentDescription.isDisplayed());
}
@Then("^I should see program image$")
public void i_should_see_program_image() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Program image is not displayed", assessmentPage.programAssessmentImage.isDisplayed());
}
@When("^I view Team Assessment section$")
public void i_view_Team_Assessment_Section() throws Throwable{
assessmentPage.teamAssessmentSection.isDisplayed();
}
@Then("^I should see team title and description$")
public void i_should_see_team_title_and_description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Team title is not displayed", assessmentPage.teamAssessmentTitle.isDisplayed());
Assert.assertTrue("Team description is not displayed", assessmentPage.teamAssessmentDescription.isDisplayed());
}
@Then("^I should see team image$")
public void i_should_see_team_image() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Team image is not displayed", assessmentPage.teamAssessmentImage.isDisplayed());
}
@When("^I view Individual Role or Talent section$")
public void i_view_Individual_role_or_Talent_section() throws Throwable{
assessmentPage.individualRoleSection.isDisplayed();
}
@Then("^I should see individual role title and description$")
public void i_should_see_individual_role_title_and_description() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Individual Role title is not displayed", assessmentPage.individualRoleTitle.isDisplayed());
Assert.assertTrue("Individual Role description is not displayed", assessmentPage.individualRoleDescription.isDisplayed());
}
@Then("^I should see individual role image$")
public void i_should_see_individual_role_image() throws Throwable{
Thread.sleep(3000);
Assert.assertTrue("Team image is not displayed", assessmentPage.individualRoleImage.isDisplayed());
}
@When("^I click on contact us button on Assessment page$")
public void i_click_on_contact_us_button_on_Assessment_page() throws Throwable{
assessmentPage.clickContactUsButton();
}
} | java | 9 | 0.781981 | 132 | 42.983193 | 238 | starcoderdata |
protected void writeUpstreamHeaders() {
HttpHeaders headers = request.headers();
// Check chunk flag on the request if there are some content to push and if transfer_encoding is set
// with chunk value
if (content) {
String encoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING);
if (encoding != null && encoding.contains(HttpHeadersValues.TRANSFER_ENCODING_CHUNKED)) {
httpClientRequest.setChunked(true);
}
} else {
request.headers().remove(HttpHeaders.TRANSFER_ENCODING);
}
// Copy headers to upstream
request.headers().forEach(httpClientRequest::putHeader);
} | java | 11 | 0.632857 | 108 | 40.235294 | 17 | inline |
#ifndef _GAMEPORT_H_
#define _GAMEPORT_H_
#include
class Gameport {
private:
const uint8_t W1_ADDRESS = 0;
const uint8_t W2_ADDRESS = 1;
const uint8_t W3_ADDRESS = 2;
const uint8_t W4_ADDRESS = 3;
const uint8_t POT_CS_PIN;
const uint8_t BUTTON1_PIN;
const uint8_t BUTTON2_PIN;
const uint8_t BUTTON3_PIN;
const uint8_t BUTTON4_PIN;
public:
Gameport(uint8_t potCsPin, uint8_t button1Pin, uint8_t button2Pin,
uint8_t button3Pin, uint8_t button4Pin)
: POT_CS_PIN(potCsPin),
BUTTON1_PIN(button1Pin),
BUTTON2_PIN(button2Pin),
BUTTON3_PIN(button3Pin),
BUTTON4_PIN(button4Pin) {}
/**
* Initializes the gameport interface.
*/
void init();
/**
* Sets all button pins to the given pressed states.
*/
void setButtonStates(bool button1, bool button2, bool button3, bool button4);
/**
* Writes all 4 wiper states to the digital potentiometer.
*
* Note: there is no wait in between the CS transitions since the pot is
* specified at 10ns min.pulse-width (48Mhz is ~20ns).
*/
void setAxes(uint8_t axis1, uint8_t axis2, uint8_t axis3, uint8_t axis4);
};
#endif // _GAMEPORT_H_ | c | 11 | 0.663016 | 79 | 24.255319 | 47 | starcoderdata |
// ComputationBalancer.cs
//
// Author:
//
//
// Copyright (c) 2018
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AT_Utils
{
[KSPAddon(KSPAddon.Startup.FlightEditorAndKSC, false)]
public class ComputationBalancer : MonoBehaviour
{
public class Task
{
public IEnumerator iter;
public bool finished;
public bool error;
public static implicit operator bool(Task t) => t.finished;
}
static ComputationBalancer Instance;
static bool level_loaded;
DateTime next_ts = DateTime.MinValue;
LowPassFilterF fps = new LowPassFilterF();
LowPassFilterF base_fps = new LowPassFilterF();
double duration;
public static float FPS => Instance.fps;
public static float FPS_AVG => Instance.base_fps;
List tasks = new List
int current = 0;
void Awake()
{
if(Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
GameEvents.onLevelWasLoadedGUIReady.Add(onLevelLoaded);
GameEvents.onGameSceneLoadRequested.Add(onGameSceneLoad);
}
void Start()
{
fps.Tau = 1;
base_fps.Tau = 2;
}
void OnDestroy()
{
Instance = null;
GameEvents.onLevelWasLoadedGUIReady.Remove(onLevelLoaded);
GameEvents.onGameSceneLoadRequested.Remove(onGameSceneLoad);
}
void onLevelLoaded(GameScenes scene)
{
fps.Reset();
base_fps.Reset();
level_loaded = true;
}
void onGameSceneLoad(GameScenes scene) => level_loaded = false;
public static Task AddTask(IEnumerator task)
{
var t = new Task { iter = task };
Instance.tasks.Add(t);
return t;
}
void Update()
{
if(!level_loaded || Time.timeSinceLevelLoad < 1) return;
var now = DateTime.Now;
if(fps.Value.Equals(0))
{
fps.Set(1 / Time.unscaledDeltaTime);
base_fps.Set(fps);
}
else
{
fps.Update(1 / Time.unscaledDeltaTime);
base_fps.Update(fps);
}
if(tasks.Count > 0)
{
var dt = Time.unscaledDeltaTime / 100;
duration = fps >= base_fps ?
Utils.ClampH(duration + dt, Time.unscaledDeltaTime / 2) :
Utils.ClampL(duration - dt, Time.unscaledDeltaTime / 10);
//var i = 0;
var next = now.AddSeconds(duration);
while(now < next && tasks.Count > 0)
{
var task = tasks[current];
try
{
if(!task.iter.MoveNext())
{
task.finished = true;
tasks.RemoveAt(current);
}
else current = (current + 1) % tasks.Count;
}
catch(Exception e)
{
task.finished = true;
task.error = true;
tasks.RemoveAt(current);
Debug.Log(e);
}
now = DateTime.Now;
//i++;
}
//Utils.Log("tasks: {}, steps: {}, fps {} base {}",
//tasks.Count, i, fps.Value, base_fps.Value);//debug
}
}
}
} | c# | 19 | 0.461838 | 82 | 28.630769 | 130 | starcoderdata |
import Mesa from '@mesa/core';
import { Stack } from '@mesa/common';
import Method from './Method';
const debug = require('debug')('mesa-http:controller');
// const route = require('koa-path-match')()
// @path('/:id')
export class Controller extends Mesa.Component {
compose() {
return Method.methods.reduce((stack, method) => {
const { [method]: handler } = this.config;
if (!handler) {
return stack;
}
const wrapper = ctx => handler.call(this, ctx);
return stack.use(Method.spec({ method }).use(wrapper));
}, Stack.spec());
// const controller = this.config.controller || this
// const path = this.constructor.PATH || this.config.path || '/'
// const router = route(path)
// const handledMethods = []
// methods.forEach((method) => {
// const handler = controller[method]
// if (handler) {
// if (typeof (handler) !== 'function') {
// throw new Error(`Expected controller.${method} to be a function`)
// }
// handledMethods.push(method)
// router[method]((ctx) => {
// const res = handler.call(controller, ctx)
// if (res !== undefined) {
// if (ctx.body !== undefined) {
// debug('Unexpected return value when ctx.body is already set')
// }
// ctx.body = res
// }
// })
// }
// })
// debug(`[${handledMethods}] ${path}`)
// return router
}
}
export default Controller; | javascript | 19 | 0.548708 | 78 | 29.18 | 50 | starcoderdata |
namespace BuckarooSdk.Services.CreditManagement.DataRequest
{
///
/// For this data request type are no response parameters
///
public class CreditManagementAddOrUpdateDebtorResponse : ActionResponse
{
public override ServiceEnum ServiceEnum => ServiceEnum.CreditManagement;
}
} | c# | 8 | 0.821256 | 104 | 36.636364 | 11 | starcoderdata |
def _reset(self, user_hook_dirs):
"""
Reset for another set of scripts. This is primary required for running the test-suite.
"""
self._top_script_node = None
self._additional_files_cache = AdditionalFilesCache()
# Command line, Entry Point, and then builtin hook dirs.
self._user_hook_dirs = [*user_hook_dirs, os.path.join(PACKAGEPATH, 'hooks')]
# Hook-specific lookup tables. These need to reset when reusing cached PyiModuleGraph to avoid hooks to refer to
# files or data from another test-case.
logger.info('Caching module graph hooks...')
self._hooks = self._cache_hooks("")
self._hooks_pre_safe_import_module = self._cache_hooks('pre_safe_import_module')
self._hooks_pre_find_module_path = self._cache_hooks('pre_find_module_path')
# Search for run-time hooks in all hook directories.
self._available_rthooks = defaultdict(list)
for uhd in self._user_hook_dirs:
uhd_path = os.path.abspath(os.path.join(uhd, 'rthooks.dat'))
try:
with open(uhd_path, 'r', encoding='utf-8') as f:
rthooks = ast.literal_eval(f.read())
except FileNotFoundError:
# Ignore if this hook path doesn't have run-time hooks.
continue
except Exception as e:
logger.error('Unable to read run-time hooks from %r: %s' % (uhd_path, e))
continue
self._merge_rthooks(rthooks, uhd, uhd_path)
# Convert back to a standard dict.
self._available_rthooks = dict(self._available_rthooks) | python | 15 | 0.606755 | 120 | 49.272727 | 33 | inline |
function header_change(){
if ($(window).scrollTop() < 40){
$('header').removeClass("small_header");
}
else{
$('header').addClass("small_header");
}
}
$(document).ready(function() {
header_change();
$(window).scroll(function() {
header_change();
});
$('.top_menu .dropdown-toggle').removeAttr('data-toggle');
$('.mobile_menu').click(function () {
$('.top_menu').toggleClass('active');
$('body').toggleClass('noscroll');
$('.mobile_menu').toggle();
});
$('.top_menu').click(function () {
$('.top_menu').toggleClass('active');
$('body').toggleClass('noscroll');
$('.mobile_menu').toggle();
});
}); | javascript | 17 | 0.516713 | 62 | 23.793103 | 29 | starcoderdata |
import numpy as np
N, C = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
mod = 10**9+7
P = np.empty((404, 404), dtype=np.int64)
P[0, :] = 1
ar = np.arange(404, dtype=np.int64)
for i in range(1, 404):
P[i] = P[i-1] * ar % mod
# この時点で # P[i, c] = i**c % mod
P = P.cumsum(axis=1, dtype=np.int64) % mod # P[i, c] = Σ_{k=0}^i k**c % mod
P = P.T
dp = np.zeros(C+1, dtype=np.int64)
dp[0] = 1
for a, b in zip(A, B):
dp_new = np.zeros(C+1, dtype=np.int64)
p = (P[b] - P[a-1]) % mod
for c in range(C+1):
dp_new[c] = (dp[:c+1] * p[c::-1] % mod).sum()
dp = dp_new % mod
print(dp[C])
| python | 15 | 0.521407 | 76 | 26.25 | 24 | codenet |
vector<double> SinglePEWaveForm(double area, double t0) override {
vector<double> PEperBin;
double threshold = PULSEHEIGHT; // photo-electrons
double sigma = PULSE_WIDTH; // ns
area *= 10. * (1. + threshold);
double amplitude = area / (sigma * sqrt(2. * M_PI)),
signal; // assumes perfect Gaussian
double tStep1 = SAMPLE_SIZE / 1e2; // ns, make sure much smaller than
// sample size; used to generate MC-true
// pulses essentially
double tStep2 =
SAMPLE_SIZE; // ns; 1 over digitization rate, 100 MHz assumed here
double time = -5. * sigma;
bool digitizeMe = false;
while (true) {
signal = amplitude * exp(-pow(time, 2.) / (2. * sigma * sigma));
if (signal < threshold) {
if (digitizeMe)
break;
else
; // do nothing - goes down to advancing time block
} else {
if (digitizeMe)
PEperBin.push_back(signal);
else {
if (RandomGen::rndm()->rand_uniform() < 2. * (tStep1 / tStep2)) {
PEperBin.push_back(time + t0);
PEperBin.push_back(signal);
digitizeMe = true;
} else {
}
}
}
if (digitizeMe)
time += tStep2;
else
time += tStep1;
if (time > 5. * sigma) break;
}
return PEperBin;
} | c++ | 18 | 0.454713 | 85 | 35.909091 | 44 | inline |
using System;
using RP_Server_Scripts.ReusedClasses;
using RP_Server_Scripts.Visuals;
using RP_Server_Scripts.VobSystem.Definitions;
namespace RP_Server_Scripts.Definitions
{
class OrcDefBuilder:IDefBuilder
{
private readonly IBaseDefFactory _BaseDefFactory;
private readonly IVobDefRegistration _Registration;
public OrcDefBuilder(IBaseDefFactory baseDefFactory, IVobDefRegistration registration)
{
_BaseDefFactory = baseDefFactory ?? throw new ArgumentNullException(nameof(baseDefFactory));
_Registration = registration ?? throw new ArgumentNullException(nameof(registration));
}
public void BuildDefinition()
{
ModelDef m = new ModelDef("orc", "orc.mds");
m.SetAniCatalog(new NPCCatalog());
#region Draw
// Draw 2h
ScriptAniJob aniJob1 = new ScriptAniJob("draw2h_part0", "t_Run_2_2h");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 5) { { SpecialFrame.Draw, 5 } });
ScriptAniJob aniJob2 = new ScriptAniJob("draw2h_part1", "s_2h");
m.AddAniJob(aniJob2);
aniJob2.SetDefaultAni(new ScriptAni(0, 1));
aniJob1.NextAni = aniJob2;
ScriptAniJob aniJob3 = new ScriptAniJob("draw2h_part2", "t_2h_2_2hRun");
m.AddAniJob(aniJob3);
aniJob3.SetDefaultAni(new ScriptAni(0, 12));
aniJob2.NextAni = aniJob3;
// Draw 2h running
ScriptAniJob aniJob = new ScriptAniJob("draw2h_running", "t_Move_2_2hMove", new ScriptAni(0, 20));
aniJob.Layer = 2;
aniJob.DefaultAni.SetSpecialFrame(SpecialFrame.Draw, 7);
m.AddAniJob(aniJob);
// Undraw 2h
aniJob1 = new ScriptAniJob("undraw2h_part0", "t_2hRun_2_2h");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 12) { { SpecialFrame.Draw, 12 } });
aniJob2 = new ScriptAniJob("undraw2h_part1", "s_2h");
m.AddAniJob(aniJob2);
aniJob2.SetDefaultAni(new ScriptAni(0, 1));
aniJob1.NextAni = aniJob2;
aniJob3 = new ScriptAniJob("undraw2h_part2", "t_2h_2_Run");
m.AddAniJob(aniJob3);
aniJob3.SetDefaultAni(new ScriptAni(0, 5));
aniJob2.NextAni = aniJob3;
// Undraw 2h running
aniJob = new ScriptAniJob("undraw2h_running", "t_2hMove_2_Move", new ScriptAni(0, 20));
aniJob.Layer = 2;
aniJob.DefaultAni.SetSpecialFrame(SpecialFrame.Draw, 13);
m.AddAniJob(aniJob);
#endregion
#region Fighting
// Fwd attack 1
ScriptAniJob job = new ScriptAniJob("2hattack_fwd0", "s_2hattack");
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(0, 24) { { SpecialFrame.Hit, 6 }, { SpecialFrame.Combo, 11 } });
// fwd combo 2
job = new ScriptAniJob("2hattack_fwd1", "s_2hattack");
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(25, 70) { { SpecialFrame.Hit, 20 } });
// left attack
job = new ScriptAniJob("2hattack_left", "t_2hAttackL");
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(0, 24) { { SpecialFrame.Hit, 3 }, { SpecialFrame.Combo, 8 } });
// right attack
job = new ScriptAniJob("2hattack_right", "t_2hAttackR");
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(0, 24) { { SpecialFrame.Hit, 3 }, { SpecialFrame.Combo, 8 } });
// run attack
job = new ScriptAniJob("2hattack_run", "t_2hAttackMove");
job.Layer = 2;
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(0, 19) { { SpecialFrame.Hit, 13 } });
// parades
job = new ScriptAniJob("2h_parade0", "t_2hParade_0");
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(0, 30));
// dodge
job = new ScriptAniJob("2h_dodge", "t_2hParadeJumpB");
m.AddAniJob(job);
job.SetDefaultAni(new ScriptAni(0, 14));
#endregion
#region XBow anis
#region Draw
aniJob1 = new ScriptAniJob("drawXbow_part0", "t_Run_2_Cbow");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 4) { { SpecialFrame.Draw, 4 } });
aniJob2 = new ScriptAniJob("drawXbow_part1", "s_Cbow");
m.AddAniJob(aniJob2);
aniJob2.SetDefaultAni(new ScriptAni(0, 1));
aniJob1.NextAni = aniJob2;
aniJob3 = new ScriptAniJob("drawXbow_part2", "t_Cbow_2_CbowRun");
m.AddAniJob(aniJob3);
aniJob3.SetDefaultAni(new ScriptAni(0, 34));
aniJob2.NextAni = aniJob3;
aniJob = new ScriptAniJob("drawXbow_running", "t_Move_2_CBowMove", new ScriptAni(0, 20));
aniJob.Layer = 2;
aniJob.DefaultAni.SetSpecialFrame(SpecialFrame.Draw, 7);
m.AddAniJob(aniJob);
aniJob1 = new ScriptAniJob("undrawXbow_part0", "t_CBowRun_2_CBow");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 34) { { SpecialFrame.Draw, 34 } });
aniJob2 = new ScriptAniJob("undrawXbow_part1", "s_CBow");
m.AddAniJob(aniJob2);
aniJob2.SetDefaultAni(new ScriptAni(0, 1));
aniJob1.NextAni = aniJob2;
aniJob3 = new ScriptAniJob("undrawXbow_part2", "t_Cbow_2_Run");
m.AddAniJob(aniJob3);
aniJob3.SetDefaultAni(new ScriptAni(0, 4));
aniJob2.NextAni = aniJob3;
aniJob = new ScriptAniJob("undrawXbow_running", "t_CBowMove_2_Move", new ScriptAni(0, 20));
aniJob.Layer = 2;
aniJob.DefaultAni.SetSpecialFrame(SpecialFrame.Draw, 14);
m.AddAniJob(aniJob);
#endregion
#region Fight
aniJob1 = new ScriptAniJob("aim_xbow", "t_cbowwalk_2_cbowaim");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 11));
aniJob2 = new ScriptAniJob("aiming_xbow", "s_CBowAim");
m.AddAniJob(aniJob2);
aniJob2.SetDefaultAni(new ScriptAni());
aniJob1.NextAni = aniJob2;
// fixme: add s_bowshoot too?
aniJob1 = new ScriptAniJob("reload_xbow", "t_CBowReload");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 20));
aniJob1.NextAni = aniJob2;
aniJob1 = new ScriptAniJob("unaim_xbow", "t_CBowAim_2_CBowwalk");
m.AddAniJob(aniJob1);
aniJob1.SetDefaultAni(new ScriptAni(0, 11));
#endregion
#endregion
#region Jump Anis
m.AddAniJob(new ScriptAniJob("jump_fwd", "t_Stand_2_Jump"));
m.AddAniJob(new ScriptAniJob("jump_run", "t_RunL_2_Jump"));
#endregion
#region Climb Anis
var ani1 = new ScriptAniJob("climb_low", "t_Stand_2_JumpUpLow", new ScriptAni(0, 10));
var ani2 = new ScriptAniJob("climb_low1", "s_JumpUpLow", new ScriptAni(0, 4));
var ani3 = new ScriptAniJob("climb_low2", "t_JumpUpLow_2_Stand", new ScriptAni(0, 15));
m.AddAniJob(ani1);
m.AddAniJob(ani2);
m.AddAniJob(ani3);
ani1.NextAni = ani2;
ani2.NextAni = ani3;
ani1 = new ScriptAniJob("climb_mid", "t_Stand_2_JumpUpMid", new ScriptAni(0, 10));
ani2 = new ScriptAniJob("climb_mid1", "s_JumpUpMid", new ScriptAni(0, 2));
ani3 = new ScriptAniJob("climb_mid2", "t_JumpUpMid_2_Stand", new ScriptAni(0, 23));
m.AddAniJob(ani1);
m.AddAniJob(ani2);
m.AddAniJob(ani3);
ani1.NextAni = ani2;
ani2.NextAni = ani3;
ani1 = new ScriptAniJob("climb_high", "t_Stand_2_JumpUp", new ScriptAni(0, 9));
ani2 = new ScriptAniJob("climb_high1", "t_JumpUp_2_Hang", new ScriptAni(0, 2));
ani3 = new ScriptAniJob("climb_high2", "t_Hang_2_Stand", new ScriptAni(0, 40));
m.AddAniJob(ani1);
m.AddAniJob(ani2);
m.AddAniJob(ani3);
ani1.NextAni = ani2;
ani2.NextAni = ani3;
#endregion
m.Radius = 80;
m.HalfHeight = 100;
m.CenterOffset = 20;
m.Create();
// NPCs
NpcDef npcDef = new NpcDef("orc_scout",_BaseDefFactory,_Registration);
npcDef.Name = "Ork-Späher";
npcDef.Model = m;
npcDef.BodyMesh = "Orc_BodyWarrior";
npcDef.BodyTex = 0;
npcDef.HeadMesh = "Orc_HeadWarrior";
npcDef.HeadTex = 0;
npcDef.Guild = 59;
npcDef.Create();
// NPCs
npcDef = new NpcDef("orc_warrior",_BaseDefFactory,_Registration);
npcDef.Name = "Ork-Krieger";
npcDef.Model = m;
npcDef.BodyMesh = "Orc_BodyWarrior";
npcDef.BodyTex = 0;
npcDef.HeadMesh = "Orc_HeadWarrior";
npcDef.HeadTex = 0;
npcDef.Guild = 59;
npcDef.Create();
npcDef = new NpcDef("orc_elite",_BaseDefFactory,_Registration);
npcDef.Name = "Ork-Elite";
npcDef.Model = m;
npcDef.BodyMesh = "Orc_BodyElite";
npcDef.BodyTex = 0;
npcDef.HeadMesh = "Orc_HeadWarrior";
npcDef.HeadTex = 0;
npcDef.Guild = 59;
npcDef.Create();
npcDef = new NpcDef("orc_oberst",_BaseDefFactory,_Registration);
npcDef.Name = "
npcDef.Model = m;
npcDef.BodyMesh = "Orc_BodyElite";
npcDef.BodyTex = 0;
npcDef.HeadMesh = "Orc_HeadWarrior";
npcDef.HeadTex = 0;
npcDef.Guild = 59;
npcDef.Create();
}
}
} | c# | 17 | 0.556514 | 110 | 36.080882 | 272 | starcoderdata |
void ddenlovr_state::hginga_blitter_w(offs_t offset, uint8_t data)
{
if (offset == 0)
{
m_ddenlovr_blit_latch = data;
}
else
{
switch (m_ddenlovr_blit_latch & 0x3f)
{
case 0x00:
switch (data & 0xf)
{
case 0x03:
case 0x06:
case 0x0a:
data = data & ~2; // do not mirror writes of other layers to layer 1? (see code at 38d)
break;
}
break;
case 0x24:
if (data == 0x1b)
data = 0x13; // vertical lines -> horizontal lines (see numbers drawn on cards on "first chance")
break;
}
}
blitter_w(0, offset, data);
} | c++ | 16 | 0.57479 | 113 | 19.551724 | 29 | inline |
// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone \
// RUN: -triple %itanium_abi_triple %s -o - | FileCheck %s
// Debug info for a global constant whose address is taken should be emitted
// exactly once.
// CHECK: @i = internal constant i32 1, align 4, !dbg ![[I:[0-9]+]]
// CHECK: ![[I]] = !DIGlobalVariableExpression(var: ![[VAR:.*]], expr: !DIExpression(DW_OP_constu, 1, DW_OP_stack_value))
// CHECK: ![[VAR]] = distinct !DIGlobalVariable(name: "i",
// CHECK: !DICompileUnit({{.*}}globals: ![[GLOBALS:[0-9]+]]
// CHECK: ![[GLOBALS]] = !{![[I]]}
static const int i = 1;
void g(const int *, int);
void f() {
g(&i, i);
}
| c | 7 | 0.6125 | 121 | 36.647059 | 17 | research_code |
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using log4net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Proverb.Data.Models;
using Proverb.Services.Interfaces;
using Proverb.Web.Controllers;
using Proverb.Web.Helpers;
namespace Proverb.Web.Tests.ASPNet.Controllers
{
[TestClass]
public class SayingControllerTests
{
private const string CATEGORY = "Proverb.Web -> SayingController";
private Mock _sayingServiceMock;
private Mock _userHelperMock;
private Mock _loggerMock;
private SayingController _controller;
[TestInitialize]
public void Initialise()
{
_sayingServiceMock = new Mock
_userHelperMock = new Mock
_loggerMock = new Mock
_controller = new SayingController(_sayingServiceMock.Object, _userHelperMock.Object, _loggerMock.Object);
}
[TestMethod, TestCategory(CATEGORY)]
public async Task Get_returns_an_Ok_with_an_ICollection_of_Saying()
{
var sayings = new List
new Saying{ Id = 1, Text = "Pithy comment", SageId = 2 }
};
_sayingServiceMock
.Setup(x => x.GetAllAsync())
.ReturnsAsync(sayings);
IHttpActionResult result = await _controller.Get();
var ok = result as OkNegotiatedContentResult
Assert.IsNotNull(ok);
Assert.AreSame(sayings, ok.Content);
_sayingServiceMock.Verify(x => x.GetAllAsync());
}
/*
private void Index_setup()
{
_sayingServiceMock
.Setup(x => x.GetAll())
.Returns(new List
}
[TestMethod]
public void Index_gets_Proverbs_from_repository()
{
Index_setup();
ViewResult result = _controller.Index();
_sayingServiceMock
.Verify(x => x.GetAll(), Times.Once);
}
[TestMethod]
public void Index_returns_Proverbs_as_model()
{
Index_setup();
ViewResult result = _controller.Index();
Assert.IsInstanceOfType(result.Model, typeof(ICollection
}
*/
}
} | c# | 17 | 0.600872 | 118 | 28.337209 | 86 | starcoderdata |
/*
Copyright 2018 codestation
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 services
import (
"fmt"
)
// ConsulConfig has the config options for the ConsulConfig service
type ConsulConfig struct {
SaveDir string
}
// ConsulAppPath points to the consul binary location
var ConsulAppPath = "/bin/consul"
// Backup generates a tarball of the consul database and returns the path where is stored
func (c *ConsulConfig) Backup() (string, error) {
filepath := generateFilename(c.SaveDir, "consul-backup") + ".snap"
args := []string{"snapshot", "save", filepath}
app := CmdConfig{}
if err := app.CmdRun(ConsulAppPath, args...); err != nil {
return "", fmt.Errorf("couldn't execute %s, %v", ConsulAppPath, err)
}
return filepath, nil
}
// Restore takes a GiteaConfig backup and restores it to the service
func (c *ConsulConfig) Restore(filepath string) error {
args := []string{"snapshot", "restore", filepath}
app := CmdConfig{}
if err := app.CmdRun(ConsulAppPath, args...); err != nil {
return fmt.Errorf("couldn't execute consul restore, %v", err)
}
return nil
} | go | 10 | 0.735112 | 89 | 27.280702 | 57 | starcoderdata |
@Test
public void addDays() throws Exception {
Date actualDate = df.parse("20/11/2016 20:00:00");
Date newDate, resultDate;
// Add one day
newDate = df.parse("21/11/2016 20:00:00");
resultDate = DateTimeUtils.addDays(actualDate, 1);
assertTrue(newDate.equals(resultDate));
} | java | 8 | 0.600592 | 58 | 35.777778 | 9 | inline |
package kscjson
import (
"github.com/aws/aws-sdk-go/aws/request"
"github.com/KscSDK/ksc-sdk-go/ksc/kscquery"
)
type xmlErrorResponse struct {
Error Error `json:"Error"`
RequestID string `json:"RequestID"`
}
type Error struct {
Code string `json:"Code"`
Message string `json:"Message"`
}
// UnmarshalErrorHandler is a name request handler to unmarshal request errors
var UnmarshalErrorHandler = request.NamedHandler{Name: "kscsdk.query.UnmarshalError", Fn: UnmarshalError}
// UnmarshalError unmarshals an error response for an AWS Query service.
func UnmarshalError(r *request.Request) {
kscquery.UnmarshalError(r)
} | go | 9 | 0.759434 | 105 | 25.5 | 24 | starcoderdata |
/* Flite_Plugin - for licensing and copyright see license.txt */
#include
#pragma once
#define FLITE_VOICE_RMS "cmu_us_rms"
#define FLITE_VOICE_SLT "cmu_us_slt"
/**
* @brief Flite Plugin Namespace
*/
namespace FlitePlugin
{
struct SPhenomeTiming
{
string sName;
float fStart;
float fEnd;
float fDuration;
float fWeight;
};
/**
* @brief plugin Flite concrete interface
*/
struct IPluginFlite
{
/**
* @brief Get Plugin base interface
*/
virtual PluginManager::IPluginBase* GetBase() = 0;
/**
* @brief Speak a text asynchronously
* @param sText Text to Speak
*/
virtual void AsyncSpeak( const char* sText, const char* sVoice = FLITE_VOICE_SLT, void* pStream = NULL ) = 0;
};
}; | c | 11 | 0.591232 | 117 | 20.125 | 40 | starcoderdata |
def raise_if_none(attrname, exception, message):
"Raise an exception if the instance attribute is None."
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if getattr(self, attrname) is None:
raise exception(message)
return func(self, *args, **kwargs)
return wrapper
return decorator | python | 13 | 0.611111 | 59 | 36.9 | 10 | inline |
func runAdmissionServer(flagset *pflag.FlagSet, admissionHooks ...apiserver.AdmissionHook) {
logs.InitLogs()
defer logs.FlushLogs()
if len(os.Getenv("GOMAXPROCS")) == 0 {
runtime.GOMAXPROCS(runtime.NumCPU())
}
stopCh := genericapiserver.SetupSignalHandler()
cmd := server.NewCommandStartAdmissionServer(os.Stdout, os.Stderr, stopCh, admissionHooks...)
cmd.Short = "Launch Quack Templating Server"
cmd.Long = "Launch Quack Templating Server"
// Add admission hook flags
cmd.PersistentFlags().AddFlagSet(flagset)
// Flags for glog
cmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)
// Fix glog printing "Error: logging before flag.Parse"
flag.CommandLine.Parse([]string{})
if err := cmd.Execute(); err != nil {
glog.Fatal(err)
}
} | go | 10 | 0.739418 | 94 | 28.115385 | 26 | inline |
using System;
using System.IO;
using System.Globalization;
namespace opc_stream
{
///
/// reads csv-file line-by-line for streaming (avoid placing entire file in memory, to get around x64 limits
/// This class is for csv-files where first line is date in a string and following lines are doubles.
///
class CsvLineReader
{
StreamReader streamReader;
string fileName;
string[] variableNames;
char separator;
string dateTimeFormat;
string timeStamp;
int currentLine;
public CsvLineReader(string fileName, char separator = ';', string dateTimeFormat = "yyyy-MM-dd HH:mm:ss")
{
this.fileName = fileName;
streamReader = new StreamReader(fileName);
this.separator = separator;
this.dateTimeFormat = dateTimeFormat;
variableNames = streamReader.ReadLine().Split(separator);
currentLine = 0;
}
public string[] GetVariableNames()
{
return variableNames;
}
//
///
/// after calling GetLine, this method can return a string with the time stamp as written in the csv-file
///
///
public string GetTimeStampAtLastLineRead()
{
return timeStamp;
}
///
/// If browsing to find a specific date, then this lightweight version of GetNextLine reads just the date
///
/// null if EOF find
public DateTime? GetNextDate()
{
currentLine++;
string[] lineStr = new string[0];
while (lineStr.Length == 0 && !streamReader.EndOfStream)
{
string currentLine = streamReader.ReadLine();
lineStr = currentLine.Split(separator);
lineStr = currentLine.Split(separator);
if (lineStr.Length > 0)
{
timeStamp = lineStr[0];
return DateTime.ParseExact(timeStamp, dateTimeFormat, CultureInfo.InvariantCulture);
}
}
return null;
}
public int GetCurrentLineNumber()
{
return currentLine;
}
///
/// Gets date and values for next line in csv, or empty date and null if EOF
///
///
public (DateTime, double[]) GetNextLine()
{
currentLine++;
string[] lineStr = new string[0];
while (lineStr.Length == 0 && !streamReader.EndOfStream)
{
double[] values = new double[variableNames.Length -1 ];
string currentLine = streamReader.ReadLine();
lineStr = currentLine.Split(separator);
if (lineStr.Length > 0)
{
// get date
timeStamp = lineStr[0];
DateTime date = DateTime.ParseExact(timeStamp, dateTimeFormat, CultureInfo.InvariantCulture);
// get values
for (int k = 1; k < lineStr.Length; k++)
{
if (lineStr[k].Length > 0)
RobustParseDouble(lineStr[k], out values[k-1]);
}
return (date, values);
}
}
return (new DateTime(), null);// should not happen unless EOF
}
///
/// Loading string data into a double value.
///
/// <param name="str">the string to be parsed
/// <param name="value">(output) is the value of the parsed double(if successfully parsed)
/// method returns true if succesful, otherwise it returns false.
static private bool RobustParseDouble(string str, out double value)
{
str = str.Replace(',', '.');
bool abletoParseVal = false;
if (Double.TryParse(str, System.Globalization.NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out value))
abletoParseVal = true;
else if (Double.TryParse(str, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out value))
abletoParseVal = true;
else if (Double.TryParse(str, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture,
out value))
abletoParseVal = true;
return abletoParseVal;
}
internal string GetFileName()
{
return fileName;
}
}
} | c# | 22 | 0.547278 | 145 | 34.926471 | 136 | starcoderdata |
using QSP.AviationTools;
using QSP.Common;
using QSP.MathTools;
using QSP.MathTools.Interpolation;
using QSP.MathTools.Tables;
using QSP.TOPerfCalculation.Airbus.DataClasses;
using System;
using System.Collections.Generic;
using System.Linq;
using static QSP.MathTools.Angles;
namespace QSP.TOPerfCalculation.Airbus
{
public static class Calculator
{
///
/// Error can be None, NoDataForSelectedFlaps, or RunwayTooShort.
///
/// <exception cref="RunwayTooShortException">
/// <exception cref="Exception">
public static TOReport TakeOffReport(AirbusPerfTable t, TOParameters p,
double tempIncrement = 1.0)
{
var d = TakeOffDistanceMeter(t, p);
var primary = new TOReportRow(p.OatCelsius, d, p.RwyLengthMeter - d);
if (primary.RwyRemainingMeter < 0) throw new RunwayTooShortException();
var rows = new List
double maxOat = 67;
for (double oat = p.OatCelsius + tempIncrement; oat <= maxOat; oat += tempIncrement)
{
try
{
var q = p.CloneWithOat(oat);
d = TakeOffDistanceMeter(t, q);
var remaining = q.RwyLengthMeter - d;
if (remaining < 0) break;
rows.Add(new TOReportRow(oat, d, remaining));
}
catch { }
}
return new TOReport(primary, rows);
}
///
/// Computes the required takeoff distance.
///
/// <exception cref="Exception">
public static double TakeOffDistanceMeter(AirbusPerfTable t, TOParameters p)
{
var tables = GetTables(t, p);
if (tables.Count == 0) throw new Exception("No data for selected flaps");
var pressAlt = ConversionTools.PressureAltitudeFt(p.RwyElevationFt, p.QNH);
var inverseTables = tables.Select(x => GetInverseTable(x, pressAlt, t, p));
var distancesFt = inverseTables.Select(x =>
x.ValueAt(p.WeightKg * 0.001 * Constants.KgLbRatio))
.ToArray();
var d = (distancesFt.Length == 1) ?
distancesFt[0] :
Interpolate1D.Interpolate(
tables.Select(x => x.IsaOffset).ToArray(),
distancesFt,
IsaOffset(p));
// The slope and wind correction is not exactly correct according to
// performance xml file comments. However, the table itsel is probably
// not that precise anyways.
return Constants.FtMeterRatio * (d - SlopeAndWindCorrectionFt(d, t, p));
}
// Use the length of first argument instead of the one in Parameters.
private static double SlopeAndWindCorrectionFt(double lengthFt,
AirbusPerfTable t, TOParameters p)
{
var windCorrectedFt = lengthFt + WindCorrectionFt(lengthFt, t, p);
return windCorrectedFt - lengthFt + SlopeCorrectionFt(t, p, windCorrectedFt);
}
private static double WindCorrectionFt(double lengthFt,
AirbusPerfTable t, TOParameters p)
{
var headwind = p.WindSpeedKnots *
Math.Cos(ToRadian(p.RwyHeading - p.WindHeading));
return (headwind >= 0 ?
t.HeadwindCorrectionTable.ValueAt(lengthFt) :
t.TailwindCorrectionTable.ValueAt(lengthFt)) * headwind;
}
private static double SlopeCorrectionFt(AirbusPerfTable t, TOParameters p,
double windCorrectedLengthFt)
{
var len = windCorrectedLengthFt;
var s = p.RwySlopePercent;
return (s >= 0 ?
t.UphillCorrectionTable.ValueAt(len) :
t.DownHillCorrectionTable.ValueAt(len)) * -s;
}
private static double BleedAirCorrection1000LB(AirbusPerfTable t, TOParameters p)
{
if (p.PacksOn) return t.PacksOnCorrection;
if (p.AntiIce == AntiIceOption.EngAndWing) return t.AllAICorrection;
if (p.AntiIce == AntiIceOption.Engine) return t.EngineAICorrection;
return 0.0;
}
private static double WetCorrection1000LB(double lengthFt,
AirbusPerfTable t, TOParameters p)
{
if (!p.SurfaceWet) return 0.0;
return t.WetCorrectionTable.ValueAt(lengthFt);
}
private static double IsaOffset(TOParameters p) =>
p.OatCelsius - ConversionTools.IsaTemp(p.RwyElevationFt);
// Returns best matching tables, returning list can have:
// 0 element if no matching flaps, or
// 1 element if only 1 table matches the flaps setting, or
// 2 elements if more than 1 table match the flaps, these two tables are
// the ones most suitable for ISA offset interpolation.
private static List GetTables(AirbusPerfTable t, TOParameters p)
{
var allFlaps = t.AvailableFlaps().ToList();
if (p.FlapsIndex >= allFlaps.Count) return new List
var flaps = allFlaps.ElementAt(p.FlapsIndex);
var sameFlaps = t.Tables.Where(x => x.Flaps == flaps).ToList();
if (sameFlaps.Count == 1) return sameFlaps;
var ordered = sameFlaps.OrderBy(x => x.IsaOffset).ToList();
var isaOffset = IsaOffset(p);
var skip = ordered.Where(x => isaOffset > x.IsaOffset).Count() - 1;
var actualSkip = Numbers.LimitToRange(skip, 0, ordered.Count - 2);
return ordered.Skip(actualSkip).Take(2).ToList();
}
private static double WetAndBleedAirCorrection1000LB(double lengthFt,
AirbusPerfTable t, TOParameters p) =>
WetCorrection1000LB(lengthFt, t, p) + BleedAirCorrection1000LB(t, p);
// The table is for limit weight. This method constructs a table of
// takeoff distance. (x: weight 1000 LB, f: runway length ft)
// Wet runway and bleed air corrections are applied here.
private static Table1D GetInverseTable(TableDataNode n, double pressAlt,
AirbusPerfTable t, TOParameters p)
{
var table = n.Table;
var len = table.y;
var weight = len.Select(i =>
table.ValueAt(pressAlt, i) - WetAndBleedAirCorrection1000LB(i, t, p));
return new Table1D(weight.ToArray(), len.ToArray());
}
}
} | c# | 23 | 0.598951 | 96 | 40.949686 | 159 | starcoderdata |
def compare_SI(a,b):
# Try to compare numerically by applying SI suffix
a_num = _to_numeric(a)
b_num = _to_numeric(b)
if (a_num is not None) and (b_num is not None):
result = a_num-b_num
#print("Numeric: {} < {}".format(a,b), (True if result < 0 else False ))
return result
# Fallback to default string sorting (alphabetical order)
if a == b:
return 0
result = (a < b)
#print("Fallback: {} < {}".format(a,b), result)
return -1 if result else 1 | python | 8 | 0.571705 | 80 | 26.210526 | 19 | inline |
#include "registers.h"
#include "general.h"
void DelayMs(unsigned int numLoops)
{
unsigned int lp;
unsigned int i;
for(lp=0; lp<numLoops; lp++)
for (i=0; i<=4000; i++) ;
}
// Generate a random-enough value based on the current system clock
unsigned int rand(unsigned int *seed)
{
*seed += NVIC_ST_CURRENT;
return NVIC_ST_CURRENT + *seed;
}
void beep(int ms)
{
TIMER0_CTL |= 0x1;
DelayMs(ms);
TIMER0_CTL &= ~0x1;
} | c | 6 | 0.674528 | 67 | 15.96 | 25 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace kSlovnik.Controls
{
public class MenuRenderer : ToolStripProfessionalRenderer
{
public MenuRenderer() : base(new MenuColorTable()) { }
}
public class MenuColorTable : ProfessionalColorTable
{
// Hover
public override Color MenuItemSelectedGradientBegin => Constants.Colors.MenuHoverColor;
public override Color MenuItemSelectedGradientEnd => Constants.Colors.MenuHoverColor;
public override Color MenuItemBorder => Color.Black;
// Select
public override Color MenuItemPressedGradientBegin => Constants.Colors.MenuHoverColor;
public override Color MenuItemPressedGradientMiddle => Constants.Colors.MenuHoverColor;
public override Color MenuItemPressedGradientEnd => Constants.Colors.MenuHoverColor;
/*public override Color ImageMarginGradientBegin => Constants.Colors.MenuHoverColor;
public override Color ImageMarginGradientMiddle => Constants.Colors.MenuHoverColor;
public override Color ImageMarginGradientEnd => Constants.Colors.MenuHoverColor;*/
public override Color ButtonPressedGradientBegin => Constants.Colors.MenuHoverColor;
public override Color ButtonPressedGradientEnd => Constants.Colors.MenuHoverColor;
public override Color ButtonPressedBorder => Color.Black;
public override Color ToolStripDropDownBackground => Color.Transparent;
// Other overridable fields
/*
public override Color ButtonCheckedGradientBegin => Color.Red;//base.ButtonCheckedGradientBegin;
public override Color ButtonCheckedGradientEnd => Color.Red;//base.ButtonCheckedGradientEnd;
public override Color ButtonCheckedGradientMiddle => Color.Red;//base.ButtonCheckedGradientMiddle;
public override Color ButtonCheckedHighlight => Color.Red;//base.ButtonCheckedHighlight;
public override Color ButtonCheckedHighlightBorder => Color.Red;//base.ButtonCheckedHighlightBorder;
public override Color ButtonPressedGradientMiddle => Color.Red;//base.ButtonPressedGradientMiddle;
public override Color ButtonPressedHighlight => Color.Red;// base.ButtonPressedHighlight;
public override Color ButtonPressedHighlightBorder => Color.Red;//base.ButtonPressedHighlightBorder;
public override Color ButtonSelectedBorder => Color.Red;//base.ButtonSelectedBorder;
public override Color ButtonSelectedGradientBegin => Color.Red;// base.ButtonSelectedGradientBegin;
public override Color ButtonSelectedGradientEnd => Color.Red;//base.ButtonSelectedGradientEnd;
public override Color ButtonSelectedGradientMiddle => Color.Red;//base.ButtonSelectedGradientMiddle;
public override Color ButtonSelectedHighlight => Color.Red;//base.ButtonSelectedHighlight;
public override Color ButtonSelectedHighlightBorder => Color.Red;// base.ButtonSelectedHighlightBorder;
public override Color CheckBackground => Color.Red;//base.CheckBackground;
public override Color CheckPressedBackground => Color.Red;// base.CheckPressedBackground;
public override Color CheckSelectedBackground => Color.Red;// base.CheckSelectedBackground;
public override Color GripDark => Color.Red;//base.GripDark;
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override Color GripLight => Color.Red;//base.GripLight;
public override Color ImageMarginRevealedGradientBegin => Color.Red;// base.ImageMarginRevealedGradientBegin;
public override Color ImageMarginRevealedGradientEnd => Color.Red;//base.ImageMarginRevealedGradientEnd;
public override Color ImageMarginRevealedGradientMiddle => Color.Red;// base.ImageMarginRevealedGradientMiddle;
public override Color MenuBorder => Color.Black;
public override Color MenuItemSelected => Color.Red;//base.MenuItemSelected;
public override Color MenuStripGradientBegin => Color.Red;//base.MenuStripGradientBegin;
public override Color MenuStripGradientEnd => Color.Red;// base.MenuStripGradientEnd;
public override Color OverflowButtonGradientBegin => Color.Red;//base.OverflowButtonGradientBegin;
public override Color OverflowButtonGradientEnd => Color.Red;//base.OverflowButtonGradientEnd;
public override Color OverflowButtonGradientMiddle => Color.Red;// base.OverflowButtonGradientMiddle;
public override Color RaftingContainerGradientBegin => Color.Red;// base.RaftingContainerGradientBegin;
public override Color RaftingContainerGradientEnd => Color.Red;//base.RaftingContainerGradientEnd;
public override Color StatusStripGradientBegin => Color.Red;// base.StatusStripGradientBegin;
public override Color StatusStripGradientEnd => Color.Red;//base.StatusStripGradientEnd;
public override Color ToolStripContentPanelGradientBegin => Color.Red;//base.ToolStripContentPanelGradientBegin;
public override Color ToolStripContentPanelGradientEnd => Color.Red;// base.ToolStripContentPanelGradientEnd;
public override Color ToolStripGradientBegin => Color.Red;//base.ToolStripGradientBegin;
public override Color ToolStripGradientEnd => Color.Red;//base.ToolStripGradientEnd;
public override Color ToolStripGradientMiddle => Color.Red;//base.ToolStripGradientMiddle;
public override Color ToolStripPanelGradientBegin => Color.Red;// base.ToolStripPanelGradientBegin;
public override Color ToolStripPanelGradientEnd => Color.Red;//base.ToolStripPanelGradientEnd;
public override string ToString()
{
return base.ToString();
}
public override Color SeparatorDark => base.SeparatorDark;
public override Color SeparatorLight => base.SeparatorLight;
public override Color ToolStripBorder => base.ToolStripBorder;
*/
}
} | c# | 11 | 0.754885 | 120 | 64.882979 | 94 | starcoderdata |
void populateStandardToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
RewritePatternSet &patterns) {
MLIRContext *context = patterns.getContext();
patterns.add<
// Unary and binary patterns
spirv::UnaryAndBinaryOpPattern<arith::MaxFOp, spirv::GLSLFMaxOp>,
spirv::UnaryAndBinaryOpPattern<arith::MaxSIOp, spirv::GLSLSMaxOp>,
spirv::UnaryAndBinaryOpPattern<arith::MaxUIOp, spirv::GLSLUMaxOp>,
spirv::UnaryAndBinaryOpPattern<arith::MinFOp, spirv::GLSLFMinOp>,
spirv::UnaryAndBinaryOpPattern<arith::MinSIOp, spirv::GLSLSMinOp>,
spirv::UnaryAndBinaryOpPattern<arith::MinUIOp, spirv::GLSLUMinOp>,
ReturnOpPattern, SelectOpPattern, SplatPattern, BranchOpPattern,
CondBranchOpPattern>(typeConverter, context);
} | c++ | 14 | 0.729089 | 72 | 49.125 | 16 | inline |
<?php
namespace App\Services;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class ValidatorService
{
private static $message;
public static $failed = false;
public static $data;
public static function validate($data, $schema, $messages = [])
{
$data = $data instanceof Request ? $data->all() : $data;
$validator = Validator::make($data, $schema, $messages);
if ($validator->fails()) {
self::$failed = true;
self::$message = $validator->errors()->first();
} else {
self::$data = json_decode(json_encode($data));
}
}
public static function error()
{
self::replaceAttributes();
return ResponseService::unprocessable(self::$message);
}
private static function replaceAttributes()
{
$validation = include(resource_path('/lang/en/validation.php'));
$attributes = collect($validation['attributes']);
$attributes->each(function($value, $key) {
$isReplasable = Str::contains(self::$message, $key);
self::$message = str_replace($key, $value, self::$message);
if ($isReplasable) return false;
});
}
} | php | 18 | 0.59858 | 72 | 27.840909 | 44 | starcoderdata |
pub fn _memcpy_impl(dst: &mut [u8], src: &[u8]) -> Result<(), RangeError> {
if src.is_empty() {
return Ok(());
}
#[cfg(target_arch = "arm")]
let r = {
// measures to prevent bus errors
#[cfg(target_pointer_width = "32")]
let r = _start_cpy_32_no_unroll(dst, src);
#[cfg(target_pointer_width = "16")]
let r = _start_cpy_1(dst, src);
//
r
};
#[cfg(not(target_arch = "arm"))]
let r = {
#[cfg(target_pointer_width = "128")]
let r = _start_cpy_128(dst, src);
#[cfg(target_pointer_width = "64")]
let r = _start_cpy_64(dst, src);
#[cfg(target_pointer_width = "32")]
let r = _start_cpy_32(dst, src);
#[cfg(target_pointer_width = "16")]
let r = _start_cpy_16(dst, src);
//
r
};
//
r
} | rust | 11 | 0.46915 | 75 | 27.666667 | 30 | inline |
function themeshow() {
document.getElementById('theme-opcion').style.display = "inline";
document.getElementById('mostrar').style.display = "none";
document.getElementById('ocultar').style.display = "inline";
}
function themehide() {
document.getElementById('theme-opcion').style.display = "none";
document.getElementById('mostrar').style.display = "inline";
document.getElementById('ocultar').style.display = "none";
}
function viewmenu() {
document.getElementById('menu-hidden').style.display = "flex";
document.getElementById('hide').style.display = "none";
document.getElementById('show').style.display = "inline";
}
function hidemenu() {
document.getElementById('menu-hidden').style.display = "none";
document.getElementById('hide').style.display = "inline";
document.getElementById('show').style.display = "none";
} | javascript | 11 | 0.708005 | 69 | 36 | 24 | starcoderdata |
from django.db.models import Count
from utils.views import ListAPIViewMixin
from .models import Post
from .serializers import PostSerializer
class ListPostsAPIViewMixin(ListAPIViewMixin):
queryset = Post.objects.all()
serializer_class = PostSerializer
def filter_queryset(self, queryset, kwargs):
return queryset.filter(body__icontains=kwargs["q"])
class ListPostsWithOrderingAPIViewMixin(ListPostsAPIViewMixin):
"""
This mixin allows order by list of posts by
likes or creation date(created_at)
"""
def filter_queryset(self, queryset, kwargs):
allowed_ordering_fields = ("likes", "createdAt")
ordering_field = kwargs.get("ordering", None)
if ordering_field:
sign = ""
if ordering_field.startswith("-"):
sign = "-"
ordering_field = ordering_field[1:]
if ordering_field in allowed_ordering_fields:
if ordering_field == "likes":
queryset = queryset.annotate(likes=Count("like"))
ordering_field = sign + ordering_field
elif ordering_field == "createdAt":
ordering_field = sign + "created_at"
queryset = queryset.order_by(ordering_field)
return super().filter_queryset(queryset, kwargs) | python | 19 | 0.626382 | 69 | 29.155556 | 45 | starcoderdata |
import React from 'react';
import { useStaticQuery, graphql } from 'gatsby';
import ReactHtmlParser from 'react-html-parser';
const SecondRow = () => {
const {
secondRow : {
nodes: [{ acf: secondRow }],
} ,
} = useStaticQuery(graphql`
query secondRowQuery {
secondRow: allWordpressAcfPages(filter: {wordpress_id: {eq: 21}}) {
nodes {
acf {
second_row {
anchor_link
content_block
first_block
row_title
second_block
sub_title
}
}
}
}
}
`);
return(
<div className="second-row">
<div className="container">
{secondRow.second_row.map((data, i) => (
<div className="main" key={i}>
<div id={data.anchor_link}>
<div className="row-title">
{ ReactHtmlParser(data.row_title) }
<div className="sub-title">
{ ReactHtmlParser(data.sub_title) }
<div className="col-sm-6">
WORK
{ ReactHtmlParser(data.first_block) }
<div className="col-sm-6">
{ ReactHtmlParser(data.second_block) }
<div className="col-sm-12">
{ ReactHtmlParser(data.content_block) }
))}
)
}
export default SecondRow; | javascript | 20 | 0.437982 | 75 | 18.159091 | 88 | starcoderdata |
"use strict";
exports.__esModule = true;
exports["default"] = void 0;
var CATEGORIES = ['alternative', 'chillout', 'classical', 'country', 'instrumental', 'jazz', 'lounge', 'piano', 'pop', 'rock', 'sport', 'talks'];
var _default = CATEGORIES;
exports["default"] = _default;
//# sourceMappingURL=categories.js.map | javascript | 3 | 0.67378 | 145 | 35.555556 | 9 | starcoderdata |
namespace Df.AuditLogging;
/// audit log entry.
public class Audit
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string GroupId { get; set; } = Guid.NewGuid().ToString();
/// type of action performed on the data, <see cref="AuditActions"/>
public string Action { get; set; } = string.Empty;
/// type of the data that the audit is created for
public string DataType { get; set; } = string.Empty;
/// of the data this audit is about
public string DataId { get; set; } = string.Empty;
/// sub ID can be provided if needed
public string DataSubId { get; set; } = string.Empty;
/// ID of the user who caused the audit
public string UserId { get; set; } = string.Empty;
/// name of the user who caused the audit
public string UserName { get; set; } = string.Empty;
/// of the audit in UTC
public DateTime TimestampUtc { get; set; } = DateTime.UtcNow;
/// a data field has been changed, provide the name of the field here
public string DataFieldName { get; set; } = string.Empty;
/// a data field has been changed, provide the field type here
public string DataFieldType { get; set; } = string.Empty;
/// a data field has been changed, provide the old value here
public string DataOldValue { get; set; } = string.Empty;
/// a data field has been changed, provide the new value here
public string DataNewValue { get; set; } = string.Empty;
/// was the source of the audit, ie. an application name
public string Source { get; set; } = string.Empty;
/// description of the audit
public string Message { get; set; } = string.Empty;
/// version of the changed data
public string Version { get; set; } = string.Empty;
/// detail level of the audit, a value between 0 and 100, the higher the more detailed
public int DetailLevel { get; set; }
/// ID to correlate between API calls (X-Correlation-ID)
public string CorrelationId { get; set; } = string.Empty;
} | c# | 9 | 0.675314 | 111 | 57.317073 | 41 | starcoderdata |
import { connect } from 'react-redux';
import addAddress from '../../actions/addAddress';
import updateAddress from '../../actions/updateAddress';
import { deleteUserAddresses } from '../../action-creators/addressBook';
import { isBusy, getUserAddressesCount, getValidationErrors } from '../../selectors/addressBook';
import { getConfig } from '../../selectors/config';
/**
* @param {Object} state state
* @return {{isFirstAddress: boolean, isBusy: boolean, config: UserConfig}}
*/
const mapStateToProps = state => ({
isFirstAddress: !getUserAddressesCount(state),
isBusy: isBusy(state),
config: getConfig(state),
validationErrors: getValidationErrors(state) || [],
});
/**
* @param {function} dispatch dispatch
* @return {{addAddress: function, updateAddress: function, deleteAddress: function}}
*/
const mapDispatchToProps = dispatch => ({
addAddress: address => dispatch(addAddress(address)),
updateAddress: address => dispatch(updateAddress(address)),
deleteAddress: addressId => dispatch(deleteUserAddresses([addressId])),
});
export default connect(mapStateToProps, mapDispatchToProps); | javascript | 13 | 0.732079 | 97 | 37.482759 | 29 | starcoderdata |
#include "common.h"
#include "platform/SystemSpecs.h"
namespace sp
{
namespace platform
{
SystemSpecs::SystemSpecs(HINSTANCE programHandle): m_programHandle(programHandle)
{
}
HINSTANCE SystemSpecs::GetProgramHandle() const
{
return m_programHandle;
}
}
} | c++ | 9 | 0.744615 | 83 | 17.111111 | 18 | starcoderdata |
private List<AbstractDomain> getAuthorizedDomain(
Set<AbstractDomain> domains, List<DomainAccessRule> rules) {
List<AbstractDomain> includes = new ArrayList<AbstractDomain>();
List<AbstractDomain> excludes = new ArrayList<AbstractDomain>();
for (AbstractDomain domain : domains) {
logger.debug("check:domain : " + domain.toString());
for (DomainAccessRule domainAccessRule : rules) {
logger.debug("check:domainAccessRule : "
+ domainAccessRule.getDomainAccessRuleType().toString());
if (domainAccessRule.getDomainAccessRuleType().equals(
DomainAccessRuleType.ALLOW_ALL)) {
// logger.debug("check:domainAccessRule : ALLOW_ALL");
// Allow domain without any check
if (!includes.contains(domain)
&& !excludes.contains(domain)) {
includes.add(domain);
}
// This rule should me the last one
break;
} else if (domainAccessRule.getDomainAccessRuleType().equals(
DomainAccessRuleType.DENY_ALL)) {
// logger.debug("check:domainAccessRule : DENY_ALL");
// Deny domain without any check
if (!excludes.contains(domain)) {
excludes.add(domain);
}
// This rule should me the last one
break;
} else if (domainAccessRule.getDomainAccessRuleType().equals(
DomainAccessRuleType.ALLOW)) {
// logger.debug("check:domainAccessRule : ALLOW");
// Allow domain
AllowDomain allowDomain = (AllowDomain) domainAccessRule;
if (allowDomain.getDomain().equals(domain)
&& !includes.contains(domain)) {
logger.debug(" ALLOW : " + domain.getUuid());
includes.add(domain);
}
} else if (domainAccessRule.getDomainAccessRuleType().equals(
DomainAccessRuleType.DENY)) {
// Deny domain
// logger.debug("check:domainAccessRule : DENY");
DenyDomain denyDomain = (DenyDomain) domainAccessRule;
if (denyDomain.getDomain().equals(domain)
&& !excludes.contains(domain)) {
logger.debug(" DENY : " + domain.getUuid());
excludes.add(domain);
} else {
includes.add(domain);
}
}
}
}
return includes;
} | java | 20 | 0.666036 | 66 | 33.112903 | 62 | inline |
/**
* Black Duck JIRA Plugin
*
* Copyright (C) 2020 Synopsys, Inc.
* https://www.synopsys.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.blackducksoftware.integration.jira.web.action;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.blackducksoftware.integration.jira.blackduck.BlackDuckAssignUtil;
import com.blackducksoftware.integration.jira.data.accessor.GlobalConfigurationAccessor;
import com.blackducksoftware.integration.jira.data.accessor.PluginErrorAccessor;
import com.blackducksoftware.integration.jira.web.model.BlackDuckProjectMapping;
import com.synopsys.integration.blackduck.api.generated.view.ProjectView;
import com.synopsys.integration.blackduck.api.generated.view.UserView;
import com.synopsys.integration.blackduck.service.BlackDuckService;
import com.synopsys.integration.exception.IntegrationException;
public class UserAssignThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final GlobalConfigurationAccessor globalConfigurationAccessor;
private final PluginErrorAccessor pluginErrorAccessor;
private transient boolean shouldTimeout;
public UserAssignThread(final String threadName, final GlobalConfigurationAccessor globalConfigurationAccessor, final PluginErrorAccessor pluginErrorAccessor) {
super(threadName);
this.globalConfigurationAccessor = globalConfigurationAccessor;
this.pluginErrorAccessor = pluginErrorAccessor;
}
@Override
public void run() {
logger.debug("Starting User Assignment thread");
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
shouldTimeout = true;
}
}, 600000);
final BlackDuckAssignUtil blackDuckAssignUtil = new BlackDuckAssignUtil();
try {
final Set blackDuckProjectMappings = blackDuckAssignUtil.getBlackDuckProjectMappings(globalConfigurationAccessor);
if (blackDuckProjectMappings.isEmpty()) {
return;
}
checkShouldInterruptOrTimeout();
final BlackDuckService blackDuckService = blackDuckAssignUtil.getBlackDuckService(globalConfigurationAccessor);
final List allProjects = blackDuckAssignUtil.getAllBDProjects(blackDuckService);
checkShouldInterruptOrTimeout();
final Set matchingProjects = blackDuckAssignUtil.getMatchingBDProjects(blackDuckProjectMappings, allProjects);
if (matchingProjects.isEmpty()) {
return;
}
checkShouldInterruptOrTimeout();
final UserView currentUser = blackDuckAssignUtil.getCurrentUser(blackDuckService);
checkShouldInterruptOrTimeout();
final Set nonAssignedProjects = blackDuckAssignUtil.getProjectsThatNeedAssigning(blackDuckService, currentUser, matchingProjects);
if (nonAssignedProjects.isEmpty()) {
return;
}
checkShouldInterruptOrTimeout();
blackDuckAssignUtil.assignUserToProjects(pluginErrorAccessor, blackDuckService, currentUser, nonAssignedProjects);
logger.debug("Completed User Assignment");
} catch (final IntegrationException e) {
logger.error("Could not assign the Black Duck user to the configured Black Duck projects. " + e.getMessage(), e);
pluginErrorAccessor.addBlackDuckError(e, "assignUserToBlackDuckProject");
} catch (final InterruptedException e) {
logger.warn("The user assignment thread was interrupted.");
Thread.currentThread().interrupt();
} catch (final TimeoutException e) {
logger.error("The user assignment thread timed out after 10 minutes.");
}
}
private void checkShouldInterruptOrTimeout() throws InterruptedException, TimeoutException {
if (!Thread.currentThread().isAlive() || Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
}
if (shouldTimeout) {
throw new TimeoutException();
}
}
} | java | 14 | 0.725948 | 164 | 44.9375 | 112 | starcoderdata |
import pytest
@pytest.fixture(scope='session')
def mongodb_collections():
return ['foo']
def test_mongodb_fixture(mongodb):
assert mongodb.get_aliases() == ('foo',)
def test_fixtures_loaded(mongodb):
assert mongodb.foo.find_one() == {'_id': 'foo'}
@pytest.mark.mongodb_collections('bar')
def test_mark_adds_collection_to_mongodb(mongodb):
assert set(mongodb.get_aliases()) == {'foo', 'bar'} | python | 10 | 0.677108 | 55 | 20.842105 | 19 | starcoderdata |
#include "mdSceneManager.h"
#include "Application.h"
#include "mdEntities.h"
#include "mdGuiManager.h"
#include "mdFonts.h"
#include "mdInput.h"
#include "mdCollision.h"
#include "mdMap.h"
#include "Player.h"
#include "mdProjectiles.h"
#include "mdParticleSystem.h"
#include "startScene.h"
#include "mainScene.h"
#include "combatScene.h"
#include "characterSelScene.h"
#include "settingsScene.h"
#include "stageSelScene.h"
mdSceneManager::mdSceneManager() {
//PROVISIONAL: Hardcoded
screen = { 0, 0, 1920, 1080 };
name = "SceneManager";
start_scene = new startScene(true);
main_scene = new mainScene(false);
settings_scene = new settingsScene(false);
char_sel_scene = new characterSelScene(false);
combat_scene = new combatScene(false);
stage_sel_scene = new stageSelScene(false);
scene_list.push_back(start_scene);
scene_list.push_back(main_scene);
scene_list.push_back(settings_scene);
scene_list.push_back(char_sel_scene);
scene_list.push_back(combat_scene);
scene_list.push_back(stage_sel_scene);
}
mdSceneManager::~mdSceneManager(){}
bool mdSceneManager::awake(const pugi::xml_node & md_config) {
return true;
}
bool mdSceneManager::start() {
bool ret = false;
for (int i = 0; i < 2; i++)
{
App->entities->createPlayer(i);
}
std::list scene_it = scene_list.begin();
scene* object = nullptr;
for (scene_it; scene_it != scene_list.end(); scene_it++)
{
object = *scene_it;
if (object->scene_active)
ret = object->start();
}
SDL_SetRenderDrawBlendMode(App->render->renderer, SDL_BLENDMODE_BLEND);
return ret;
}
bool mdSceneManager::update(float dt) {
bool ret = false;
std::list scene_it = scene_list.begin();
scene* object = nullptr;
for (scene_it; scene_it != scene_list.end(); scene_it++)
{
object = *scene_it;
if (object->scene_active)
ret = object->update(dt);
}
//---------------------------------------------------------------
startSwitch();
return ret;
}
bool mdSceneManager::changeScene(scene* scene_in, scene* scene_out) {
bool ret = false;
if (current_step == fade_step::NONE)
{
current_step = fade_step::FADE_TO_BLACK;
switch_timer.start();
to_enable = scene_in;
to_disable = scene_out;
ret = true;
}
return ret;
}
void mdSceneManager::startSwitch() {
float normalized = MIN(1.0f, switch_timer.readSec() / fadetime);
static iPoint temp_cam;
switch (current_step)
{
case fade_step::NONE:
break;
case fade_step::FADE_TO_BLACK:
if (switch_timer.readSec() >= fadetime)
{
to_disable->scene_active = false;
//SPECIAL CASES
if (to_disable->name == "Combat Scene")
{
if (to_enable->name == "Stage Selection Scene")
App->entities->show = false, App->entities->setStopped(false);
else if (!to_disable->rematching)
{
App->collision->cleanUp();
for (int i = 0; i < 2; i++)
{
App->entities->players[i]->removeCharacters();
}
}
}
//Resetting focus
App->entities->players[0]->focus = nullptr;
App->entities->players[1]->focus = nullptr;
App->gui->cleanUp();
App->render->cleanBlitQueue();
App->projectiles->cleanUp();
App->map->map_loaded = false;
to_enable->scene_active = true;
to_enable->start();
switch_timer.start();
current_step = fade_step::FADE_FROM_BLACK;
}
break;
case fade_step::FADE_FROM_BLACK:
normalized = 1.0f - normalized;
if (switch_timer.readSec() >= fadetime)
current_step = fade_step::NONE;
break;
default:
break;
}
if (current_step != fade_step::NONE) {
SDL_SetRenderDrawColor(App->render->renderer, 0, 0, 0, (Uint8)(normalized * 255.0f));
SDL_RenderFillRect(App->render->renderer, &screen); // Fade to black should happen over all the screen
}
} | c++ | 22 | 0.656716 | 104 | 21.60241 | 166 | starcoderdata |
from graphics import *
from Verb import *
def generateVerbs():
f = open("Verbs.csv", "r")
ERDict = {}
IRDict = {}
REDict = {}
iregDict = {}
verbList = []
for verb in f:
verb = verb.strip().split(",")
verbList.append(verb[0])
regular = verb[2]
if regular == "Regular":
verbInfin = verb[0]
if verbInfin[-2: ] == "er":
ERDict[verbInfin] = verb[1]
elif verbInfin[-2: ] == "ir":
IRDict[verb[0]] = verb[1]
else:
REDict[verb[0]] = verb[1]
else:
iregDict[verb[0]] = verb[1]
f.close
return verbList, ERDict, IRDict, REDict, iregDict
def present():
#win = GraphWin("Present Tense", 600, 400)
#win.setBackground("light green")
verbList, ERDict, IRDict, REDict, iregDict = generateVerbs()
for verb in verbList:
if verb in ERDict:
conjug = ERVerb(verb)
conList = conjug.getPresent()
generateScreen(conList, verb)
elif verb in IRDict:
con = IRVerb(verb)
elif verb in REDict:
con = REVerb(verb)
else:
pass
#ireegulars
"""
for verb in range(len(verbList)):
if verb in ERDict:
con = ERVerb(verb)
presentList.append(con.firstSing)
presentList.append(con.firstSing
elif verb in IRDict:
con = IRVerb(verb)
elif verb in REDict:
con = REVerb(verb)
"""
present() | python | 14 | 0.508615 | 64 | 24.688525 | 61 | starcoderdata |
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<meta charset="UTF-8">
visualizada
<form method="post" action="visualizacao.php">
for="font">Selecionar Fonte:
id="font" name="font">
<option value="Verdana">Verdana
<option value="Arial">Arial
<option value="Times New Roman">Times New Roman
for="size">Selecione Tamanho:
id="size" name="size">
<option value="10px">10px
<option value="12px">12px
<option value="16px">16px
<option value="20px">20px
for="color">Selecionar Cor:
id="color" name="color">
<option value="black">black
<option value="green">green
<option value="purple">purple
<option value="red">red
type="submit" name="enviar" value="Enviar"/>
checked="checked" type="checkbox" id="save_prefs" name="save_prefs"/>
<label for="save_prefs">Guarde estas preferências para a próxima vez que fizer login.
<?php
if (isset($_POST['enviar']) && isset($_POST['font']) == $_SESSION['font'] = $_POST['font'] && isset($_POST['size']) == $_SESSION['size'] = $_POST['size'] && isset($_POST['color']) == $_SESSION['color'] = $_POST['color']) {
$font = $_POST['font'];
$size = $_POST['size'];
$color = $_POST['color'];
echo '<p style="font-family: ' . $font . '; font-size: ' . $size . '; color: ' . $color . ';">Texto para exibir!
} else if (isset($_POST['save_prefs'])) {
setcookie('font', $_POST['font'], time() + 60);
setcookie('color', $_POST['color'], time() + 60);
setcookie('color', $_POST['color'], time() + 60);
echo $_COOKIE['font'];
}
function display_times($num){
echo " tem visto essa pagina" . $num . ' time(s).
}
// obiter o valor cookie e adicionar 1 para esse visitante
$num_times = 1;
if (isset($_COOKIE['num_times'])){
$num_times = $_COOKIE['num_times'] + 1;
}
// definir o valor de volta para o cookie para proxima vez
setcookie('num_times', $num_times, time() + 60);
?> | php | 16 | 0.450501 | 230 | 42.525641 | 78 | starcoderdata |
########################################################################################################################
# Module: tests/test_toy_scenarios.py
# Description: Tests for univariate and multivariate toy scenarios
#
# Web: https://github.com/SamDuffield/mocat
########################################################################################################################
import unittest
import jax.numpy as jnp
import numpy.testing as npt
from mocat.src.scenarios import toy_examples
class Test1DGaussian(unittest.TestCase):
scenario = toy_examples.Gaussian(1, prior_potential=lambda x, rk: 0.)
def test_basic(self):
npt.assert_equal(self.scenario.dim, 1)
npt.assert_equal(self.scenario.mean.shape, (1,))
npt.assert_equal(self.scenario.covariance.shape, (1, 1))
npt.assert_equal(self.scenario.precision_sqrt.shape, (1, 1))
def test_scalar_potential(self):
npt.assert_array_equal(self.scenario.potential(0.), 0.)
npt.assert_array_equal(self.scenario.potential(5.), 12.5)
def test_scalar_grad_potential(self):
npt.assert_array_equal(self.scenario.grad_potential(0.), 0.)
npt.assert_array_equal(self.scenario.grad_potential(5.), 5.)
def test_setcov(self):
self.scenario.covariance = jnp.array([[7.]])
npt.assert_array_almost_equal(self.scenario.precision_sqrt, 0.37796447)
class TestNDGaussian(unittest.TestCase):
scenario = toy_examples.Gaussian(10, prior_potential=lambda x, rk: 0.)
def test_basic(self):
npt.assert_equal(self.scenario.dim, 10)
npt.assert_equal(self.scenario.mean.shape, (10,))
npt.assert_equal(self.scenario.covariance.shape, (10, 10))
npt.assert_equal(self.scenario.precision_sqrt.shape, (10, 10))
def test_array_potential(self):
npt.assert_array_equal(self.scenario.potential(jnp.zeros(10)), 0.)
npt.assert_array_equal(self.scenario.potential(jnp.ones(10) * 3), 45.)
def test_array_grad_potential(self):
npt.assert_array_equal(self.scenario.grad_potential(jnp.zeros(10)), jnp.zeros(10))
npt.assert_array_equal(self.scenario.grad_potential(jnp.ones(10) * 3.), jnp.ones(10) * 3.)
class Test1DGaussianMixture(unittest.TestCase):
scenario = toy_examples.GaussianMixture(means=jnp.array([0, 1]), prior_potential=lambda x, rk: 0.)
def test_basic(self):
npt.assert_equal(self.scenario.dim, 1)
npt.assert_equal(self.scenario.means.shape, (2, 1))
npt.assert_equal(self.scenario.covariances.shape, (2, 1, 1))
npt.assert_equal(self.scenario.precisions.shape, (2, 1, 1))
npt.assert_equal(self.scenario.precision_sqrts.shape, (2, 1, 1))
npt.assert_equal(self.scenario.precision_dets.shape, (2,))
def test_scalar_potential(self):
npt.assert_array_equal(self.scenario.potential(0.), self.scenario.potential(1.))
npt.assert_array_almost_equal(self.scenario.potential(5.), 9.601038)
def test_scalar_grad_potential(self):
npt.assert_array_equal(self.scenario.grad_potential(0.), -self.scenario.grad_potential(1.))
npt.assert_array_almost_equal(self.scenario.grad_potential(5.), 4.010987)
def test_setcovs(self):
self.scenario.covariances = jnp.repeat(jnp.array([[7.]])[jnp.newaxis, :, :], 2, axis=0)
npt.assert_array_equal(self.scenario.precisions, jnp.repeat(jnp.array([[1 / 7.]])[jnp.newaxis, :, :], 2, axis=0))
npt.assert_array_almost_equal(self.scenario.precision_sqrts,
jnp.repeat(jnp.array([[0.37796447]])[jnp.newaxis, :, :], 2, axis=0))
class TestNDGaussianMixture(unittest.TestCase):
scenario = toy_examples.GaussianMixture(means=jnp.arange(15).reshape(5, 3), prior_potential=lambda x, rk: 0.)
def test_basic(self):
npt.assert_equal(self.scenario.dim, 3)
npt.assert_equal(self.scenario.means.shape, (5, 3))
npt.assert_equal(self.scenario.covariances.shape, (5, 3, 3))
npt.assert_equal(self.scenario.precisions.shape, (5, 3, 3))
npt.assert_equal(self.scenario.precision_sqrts.shape, (5, 3, 3))
npt.assert_equal(self.scenario.precision_dets.shape, (5,))
def test_array_potential(self):
npt.assert_array_almost_equal(self.scenario.potential(jnp.zeros(3)), 6.8662534)
npt.assert_array_almost_equal(self.scenario.potential(jnp.ones(3) * 2), 6.8552055)
def test_array_grad_potential(self):
npt.assert_array_almost_equal(self.scenario.grad_potential(jnp.zeros(3)), jnp.array([0., -1, -2]))
npt.assert_array_almost_equal(self.scenario.grad_potential(jnp.ones(3) * 2.), jnp.array([1.967039,
0.967039,
-0.032961]))
class Test1DDoubleWell(unittest.TestCase):
scenario = toy_examples.DoubleWell(1, prior_potential=lambda x, rk: 0.)
def test_basic(self):
npt.assert_equal(self.scenario.dim, 1)
def test_scalar_potential(self):
npt.assert_array_equal(self.scenario.potential(-3.), self.scenario.potential(3.))
npt.assert_array_equal(self.scenario.potential(0.), 0)
npt.assert_array_almost_equal(self.scenario.potential(5.), 143.75)
def test_scalar_grad_potential(self):
npt.assert_array_equal(self.scenario.grad_potential(-3.), -self.scenario.grad_potential(3.))
npt.assert_array_equal(self.scenario.grad_potential(0.), 0.)
npt.assert_array_equal(self.scenario.grad_potential(1.), 0.)
npt.assert_array_equal(self.scenario.grad_potential(-1.), 0.)
npt.assert_array_almost_equal(self.scenario.grad_potential(5.), 120.)
class TestNDDoubleWell(unittest.TestCase):
scenario = toy_examples.DoubleWell(6, prior_potential=lambda x, rk: 0.)
def test_basic(self):
npt.assert_equal(self.scenario.dim, 6)
def test_array_potential(self):
npt.assert_array_equal(self.scenario.potential(jnp.zeros(6)), 0.)
npt.assert_array_equal(self.scenario.potential(jnp.ones(3) * 2), 6.)
npt.assert_array_almost_equal(self.scenario.potential(jnp.arange(6)), 217.25)
def test_array_grad_potential(self):
npt.assert_array_equal(self.scenario.grad_potential(jnp.zeros(6)), jnp.zeros(6))
npt.assert_array_equal(self.scenario.grad_potential(jnp.ones(6)), jnp.zeros(6))
npt.assert_array_equal(self.scenario.grad_potential(-jnp.zeros(6)), jnp.zeros(6))
npt.assert_array_almost_equal(self.scenario.grad_potential(jnp.arange(6, dtype='float32')),
jnp.array([0., 0., 6., 24., 60., 120.]))
if __name__ == '__main__':
unittest.main() | python | 16 | 0.630846 | 121 | 44.172185 | 151 | starcoderdata |
def launch_training_job(search_range):
'''Launch training of the model with a set of hyperparameters in parent_dir/job_name
Args:
search_range: one combination of the params to search
'''
search_range = search_range[0]
params = {k: search_params[k][search_range[idx]] for idx, k in enumerate(sorted(search_params.keys()))}
model_param_list = '-'.join('_'.join((k, f'{v:.2f}')) for k, v in params.items())
model_param = copy(param_template)
for k, v in params.items():
setattr(model_param, k, v)
pool_id, job_idx = multiprocessing.Process()._identity
gpu_id = gpu_ids[pool_id - 1]
logger.info(f'Worker {pool_id} running {job_idx} using GPU {gpu_id}')
# Create a new folder in parent_dir with unique_name 'job_name'
model_name = os.path.join(model_dir, model_param_list)
model_input = os.path.join(args.model_name, model_param_list)
if not os.path.exists(model_name):
os.makedirs(model_name)
# Write parameters in json file
json_path = os.path.join(model_name, 'params.json')
model_param.save(json_path)
logger.info(f'Params saved to: {json_path}')
# Launch training with this config
cmd = f'{PYTHON} train.py ' \
f'--model-name={model_input} ' \
f'--dataset={args.dataset} ' \
f'--data-folder={args.data_dir} ' \
f'--save-best '
if args.sampling:
cmd += ' --sampling'
if args.relative_metrics:
cmd += ' --relative-metrics'
logger.info(cmd)
check_call(cmd, shell=True, env={'CUDA_VISIBLE_DEVICES': str(gpu_id),
'OMP_NUM_THREADS': '4'}) | python | 13 | 0.614918 | 107 | 37.372093 | 43 | inline |
#include <bits/stdc++.h>
#define FOR(i,b,e) for (common_type_t<decltype(b),decltype(e)> i = (b), i ## __end = (e); i < i ## __end; ++ i)
#define rep(i,n) FOR (i, size_t{}, n)
#define ALL(x) begin (x), end (x)
using namespace std;
using ll = int64_t;
constexpr ll inf = 2e18;
using vertex_t = size_t;
constexpr vertex_t invalid = ~ 0ull;
inline auto to_vertex (size_t i, size_t j)
{
if (i > j) swap (i, j);
return i * 1000 + j;
}
inline auto vertex_to_pair (vertex_t v)
{
return pair <size_t, size_t> (v / 1000, v % 1000);
}
template <typename Graph>
inline auto topological_sort (const Graph & graph, const set <vertex_t> & v)
{
//using vertex_t = size_t;
enum class flag_t : unsigned char { YET, VISITED, DONE };
auto n = graph.size ();
vector <flag_t> visited (n, flag_t::YET);
vector <vertex_t> res;
auto res_ite = back_inserter (res);
auto dfs = [&] (auto self, auto && from) {
if (visited[from] == flag_t::DONE) return;
if (visited[from] == flag_t::VISITED) throw runtime_error ("Error in topological_sort: The graph must be DAG.");
visited[from] = flag_t::VISITED;
for (auto && to : graph[from])
{
self (self, to);
}
* res_ite ++ = from;
visited[from] = flag_t::DONE;
};
for (auto && i : v) dfs (dfs, i);
reverse (ALL (res));
return res;
}
template <typename Graph, typename Iterator>
inline auto solve (const Graph & graph, Iterator first, Iterator last)
{
enum class flag_t : unsigned char { YET, VISITED, DONE };
auto n = graph.size ();
vector <flag_t> visited (n, flag_t::YET);
vector <vertex_t> memo (n);
ll res = 0;
auto dfs = [&] (auto self, auto && from) -> ll {
if (visited[from] == flag_t::DONE) return memo[from];
if (visited[from] == flag_t::VISITED) throw runtime_error ("Error in topological_sort: The graph must be DAG.");
visited[from] = flag_t::VISITED;
ll ans = 1;
for (auto && to : graph[from])
{
ans = max (ans, self (self, to) + 1);
}
visited[from] = flag_t::DONE;
return memo[from] = ans;
};
FOR (ite, first, last)
{
res = max (res, dfs (dfs, * ite));
}
return res;
}
auto main () -> int
{
cin.tie (nullptr);
ios::sync_with_stdio (false);
size_t n;
cin >> n;
vector <vector <size_t>> A (n);
vector <vector <vertex_t>> g (1000 * 1000 + 1);
rep (i, n)
{
auto pre_v = invalid;
rep (j ,n - 1)
{
size_t a;
cin >> a;
-- a;
A [i].push_back (a);
if (pre_v != invalid)
{
g [pre_v].push_back (to_vertex (i, a));
}
pre_v = to_vertex (i, a);
}
}
set <vertex_t> v;
rep (j, n) rep (i, j) v.insert (to_vertex (i, j));
try
{
vector <bool> battled (n);
auto sorted = topological_sort (g, v);
auto ans = solve (g, ALL (sorted));
/*
for (auto ite = begin (sorted); ite != end (sorted); )
{
size_t i, j;
tie (i, j) = vertex_to_pair (* ite);
if (battled [i] || battled [j]) {
++ ans;
fill (ALL (battled), false);
}
else
{
battled [i] = battled [j] = true;
++ ite;
}
}
if (any_of (ALL (battled), [&](auto && elem){return elem;})) ++ ans;
*/
#ifdef LOCAL
cerr << "debug:" << endl;
for (auto && elem : sorted)
{
size_t i, j;
tie (i, j) = vertex_to_pair (elem);
cout << "(" << i << ", " << j << ")" << endl;
}
#endif
cout << ans << endl;
}
catch (...)
{
cout << -1 << endl;
}
}
| c++ | 17 | 0.530811 | 116 | 23.570423 | 142 | codenet |
def dfs(board, i, j, word, visited):
if len(word) == 0: # hit base case
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited.get((i,j)) or word[0]!=board[i][j]:
return False
visited[(i,j)] = True
res = dfs(board, i, j+1, word[1:], visited) \
or dfs(board, i+1, j, word[1:], visited) \
or dfs(board, i-1, j, word[1:], visited) \
or dfs(board, i, j-1, word[1:], visited)
visited[(i,j)] = False
return res | python | 12 | 0.440336 | 117 | 48.666667 | 12 | inline |
package org.pa.boundless.bsp;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.commons.io.IOUtils;
import org.pa.boundless.bsp.raw.Brush;
import org.pa.boundless.bsp.raw.Brushside;
import org.pa.boundless.bsp.raw.BspFile;
import org.pa.boundless.bsp.raw.DirEntry;
import org.pa.boundless.bsp.raw.Effect;
import org.pa.boundless.bsp.raw.Face;
import org.pa.boundless.bsp.raw.Header;
import org.pa.boundless.bsp.raw.Leaf;
import org.pa.boundless.bsp.raw.Lightmap;
import org.pa.boundless.bsp.raw.Lightvol;
import org.pa.boundless.bsp.raw.Lump;
import org.pa.boundless.bsp.raw.Model;
import org.pa.boundless.bsp.raw.Node;
import org.pa.boundless.bsp.raw.Plane;
import org.pa.boundless.bsp.raw.Texture;
import org.pa.boundless.bsp.raw.Vertex;
import org.pa.boundless.bsp.raw.Visdata;
/**
* Loads raw BSP data from a stream. Produces a {@link BspFile}.
*
* @author palador
*/
public class BspLoader implements Callable {
/**
* Chunkreader used to read direntries.
*/
private static final ChunkReader DIRENTRY = new ChunkReader<>(
DirEntry.class);
/**
* Maps a lump to a suited chunk-reader. Works for lumps with fixed chunk
* length, only.
*/
private static final Map<Lump, ChunkReader LUMP_TO_CHUNKREADER;
static {
// init that map
HashMap<Lump, ChunkReader lumpToChunkreader = new HashMap<>();
for (Lump lump : Lump.lumpsWithFixedChunkLength()) {
lumpToChunkreader.put(lump, new ChunkReader<>(lump.getChunkType()));
}
LUMP_TO_CHUNKREADER = Collections.unmodifiableMap(lumpToChunkreader);
}
// The inputstream of your choice.
private InputStream is;
/**
* Sets the stream to read the BSP-data from.
*
* @param is
* the input-stream
* @return this
* @throws IllegalArgumentException
* if is
*/
public BspLoader setStream(InputStream is) throws IllegalArgumentException {
this.is = is;
return this;
}
/**
* Loads a BSP-file.
*
* @param is
* the input-stream to load the BSP from
* @return the BSP-file
* @throws IOException
* If an I/O-error occured.
* @throws IllegalStateException
* If the provided data is illegal or the loader-configuration
* is invalid or insufficient.
* @throws IllegalArgumentException
* If the provided data is illegal.
*/
public BspFile call() throws IOException, IllegalStateException,
IllegalArgumentException {
if (is == null) {
throw new IllegalStateException("no inputstream set");
}
// load whole file and put it into a little endian byte-buffer
ByteBuffer buf =
ByteBuffer.wrap(IOUtils.toByteArray(is)).order(
ByteOrder.LITTLE_ENDIAN);
// create result-object and load the header
BspFile bsp = new BspFile();
bsp.header = new Header();
bufGetText(buf, bsp.header.magic);
bsp.header.version = buf.getInt();
for (Lump lump : Lump.values()) {
bsp.header.direntries[lump.ordinal()] = DIRENTRY.loadChunk(buf);
}
// load fixed chunk-length lumps
for (Lump lump : Lump.values()) {
try {
// prepare buffer
DirEntry dirEntry = bsp.header.direntries[lump.ordinal()];
// note: length is specified in multiples of 4
buf.limit(dirEntry.offset + (dirEntry.length));
buf.position(dirEntry.offset);
if (Lump.lumpsWithFixedChunkLength().contains(lump)) {
ChunkReader chunkReader = LUMP_TO_CHUNKREADER.get(lump);
int chunkCount =
buf.remaining() / chunkReader.getChunkLength();
Object[] chunks = new Object[chunkCount];
for (int i = 0; i < chunkCount; i++) {
chunks[i] = chunkReader.loadChunk(buf);
}
// find and init target array
Object targetArray;
switch (lump) {
case BRUSHES:
bsp.brushes = new Brush[chunkCount];
targetArray = bsp.brushes;
break;
case BRUSHSIDES:
bsp.brushsides = new Brushside[chunkCount];
targetArray = bsp.brushsides;
break;
case EFFECTS:
bsp.effects = new Effect[chunkCount];
targetArray = bsp.effects;
break;
case FACES:
bsp.faces = new Face[chunkCount];
targetArray = bsp.faces;
break;
case LEAFS:
bsp.leafs = new Leaf[chunkCount];
targetArray = bsp.leafs;
break;
case LIGHTMAPS:
bsp.lightmaps = new Lightmap[chunkCount];
targetArray = bsp.lightmaps;
break;
case LIGHTVOLS:
bsp.lightvols = new Lightvol[chunkCount];
targetArray = bsp.lightvols;
break;
case MODELS:
bsp.models = new Model[chunkCount];
targetArray = bsp.models;
break;
case NODES:
bsp.nodes = new Node[chunkCount];
targetArray = bsp.nodes;
break;
case PLANES:
bsp.planes = new Plane[chunkCount];
targetArray = bsp.planes;
break;
case TEXTURES:
bsp.textures = new Texture[chunkCount];
targetArray = bsp.textures;
break;
case VERTEXES:
bsp.vertices = new Vertex[chunkCount];
targetArray = bsp.vertices;
break;
default:
throw new RuntimeException(
"Lump doesn't support automatic reading: "
+ lump);
}
// copy loaded data to target-array
System.arraycopy(chunks, 0, targetArray, 0, chunkCount);
} else {
// Load lump without fixed chunk-length
switch (lump) {
case ENTITIES:
bsp.entities = bufToText(buf);
break;
case LEAFBRUSHES:
bsp.leafbrushes = bufToIntArray(buf);
break;
case LEAFFACES:
bsp.leaffaces = bufToIntArray(buf);
break;
case MESHVERTS:
bsp.meshverts = bufToIntArray(buf);
break;
case VISDATA: {
Visdata visdata = new Visdata();
visdata.n_vecs = buf.getInt();
visdata.sz_vecs = buf.getInt();
visdata.vecs =
new byte[visdata.n_vecs * visdata.sz_vecs];
buf.get(visdata.vecs);
bsp.visdata = visdata;
break;
}
default:
throw new RuntimeException("unexpected lump: " + lump);
}
}
} catch (Exception e) {
throw new IllegalArgumentException(
"Invalid data: could not load lump " + lump, e);
}
}
return bsp;
}
private static char[] bufToText(ByteBuffer buf) {
char[] result = new char[buf.remaining()];
for (int i = 0; i < result.length; i++) {
result[i] = (char) buf.get();
}
return result;
}
private static void bufGetText(ByteBuffer buf, char[] dest) {
for (int i = 0; i < dest.length; i++) {
dest[i] = (char) buf.get();
}
}
private static int[] bufToIntArray(ByteBuffer buf) {
int[] result = new int[buf.remaining() / 4];
for (int i = 0; i < result.length; i++) {
result[i] = buf.getInt();
}
return result;
}
} | java | 21 | 0.654388 | 77 | 26.911647 | 249 | starcoderdata |
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author:
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail:
* Copyright (C): 2004-2012, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.prolog.test;
import junit.framework.TestCase;
import org.cs3.prolog.connector.Connector;
import org.cs3.prolog.connector.common.Debug;
import org.cs3.prolog.connector.process.PrologProcess;
import org.cs3.prolog.connector.process.PrologProcessException;
public class XpceTest extends TestCase {
public void testXpce() throws PrologProcessException {
Debug.setDebugLevel(Debug.LEVEL_DEBUG);
PrologProcess plInterface = Connector.newUninitializedPrologProcess();
plInterface.start();
try{
plInterface.getSession().queryOnce("help");
}catch(Exception pissnelke){
Debug.report(pissnelke);
fail();
}
}
public void _testDifferent() throws Throwable{
String home=System.getProperty("user.home");
Runtime.getRuntime().exec(new String[]{"/usr/X11R6/bin/xterm"},new String[]{"DISPLAY=:0.0","HOME="+home});
System.out.println("success");
}
} | java | 12 | 0.656746 | 108 | 31.869565 | 46 | starcoderdata |
namespace AbstractDemo.Lib
{
public interface IPurrable
{
void SoftPurr(int decibel);
}
} | c# | 8 | 0.619469 | 35 | 10.4 | 10 | starcoderdata |
void DestroySignal()
{
// If handle is now invalid wake any retained sleepers.
if (--refcount_ == 0) CasRelaxed(0, 0);
// Release signal, last release will destroy the object.
Release();
} | c | 7 | 0.587719 | 64 | 31.714286 | 7 | inline |
from typing import Text
from pyparsing import *
from odinson.ruleutils import config
from odinson.ruleutils.queryast import *
__all__ = [
"parse_odinson_query",
"parse_surface",
"parse_traversal",
]
# punctuation
comma = Literal(",").suppress()
equals = Literal("=").suppress()
vbar = Literal("|").suppress()
lt = Literal("<").suppress()
gt = Literal(">").suppress()
at = Literal("@").suppress()
ampersand = Literal("&").suppress()
open_curly = Literal("{").suppress()
close_curly = Literal("}").suppress()
open_parens = Literal("(").suppress()
close_parens = Literal(")").suppress()
open_bracket = Literal("[").suppress()
close_bracket = Literal("]").suppress()
# literal values
surface_hole = config.SURFACE_HOLE_GLYPH
traversal_hole = config.TRAVERSAL_HOLE_GLYPH
query_hole = config.QUERY_HOLE_GLYPH
number = Word(nums).setParseAction(lambda t: int(t[0]))
identifier = Word(alphas + "_", alphanums + "_")
single_quoted_string = QuotedString("'", unquoteResults=True, escChar="\\")
double_quoted_string = QuotedString('"', unquoteResults=True, escChar="\\")
quoted_string = single_quoted_string | double_quoted_string
string = identifier | quoted_string
# number to the left of the comma {n,}
quant_range_left = open_curly + number + comma + close_curly
quant_range_left.setParseAction(lambda t: (t[0], None))
# number to the right of the comma {,m}
quant_range_right = open_curly + comma + number + close_curly
quant_range_right.setParseAction(lambda t: (0, t[0]))
# numbers on both sides of the comma {n,m}
quant_range_both = open_curly + number + comma + number + close_curly
quant_range_both.setParseAction(lambda t: (t[0], t[1]))
# no number either side of the comma {,}
quant_range_neither = open_curly + comma + close_curly
quant_range_neither.setParseAction(lambda t: (0, None))
# range {n,m}
quant_range = (
quant_range_left | quant_range_right | quant_range_both | quant_range_neither
)
# repetition {n}
quant_rep = open_curly + number + close_curly
quant_rep.setParseAction(lambda t: (t[0], t[0]))
# quantifier operator
quant_op = oneOf("? * +")
quant_op.setParseAction(
lambda t: (0, 1) if t[0] == "?" else (0, None) if t[0] == "*" else (1, None)
)
# any quantifier
quantifier = quant_op | quant_range | quant_rep
# a hole that can take the place of a matcher
hole_matcher = Literal(surface_hole).setParseAction(lambda t: HoleMatcher())
# a matcher that compares tokens to a string (t[0])
exact_matcher = string.setParseAction(lambda t: ExactMatcher(t[0]))
# any matcher
matcher = hole_matcher | exact_matcher
# a hole that can take the place of a token constraint
hole_constraint = Literal(surface_hole).setParseAction(lambda t: HoleConstraint())
# a constraint of the form `f=v` means that only tokens
# that have a field `f` with a corresponding value of `v`
# can be accepted
field_constraint = matcher + equals + matcher
field_constraint.setParseAction(lambda t: FieldConstraint(*t))
# forward declaration, defined below
or_constraint = Forward()
# an expression that represents a single constraint
atomic_constraint = (
field_constraint | hole_constraint | open_parens + or_constraint + close_parens
)
# a constraint that may or may not be negated
not_constraint = Optional("!") + atomic_constraint
not_constraint.setParseAction(lambda t: NotConstraint(t[1]) if len(t) > 1 else t[0])
# one or two constraints ANDed together
and_constraint = Forward()
and_constraint << (not_constraint + Optional(ampersand + and_constraint))
and_constraint.setParseAction(lambda t: AndConstraint(*t) if len(t) == 2 else t[0])
# one or two constraints ORed together
or_constraint << (and_constraint + Optional(vbar + or_constraint))
or_constraint.setParseAction(lambda t: OrConstraint(*t) if len(t) == 2 else t[0])
# a hole that can take the place of a surface query
hole_surface = Literal(surface_hole).setParseAction(lambda t: HoleSurface())
# a token constraint surrounded by square brackets
token_constraint = open_bracket + or_constraint + close_bracket
token_constraint.setParseAction(lambda t: TokenSurface(t[0]))
# an unconstrained token
token_wildcard = open_bracket + close_bracket
token_wildcard.setParseAction(lambda t: WildcardSurface())
# a token pattern
token_surface = token_wildcard | token_constraint
# forward declaration, defined below
or_surface = Forward()
# an entity or event mention
mention_surface = at + matcher
mention_surface.setParseAction(lambda t: MentionSurface(t[0]))
# an expression that represents a single query
atomic_surface = (
hole_surface
| token_surface
| mention_surface
| open_parens + or_surface + close_parens
)
# a query with an optional quantifier
repeat_surface = atomic_surface + Optional(quantifier)
repeat_surface.setParseAction(
lambda t: RepeatSurface(t[0], *t[1]) if len(t) > 1 else t[0]
)
# one or two queries that must match consecutively
concat_surface = Forward()
concat_surface << (repeat_surface + Optional(concat_surface))
concat_surface.setParseAction(lambda t: ConcatSurface(*t) if len(t) == 2 else t[0])
# one or two queries ORed together
or_surface << (concat_surface + Optional(vbar + or_surface))
or_surface.setParseAction(lambda t: OrSurface(*t) if len(t) == 2 else t[0])
# a hole that can take the place of a traversal
hole_traversal = Literal(traversal_hole).setParseAction(lambda t: HoleTraversal())
# labeled incoming edge
incoming_label = lt + matcher
incoming_label.setParseAction(lambda t: IncomingLabelTraversal(t[0]))
# any incoming edge
incoming_wildcard = Literal("<<")
incoming_wildcard.setParseAction(lambda t: IncomingWildcardTraversal())
# an incoming edge
incoming_traversal = incoming_label | incoming_wildcard
# labeled outgoing edge
outgoing_label = gt + matcher
outgoing_label.setParseAction(lambda t: OutgoingLabelTraversal(t[0]))
# any outgoing edge
outgoing_wildcard = Literal(">>")
outgoing_wildcard.setParseAction(lambda t: OutgoingWildcardTraversal())
# an outgoing edge
outgoing_traversal = outgoing_label | outgoing_wildcard
# forward declaration, defined below
or_traversal = Forward()
# an expression that represents a single traversal
atomic_traversal = (
hole_traversal
| incoming_traversal
| outgoing_traversal
| open_parens + or_traversal + close_parens
)
# a traversal with an optional quantifier
repeat_traversal = atomic_traversal + Optional(quantifier)
repeat_traversal.setParseAction(
lambda t: RepeatTraversal(t[0], *t[1]) if len(t) > 1 else t[0]
)
# one or two traversals that must match consecutively
concat_traversal = Forward()
concat_traversal << (repeat_traversal + Optional(concat_traversal))
concat_traversal.setParseAction(lambda t: ConcatTraversal(*t) if len(t) == 2 else t[0])
# one or two traversals ORed together
or_traversal << (concat_traversal + Optional(vbar + or_traversal))
or_traversal.setParseAction(lambda t: OrTraversal(*t) if len(t) == 2 else t[0])
# a hole that can take the place of a hybrid query
hole_query = Literal(query_hole).setParseAction(lambda t: HoleQuery())
# forward declaration, defined below
odinson_query = Forward()
# a single surface or a hybrid (surface, traversal, surface)
hybrid_query = Forward()
hybrid_query << (or_surface + Optional(or_traversal + odinson_query))
hybrid_query.setParseAction(lambda t: HybridQuery(*t) if len(t) == 3 else t[0])
odinson_query << (hole_query | hybrid_query)
# the top symbol of our grammar
top = LineStart() + odinson_query + LineEnd()
def parse_odinson_query(pattern: Text) -> AstNode:
"""Gets a string and returns the corresponding AST."""
return top.parseString(pattern)[0]
def parse_surface(pattern: Text) -> Surface:
"""Gets a string and returns the corresponding surface pattern."""
or_surface.parseString(pattern)[0]
def parse_traversal(pattern: Text) -> Traversal:
"""Gets a string and returns the corresponding graph traversal."""
return or_traversal.parseString(pattern)[0] | python | 10 | 0.733149 | 87 | 34.096916 | 227 | starcoderdata |
package com.group.yztcedu.fblife.main.carbarn;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.group.yztcedu.fblife.R;
import com.group.yztcedu.fblife.config.UrlConfig_BrandImage;
import com.group.yztcedu.fblife.main.carbarn.entity.Vehicle;
import java.util.List;
/**
* Created by Administrator on 2016/8/10.
*/
public class VehicleAdapter extends BaseAdapter implements SectionIndexer {
private Context mContext;
private List mList;
public VehicleAdapter(Context context, List list){
this.mContext=context;
this.mList=list;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int i) {
return mList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view==null){
view = LayoutInflater.from(mContext).inflate(R.layout.garage_item_layout,null);
viewHolder=new ViewHolder(view);
view.setTag(viewHolder);
}else {
viewHolder= (ViewHolder) view.getTag();
}
int section=getSectionForPosition(i);
int position=getPositionForSection(section);
viewHolder.textView.setText(mList.get(i).getName());
Glide.with(mContext).load(UrlConfig_BrandImage.base_url+mList.get(i).getBrand()+".jpg")
.into(viewHolder.imageView);
if(position==i){
viewHolder.linearLayout.setVisibility(View.VISIBLE);
viewHolder.textView_title.setText(mList.get(i).getSortedKey());
Log.i("TAG","执行了适配器");
}else{
viewHolder.linearLayout.setVisibility(View.GONE);
}
return view;
}
static class ViewHolder{
ImageView imageView;
TextView textView,textView_title;
LinearLayout linearLayout;
public ViewHolder(View view){
imageView= (ImageView) view.findViewById(R.id.garage_vehicle_image);
textView= (TextView) view.findViewById(R.id.garage_brand);
textView_title= (TextView) view.findViewById(R.id.garage_sortedKey);
linearLayout= (LinearLayout) view.findViewById(R.id.garage_title);
}
}
@Override
public Object[] getSections() {
return null;
}
@Override
public int getPositionForSection(int i) {
for(int j=0;j<mList.size();j++){
String t=mList.get(j).getSortedKey();
char s=t.charAt(0);
if(s==i){
return j;
//直接跳此方法,返回结果;
}
}
return -1;
}
@Override
public int getSectionForPosition(int i) {
return mList.get(i).getSortedKey().charAt(0);
}
} | java | 14 | 0.639143 | 95 | 27.845455 | 110 | starcoderdata |
"# PKG Rules"
load("//pkg/private/rules:pkg_tar.bzl", _pkg_tar = "pkg_tar")
load("//pkg/private/rules:file_size.bzl", _file_size = "file_size")
load("//pkg/private:providers.bzl", _ArchiveInfo = "ArchiveInfo")
pkg_tar = _pkg_tar
file_size = _file_size
ArchiveInfo = _ArchiveInfo | python | 6 | 0.683274 | 67 | 30.222222 | 9 | starcoderdata |
'use strict';
const {dirname, normalize, join} = require('path');
const {readdirSync} = require('fs');
const {platform: os} = require('process');
const compose = require('compose-function');
const sequence = require('promise-compose');
const micromatch = require('micromatch');
const tape = require('blue-tape');
const {init, layer, cwd, fs, env, meta, exec} = require('test-my-cli');
const {assign} = Object;
const {assertExitCodeZero} = require('./lib/assert');
const {testBase} = require('./cases/common/tests');
// tests are located in resolve-url-loader package which might differ from package under test
const PLATFORMS_DIR = compose(normalize, join)(__dirname, '..', 'packages', 'resolve-url-loader', 'test');
const CASES_DIR = join(__dirname, 'cases');
const testCaseVsEngine = ([_, engineName, caseName]) => {
const split = caseName.split('.');
return (split.length === 1) || (split[1] === engineName);
};
const testIncluded = process.env.ONLY ?
(arr) => {
const patterns = process.env.ONLY.split(' ').map(v => v.trim());
return (micromatch(arr, patterns).length >= patterns.length);
} :
() => true;
const permute = (array, ...rest) =>
(rest.length === 0) ?
array.map(v => [v]) :
array.reduce((r, v) => [...r, ...permute(...rest).map((vv) => [v, ...vv])], []);
const getVersionHash = platform =>
platform
.match(/\b\w+\d\b/g)
.reduce((r, v) => assign(r, {
[v.slice(0, -1)]: parseInt(v.slice(-1))
}), {});
// isolate test by timestamp
const epoch = Math.round(Date.now() / 1000).toString().padStart(10, 0);
console.log(`timestamp: ${epoch}`);
// platforms, engines, cases
const tests = permute(
readdirSync(PLATFORMS_DIR),
['rework', 'postcss'],
readdirSync(CASES_DIR).filter((v) => v.endsWith('.js')).map((v) => v.split('.').slice(0, -1).join('.'))
)
.filter(testCaseVsEngine)
.filter(testIncluded);
const filterTests = (...terms) =>
tests
.filter(test => test.slice(0, terms.length).join() === terms.join())
.map(test => test[terms.length])
.filter((v, i, a) => a.indexOf(v) === i);
// before we do anything show all tests that match the filter
tests.forEach((test) => console.log(...test));
filterTests()
.forEach(platform => {
// common and/or cached node-modules cuts test time drastically
const platformDir = join(PLATFORMS_DIR, platform);
const platformFiles = readdirSync(platformDir)
.reduce((r, file) => assign(r, {[file]: join(platformDir, file)}), {});
tape(
platform,
sequence(
init({
directory: [process.cwd(), join('tmp', '.cache'), platform],
ttl: false,
debug: (process.env.DEBUG === 'true'),
env: {
merge: {
'PATH': (...elements) => elements.join((platform === 'win32') ? ';' : ':')
}
},
layer: {
keep: true
}
}),
layer()(
cwd('.'),
fs(platformFiles),
env({
PATH: dirname(process.execPath)
}),
exec('npm install'),
assertExitCodeZero('npm install')
)
)
);
// test cases are a function of the cache directory and the gross package versions
tape(
platform,
sequence(
init({
directory: [process.cwd(), join('tmp', epoch), platform],
ttl: (process.env.KEEP !== 'true') && '1s',
debug: (process.env.DEBUG === 'true'),
env: {
merge: {
'PATH': (...elements) => elements.join((os === 'win32') ? ';' : ':'),
'*QUERY': (...elements) => elements.join('&'),
'*OPTIONS': (prev, next) => assign(JSON.parse(prev), next),
'OUTPUT': (...elements) => elements.join('--')
}
},
layer: {
keep: (process.env.KEEP === 'true')
}
}),
...filterTests(platform).map(engine =>
testBase(engine)(
env({
PATH: dirname(process.execPath),
RESOLVE_URL_LOADER_TEST_HARNESS: 'stderr'
}),
meta({
cacheDir: join(process.cwd(), 'tmp', '.cache', platform),
version: getVersionHash(platform)
}),
...filterTests(platform, engine).map(caseName => require(join(CASES_DIR, caseName)))
)
)
)
);
}); | javascript | 26 | 0.545783 | 106 | 31.364964 | 137 | starcoderdata |
#include "MinerClient.hpp"
#include "Messages.hpp"
#include "Signature.hpp"
#include "Utils.hpp"
namespace bc {
MinerClient::MinerClient(boost::asio::io_service& ioService, short port)
: Client(ioService, port)
{}
void MinerClient::receive(Session*, uint8_t const* data, size_t size) {
Message const& msg = *reinterpret_cast<Message const*>(data);
if (msg.type != MessageType::blockReq) {
std::cerr << "Message type is not block request" << std::endl;
}
std::cout << "Got block request" << std::endl;
BlockReq const& req = *reinterpret_cast<BlockReq const*>(msg.buffer);
uint8_t const* blockReqData = req.buffer;
// signature
size_t b64msgLen = *(size_t*)blockReqData;
blockReqData += sizeof(size_t);
B64Message b64msg;
b64msg.alloc((char const*)blockReqData, b64msgLen);
blockReqData += b64msgLen;
Signature signature;
b64msg.decode(signature);
// public key
size_t publicKeyLen = *(size_t*)blockReqData;
blockReqData += sizeof(size_t);
char* publicKey = new char[publicKeyLen + 1];
std::memcpy(publicKey, blockReqData, publicKeyLen);
publicKey[publicKeyLen] = 0;
blockReqData += publicKeyLen;
// message
size_t messageLen = *(size_t*)blockReqData;
blockReqData += sizeof(size_t);
bool authentic;
if (signature.verify(publicKey, publicKeyLen, (char const*)blockReqData, messageLen, authentic) == false) {
std::cerr << "Failed to verify transaction" << std::endl;
return;
}
if (authentic) {
std::cout << "Transaction is verified" << std::endl;
}
delete[] publicKey;
std::string message((char const*)blockReqData, messageLen);
auto [nonce, hash] = findHash(req.uid, req.previousHash, Hash{message});
Block block{req.uid, req.previousHash, hash, nonce, message};
sendBlock(block);
session->start();
}
void MinerClient::onConnect() {
sendRegistrationRequest();
session->start();
}
void MinerClient::sendBlock(Block const& block) {
// send calculated block
uint8_t* msgData = session->allocateMessage();
Message& msg = *new (msgData) Message;
msg.type = MessageType::blockRsp;
BlockRsp& rsp = *new (msg.buffer) BlockRsp;
rsp.uid = block.uid;
rsp.previousHash = block.previousHash;
rsp.hash = block.hash;
rsp.nonce = block.nonce;
uint8_t* blockRspData = rsp.buffer;
*(size_t*)blockRspData = block.data.size();
blockRspData += sizeof(size_t);
std::memcpy(blockRspData, block.data.c_str(), block.data.size());
blockRspData += block.data.size();
msg.size = blockRspData - msgData - sizeof(Message);
session->send(msgData, blockRspData - msgData);
}
void MinerClient::sendRegistrationRequest() {
uint8_t* msgData = session->allocateMessage();
Message& msg = *new (msgData) Message;
msg.type = MessageType::minerRegister;
msg.size = 0;
session->send(msgData, sizeof(msg));
}
} // namespace bc | c++ | 13 | 0.659399 | 111 | 26.770642 | 109 | starcoderdata |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
class EditTimeTrackable(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta(object):
abstract = True
class Namable(models.Model):
name = models.CharField(unique=True, max_length=255)
class Meta(object):
abstract = True
class Breed(EditTimeTrackable, Namable):
"""Class is a model that keep pet bread."""
class Pet(Namable, EditTimeTrackable):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
breed = models.ForeignKey(Breed)
GENDERS = (
('male', 'male'),
('female', 'female'),
)
gender = models.CharField(choices=GENDERS, max_length=6)
class Birth(EditTimeTrackable):
child = models.OneToOneField(Pet)
father = models.ForeignKey(Pet, related_name='father_of', null=True)
mother = models.ForeignKey(Pet, related_name='mother_of', null=True) | python | 9 | 0.691027 | 72 | 24.738095 | 42 | starcoderdata |
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using ApprovalTests;
using ApprovalTests.Reporters;
using WebApi.Hal.Tests.Representations;
using Xunit;
namespace WebApi.Hal.Tests
{
public class HalResourceListTests
{
readonly OrganisationListRepresentation representation;
readonly OrganisationListRepresentation oneitemrepresentation;
public HalResourceListTests()
{
representation = new OrganisationListRepresentation(
new List
{
new OrganisationRepresentation(1, "Org1"),
new OrganisationRepresentation(2, "Org2")
});
oneitemrepresentation = new OrganisationListRepresentation(
new List
{
new OrganisationRepresentation(1, "Org1")
});
}
[Fact]
[UseReporter(typeof(DiffReporter))]
public void organisation_list_get_xml_test()
{
// arrange
var mediaFormatter = new XmlHalMediaTypeFormatter();
var content = new StringContent(string.Empty);
var type = representation.GetType();
// act
using (var stream = new MemoryStream())
{
mediaFormatter.WriteToStream(type, representation, stream, content);
stream.Seek(0, SeekOrigin.Begin);
var serialisedResult = new StreamReader(stream).ReadToEnd();
// assert
Approvals.Verify(serialisedResult, s => s.Replace("\r\n", "\n"));
}
}
[Fact]
[UseReporter(typeof(DiffReporter))]
public void organisation_list_get_json_test()
{
// arrange
var mediaFormatter = new JsonHalMediaTypeFormatter { Indent = true };
var content = new StringContent(string.Empty);
var type = representation.GetType();
// act
using (var stream = new MemoryStream())
{
mediaFormatter.WriteToStreamAsync(type, representation, stream, content, null).Wait();
stream.Seek(0, SeekOrigin.Begin);
var serialisedResult = new StreamReader(stream).ReadToEnd();
// assert
Approvals.Verify(serialisedResult, s => s.Replace("\r\n", "\n"));
}
}
[Fact]
[UseReporter(typeof(DiffReporter))]
public void one_item_organisation_list_get_json_test()
{
// arrange
var mediaFormatter = new JsonHalMediaTypeFormatter { Indent = true };
var content = new StringContent(string.Empty);
var type = oneitemrepresentation.GetType();
// act
using (var stream = new MemoryStream())
{
mediaFormatter.WriteToStreamAsync(type, oneitemrepresentation, stream, content, null).Wait();
stream.Seek(0, SeekOrigin.Begin);
var serialisedResult = new StreamReader(stream).ReadToEnd();
// assert
Approvals.Verify(serialisedResult, s => s.Replace("\r\n", "\n"));
}
}
}
} | c# | 18 | 0.562115 | 109 | 33.40404 | 99 | starcoderdata |
static void lssi_update_volume_headers( LSS_V3 *lss )
{
int i;
/*
* update all volume headers that are open for WRITE access
*/
for (i=0; i<lss->num_vols; i++)
{
if (lss->vol[i].flags & LSS_RDWR)
{
lssi_update_one_volume_header( lss, i );
}
}
} | c | 11 | 0.533557 | 62 | 18.933333 | 15 | inline |
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Rotate extends JFrame
{
double angle=90;
JLabel l;
public Rotate()
{
super("My Window");
setLayout(null);
setResizable(false);
l=new JLabel(new ImageIcon(getClass().getResource("apple.png"))){
@Override
protected void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform aff=g2.getTransform();
Shape shape=g2.getClip();
double w=getWidth()/2.0;
double h=getHeight()/2.0;
aff.rotate(Math.toRadians(angle), w, h);
g2.setClip(shape);
g2.setTransform(aff);
super.paintComponent(g);
}
};
l.setBounds(200,200,100,100);
l.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
try{
URL url=getClass().getResource("wind.wav");
AudioStream stream=new AudioStream(url.openStream());
AudioPlayer.player.start(stream);
}catch(Exception ex)
{}
}
});
add(l);
l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
addKeyListener(new MyClass());
setSize(500,500);
setVisible(true);
}
public class MyClass extends KeyAdapter
{
@Override
public void keyPressed(KeyEvent e)
{
int keycode=e.getKeyCode();
if(keycode==KeyEvent.VK_LEFT)
angle=270;
else if(keycode==KeyEvent.VK_RIGHT)
angle=90;
else if(keycode==KeyEvent.VK_UP)
angle=0;
else if(keycode==KeyEvent.VK_DOWN)
angle=180;
l.repaint();
}
}
public static void main(String a[])
{
new Rotate();
}
} | java | 20 | 0.523274 | 73 | 29.060241 | 83 | starcoderdata |
import { Argv } from 'yargs';
export default async (yargs: Argv) => {
yargs
.usage('usage: $0 account
.command('create', 'create account', require('./cmd/create').default)
.command('key', 'get private key', require('./cmd/key').default)
.command('balance', 'get account balance', require('./cmd/balance').default)
.command('drand', 'create decentralized randomness', require('./cmd/drand').default)
.command('oraichain-vrf', 'full flow creating a decentralized random seed', require('./cmd/oraichain-vrf').default);
}; | javascript | 17 | 0.681967 | 120 | 54.454545 | 11 | starcoderdata |
package hbuild
import (
"net/http"
"strings"
)
type Build struct {
Id UUID
Stream *http.Response
status string
token string
app string
}
type BuildResponseJSON struct {
Id string `json:"id"`
OutputStreamURL string `json:"output_stream_url"`
Status string `json:"status"`
}
type BuildRequestJSON struct {
SourceBlob struct {
Url string `json:"url"`
Version string `json:"version"`
} `json:"source_blob"`
}
type BuildResultJSON struct {
Build struct {
Id string `json:"id"`
Status string `json:"status"`
} `json:"build"`
ExitCode int `json:"exit_code"`
Lines []map[string]string `json:"lines"`
}
type BuildOptions struct {
SourceVersion string
AdditionalHeaders http.Header
}
func NewBuild(token, app string, source Source, opts BuildOptions) (build Build, err error) {
buildReqJson := BuildRequestJSON{}
buildReqJson.SourceBlob.Url = source.Get.String()
buildReqJson.SourceBlob.Version = opts.SourceVersion
client := newHerokuClient(token)
buildResJson := BuildResponseJSON{}
err = client.request(buildRequest(app, buildReqJson, opts.AdditionalHeaders), &buildResJson)
if err != nil {
return
}
build.Id = UUID(buildResJson.Id)
build.token = token
build.app = app
transport := http.DefaultTransport
if strings.Contains(buildResJson.OutputStreamURL, "herokudev") {
transport = unverifiedSSLTransport
}
streamingClient := &http.Client{Transport: transport}
stream, err := streamingClient.Get(buildResJson.OutputStreamURL)
if err != nil {
return
}
build.Stream = stream
return
}
func (b *Build) Status() (string, error) {
buildJson := new(BuildResponseJSON)
client := newHerokuClient(b.token)
err := client.request(buildStatusRequest(*b), &buildJson)
if err != nil {
return "", err
}
return buildJson.Status, nil
}
func (b *Build) Result() (BuildResultJSON, error) {
result := BuildResultJSON{}
client := newHerokuClient(b.token)
err := client.request(buildResultRequest(*b), &result)
if err != nil {
return result, err
}
return result, nil
}
func buildRequest(app string, build BuildRequestJSON, additionalHeaders http.Header) herokuRequest {
return herokuRequest{"POST", "/apps/" + app + "/builds", build, additionalHeaders}
}
func buildStatusRequest(build Build) herokuRequest {
return herokuRequest{"GET", "/apps/" + build.app + "/builds/" + string(build.Id), nil, http.Header{}}
}
func buildResultRequest(build Build) herokuRequest {
return herokuRequest{"GET", "/apps/" + build.app + "/builds/" + string(build.Id) + "/result", nil, http.Header{}}
} | go | 13 | 0.705611 | 114 | 23.317757 | 107 | starcoderdata |
#pragma once
class CLight_rSM
{
public:
void compute_xf_direct (Fmatrix& L_view, Fmatrix& L_project, Fmatrix& mView, float p_FOV, float p_A, float p_FAR, float plane_dist);
void create (u32 dim);
void destroy ();
}; | c | 8 | 0.655319 | 133 | 24.111111 | 9 | starcoderdata |
<?php
requirePHPLib('api');
$curUser = validateAll()['user'];
if (!isset($_GET['id'])) fail('id: Field should not be empty');
if (!validateUInt($_GET['id']) || !($contest = queryContest($_GET['id']))) fail("id: Contest with id '{$_GET['id']}' not found");
if (!checkContestGroup($curUser, $contest)) fail("id: You have no permission to view contest #{$_GET['id']}");
genMoreContestInfo($contest);
$conf = array('show_estimate_result' => true);
if (check_parameter_on('all')) {
$conf['verbose'] = true;
}
$contest_data = queryContestData($contest, $conf);
calcStandings($contest, $contest_data, $score, $standings);
$ret = array(
'standings' => $standings,
'score' => $score,
'problems' => $contest_data['problems'],
'full_scores' => $contest_data['full_scores']
);
if (isset($conf['verbose'])) {
$ret['submissions'] = $contest_data['data'];
}
die_json(json_encode(array(
'status' => 'ok',
'result' => $ret
))); | php | 12 | 0.568326 | 133 | 32.484848 | 33 | starcoderdata |
def test_path_and_rename_logos_instance_pk():
instance = mock.Mock(pk=1)
actual = helpers.path_and_rename_logos(instance, 'a.jpg')
assert actual.startswith('company_logos')
# PK should not be in the filename
assert actual != 'company_logos/1.jpg'
assert actual.endswith('.jpg') | python | 8 | 0.688742 | 61 | 36.875 | 8 | inline |
package chao.app.debugtools.widgets.cardrefresh;
import android.view.View;
/**
* @author qinchao
* @since 2018/8/16
*/
public abstract class AbstractModeController implements ModeController{
PullRecycleView pullRecycleView;
PullHeaderView headerView;
View refreshView;
private static final int HEADER_POSITION = -1;
private PullStaggeredGridLayoutManager layoutManager;
private int mScrollState;
@Override
public boolean overHeader() {
int firstPosition = getLayoutManager().findFirstVisibleItemPosition();
return firstPosition == HEADER_POSITION;
}
@Override
public void setHeaderView(PullHeaderView headerView) {
this.headerView = headerView;
refreshView = headerView.getRefreshView();
}
public AbstractModeController(PullRecycleView recycleView) {
this.pullRecycleView = recycleView;
}
public PullStaggeredGridLayoutManager getLayoutManager() {
if (layoutManager == null) {
layoutManager = (PullStaggeredGridLayoutManager) pullRecycleView.getLayoutManager();
}
return layoutManager;
}
@Override
public int cursor() {
return headerView.getBottom();
}
@Override
public int offset() {
return 0;
}
boolean isScrollState(int state) {
return mScrollState == state;
}
void setScrollState(int state) {
mScrollState = state;
}
int getHeight() {
return headerView.getHeight();
}
public int getCardHight() {
return headerView.getCardView().getHeight();
}
public int getRefreshHeight() {
return headerView.getRefreshView().getHeight();
}
} | java | 12 | 0.668611 | 96 | 21.552632 | 76 | starcoderdata |
import React, {Component} from "react";
import API from "../../Utils/API";
// const Search = () => (
//
// By Breed!
// Name:
// <input type="text" />
// <button id="submit">Submit
//
// )
class Search extends Component {
state = {
breedName: ""
}
handleInputChange = event => {
this.setState({breedName: event.target.value});
}
handleSubmit = event => {
// console.log(this);
// console.log(event);
event.preventDefault();
API.searchBreed(this.state.breedName).then((req, res) => {
// console.log("API Search Breed")
this.setState({breedArr: res.data.message})
});
}
render() {
return (
By Breed!
Name:
<input
value={this.state.breedName}
onChange={this.handleInputChange}
type="text" />
<button id="submit" onClick={this.handleSubmit}>Submit
);
}
}
export default Search; | javascript | 18 | 0.497553 | 79 | 23.54 | 50 | starcoderdata |
/*
Copyright 2016-2020 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.
*/
#pragma once
#include "sched/sched_base.hpp"
class ccl_sched;
class ccl_sched_key;
class ccl_master_sched : public ccl_sched_base, public ccl_request {
public:
static constexpr const char* class_name() {
return "master_sched";
}
ccl_master_sched(const ccl_coll_param& coll_param)
: ccl_sched_base(coll_param),
ccl_request(),
partial_scheds() {
#ifdef ENABLE_DEBUG
set_dump_callback([this](std::ostream& out) {
dump(out);
});
#endif
}
ccl_master_sched(const ccl_master_sched& src) = delete;
~ccl_master_sched() override;
void add_partial_sched(const ccl_coll_param& param);
void commit(ccl_parallelizer* parallelizer = nullptr);
ccl_request* start(ccl_executor* exec, bool reset_sched = true);
/**
* Reset completion counter of @b req
* @return pointer to req that can be used to track completion
*/
ccl_request* reset_request();
/**
* Synchronizes partial schedules on local barrier
*/
void sync_partial_scheds();
void dump(std::ostream& out) const;
//TODO encapsulate it in private.
std::vector partial_scheds;
//factory method (TODO: wrap into smart-pointer)
using ccl_master_sched_ptr = ccl_master_sched*;
static ccl_master_sched_ptr create(const ccl_coll_param& param, const ccl_coll_attr& attr);
private:
void prepare_partial_scheds();
}; | c++ | 14 | 0.682669 | 95 | 29.188406 | 69 | starcoderdata |
# Copyright 2018 Luddite Labs Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from docutils.utils import Reporter as _Reporter
def create_logger(verbose=False):
"""Create autodoc logger.
This function creates output stream logger with simplified message format.
Args:
verbose: Set debug level.
Returns:
Logger instance.
"""
console = logging.StreamHandler()
console.setFormatter(logging.Formatter('%(message)s'))
logger = logging.getLogger('autodoc')
logger.addHandler(console)
logger.setLevel(logging.DEBUG if verbose else logging.INFO)
return logger
# Levels mapping to convert from docutils levels to logging levels.
_levels = {
_Reporter.DEBUG_LEVEL: logging.DEBUG,
_Reporter.INFO_LEVEL: logging.INFO,
_Reporter.WARNING_LEVEL: logging.WARNING,
_Reporter.ERROR_LEVEL: logging.ERROR,
_Reporter.SEVERE_LEVEL: logging.FATAL
}
class Codes:
"""Report codes."""
# -- Docstring analysis codes ---------------------------------------------
#: Something is too complex (like 'specification too complex').
COMPLEX = 'D301'
#: Duplicate (duplicate declaration).
DUPLICATE = 'D302'
#: Something is incorrect (incorrect signature).
INCORRECT = 'D303'
#: Something unknown.
UNKNOWN = 'D304'
#: Empty state.
EMPTY = 'D305'
#: Missing state.
MISSING = 'D306'
#: Mismatch in something.
MISMATCH = 'D307'
#: Empty/missing docstring.
NODOC = 'D308'
#: Docstring parsing error.
PARSERR = 'D309'
# -- Other codes ----------------------------------------------------------
#: Internal errors.
INTERNAL = 'INTERNAL'
#: Information.
INFO = 'D300'
#: Transform errors.
ERROR = 'D401'
#: I/O errors.
IOERROR = 'D402'
class BaseReporter:
def __init__(self):
self.definition = None
def reset(self):
"""Reset reporter's state."""
self.definition = None
def document_message(self, msg):
"""This method collects docutils' reporter messages."""
if self.definition is not None:
line, col = self.definition.get_start_pos()
else:
line = col = None
if msg.hasattr('autodoc'):
self.add_report(msg.get('code', 'D201'), msg.children[0].astext(),
line, col)
else:
level = msg.get('level')
log_level = _levels.get(level, logging.DEBUG)
code = 'D1{:02d}'.format(level)
text = msg.children[0].astext().replace('\n', ' ')
self.add_report(code, text, line, col, log_level)
def add_report(self, code, message, line=None, col=None, level=None):
"""Add report.
Args:
code: Report code.
message: Report message.
line: Line number in the content.
col: Column number in the content.
level: Logging level. Info level is used if not specified.
"""
pass
class DomainReporter(BaseReporter):
#: Message format.
fmt = u'{path}: [{code}] {msg}'
def __init__(self, domain):
super(DomainReporter, self).__init__()
self.domain = domain
self._env = None
self._filename = None
@property
def env(self):
return self._env
@env.setter
def env(self, value):
self._env = value
self.definition = value.get('definition')
self._filename = value.get('report_filename')
def reset(self):
super(DomainReporter, self).reset()
self._filename = None
self._env = None
def add_report(self, code, message, line=0, col=0, level=None):
level = level or logging.INFO
if self.definition is not None:
line_, col_ = self.definition.get_start_pos()
if line == 0:
line = line_
if col == 0:
col = col_
name = self.definition.name
else:
name = None
path_item = [self._filename] if self._filename else []
if line:
# NOTE:
# We +1 because all indexes and positions are assumed to be
# zero-based and we display in 1-based format.
path_item.append(str(line))
path_item.append(str(col))
code_item = [code, self.domain.name]
if name:
code_item.append(name)
message = self.fmt.format(path=':'.join(path_item),
code=':'.join(code_item), msg=message)
self.domain.logger.log(level, message) | python | 16 | 0.584078 | 79 | 26.540107 | 187 | starcoderdata |
def get_detector_array(self, coordinates):
"""
Calculate the number of pixels in the detector FOV and the physical coordinates of the
bottom left and top right corners.
"""
if self.fov_center is not None and self.fov_width is not None:
center = self.fov_center.transform_to(self.projected_frame)
bins_x = int(np.ceil((self.fov_width[0] / self.resolution[0]).decompose()).value)
bins_y = int(np.ceil((self.fov_width[1] / self.resolution[1]).decompose()).value)
bottom_left_corner = SkyCoord(
Tx=center.Tx - self.fov_width[0]/2,
Ty=center.Ty - self.fov_width[1]/2,
frame=center.frame,
)
top_right_corner = SkyCoord(
Tx=bottom_left_corner.Tx + self.fov_width[0],
Ty=bottom_left_corner.Ty + self.fov_width[1],
frame=bottom_left_corner.frame
)
else:
# If not specified, derive FOV from loop coordinates
coordinates = coordinates.transform_to(self.projected_frame)
# NOTE: this is the coordinate of the bottom left corner of the bottom left corner pixel,
# NOT the coordinate at the center of the pixel!
bottom_left_corner = SkyCoord(
Tx=coordinates.Tx.min() - self.pad_fov[0],
Ty=coordinates.Ty.min() - self.pad_fov[1],
frame=coordinates.frame
)
delta_x = coordinates.Tx.max() + self.pad_fov[0] - bottom_left_corner.Tx
delta_y = coordinates.Ty.max() + self.pad_fov[1] - bottom_left_corner.Ty
bins_x = int(np.ceil((delta_x / self.resolution[0]).decompose()).value)
bins_y = int(np.ceil((delta_y / self.resolution[1]).decompose()).value)
# Compute right corner after the fact to account for rounding in bin numbers
# NOTE: this is the coordinate of the top right corner of the top right corner pixel, NOT
# the coordinate at the center of the pixel!
top_right_corner = SkyCoord(
Tx=bottom_left_corner.Tx + self.resolution[0]*bins_x*u.pixel,
Ty=bottom_left_corner.Ty + self.resolution[1]*bins_y*u.pixel,
frame=coordinates.frame
)
return (bins_x, bins_y), (bottom_left_corner, top_right_corner) | python | 19 | 0.582812 | 101 | 56.095238 | 42 | inline |
// Flaredns backups the DNS records table of all provided Cloudflare domains.
// Optionally commits all your DNS records to a git repository.
package main
import (
"math/rand"
"os"
"time"
"github.com/vlct-io/pkg/logger"
"github.com/gobuffalo/envy"
"github.com/spf13/cobra"
)
var (
log = logger.New()
start = time.Now().UTC().Format(time.RFC3339)
)
// Environment variables
var (
exportFlag string
envErr error
cfAuthKey string
cfAuthEmail string
)
func init() {
rand.Seed(time.Now().UnixNano())
envy.Load()
cfAuthKey, envErr = envy.MustGet("CF_AUTH_KEY")
cfAuthEmail, envErr = envy.MustGet("CF_AUTH_EMAIL")
cobra.OnInitialize(initConfig)
RootCmd.AddCommand(VersionCmd)
RootCmd.AddCommand(ExportCmd)
return
}
func main() {
// This should be all that's needed after everything gets converted.
Execute()
}
func writeFile(data []byte, filePath string) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
return err
}
return nil
} | go | 10 | 0.7 | 77 | 16.966102 | 59 | starcoderdata |
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* Contains types to model text files and handle operations on text.
* Parser implementations build upon this framework. This package is
* built around the type {@link net.sourceforge.pmd.lang.document.TextFile},
* which represents a source file and allows reading and writing. The
* class {@link net.sourceforge.pmd.lang.document.TextDocument} models
* an in-memory snapshot of the state of a TextFile, and exposes information
* like line/offset mapping.
*
* @see net.sourceforge.pmd.lang.document.TextFile
* @see net.sourceforge.pmd.lang.document.TextDocument
* @see net.sourceforge.pmd.reporting.Reportable
*/
@Experimental
package net.sourceforge.pmd.lang.document;
import net.sourceforge.pmd.annotation.Experimental;
| java | 6 | 0.772397 | 79 | 38.333333 | 21 | research_code |
import React from 'react';
import {browserHistory} from 'react-router';
import Modal from 'react-modal';
import expect from 'expect';
import sinon from 'sinon';
import {mount,shallow} from 'enzyme';
import * as DocActions from '../../../actions/DocumentActions';
import DocStore from '../../../stores/DocumentStore';
import AllDocsList from '../AllDocsList.jsx';
describe('AllDocs Listing Component Tests', function() {
describe('AllDocs Component Rendering Tests', function() {
it('renders the component correctly if no docs exist', function() {
let component = mount(<AllDocsList />);
component.setState({
docs: []
});
expect(component.find('Card').length).toBe(0);
component.unmount();
});
it('renders the component correctly if docs exist', function() {
let component = mount(<AllDocsList />);
let docTest = [
{
_id: 'dsdsds',
dataCreated: Date.now(),
content: 'Content',
title: 'Test Document',
ownerId: { username: 'owner'}
},
{
_id: 'dsdsdds',
dataCreated: Date.now(),
content: 'Content2',
title: 'Test Document 2',
ownerId: { username: 'owner'}
}
];
component.setState({
docs: docTest
});
// shows 2 docs
expect(component.find('Card').length).toBe(2);
expect(component.find('AllDocs').childAt(0).text()).toMatch(/Test Document/);
expect(component.find('AllDocs').childAt(1).text()).toMatch(/Test Document 2/);
component.unmount();
});
it('initializes with the correct state', function() {
sinon.stub(DocActions, 'getAllDocs').returns({});
let component = shallow(<AllDocsList />);
expect(component.state().docs).toEqual([]);
component.unmount();
DocActions.getAllDocs.restore();
});
});
describe('AllDocs Component Method Tests', function() {
it('Calls componentWillMount', function() {
sinon.spy(AllDocsList.prototype, 'componentWillMount');
sinon.spy(DocStore, 'addChangeListener');
let component = mount(<AllDocsList />);
expect(AllDocsList.prototype.componentWillMount.called).toBe(true);
expect(DocStore.addChangeListener.called).toBe(true);
AllDocsList.prototype.componentWillMount.restore();
DocStore.addChangeListener.restore();
component.unmount();
});
it('Calls componentDidMount', function() {
sinon.stub(DocActions, 'getAllDocs').returns(true);
sinon.spy(AllDocsList.prototype, 'componentDidMount');
let component = mount(<AllDocsList />);
expect(AllDocsList.prototype.componentDidMount.called).toBe(true);
expect(DocActions.getAllDocs.called).toBe(true);
AllDocsList.prototype.componentDidMount.restore();
component.unmount();
DocActions.getAllDocs.restore();
});
it('Calls componentWillUnmount', function() {
sinon.spy(AllDocsList.prototype, 'componentWillUnmount');
sinon.spy(DocStore, 'removeChangeListener');
let component = mount(<AllDocsList />);
component.unmount();
expect(AllDocsList.prototype.componentWillUnmount.called).toBe(true);
expect(DocStore.removeChangeListener.called).toBe(true);
AllDocsList.prototype.componentWillUnmount.restore();
DocStore.removeChangeListener.restore();
});
it('getAllDocs handling', function() {
let docTest = [
{
_id: 'dsdsds',
dataCreated: Date.now(),
content: 'Content',
title: 'Test Document'
},
{
_id: 'dsdsdds',
dataCreated: Date.now(),
content: 'Content2',
title: 'Test Document 2'
}
];
sinon.stub(DocActions, 'getAllDocs').returns(docTest);
let component = mount(<AllDocsList />);
sinon.spy(AllDocsList.prototype, 'getAllDocs');
sinon.spy(DocStore, 'getAllDocs');
AllDocsList.prototype.getAllDocs();
expect(AllDocsList.prototype.getAllDocs.called).toBe(true);
expect(DocStore.getAllDocs.called).toBe(true);
component.unmount();
AllDocsList.prototype.getAllDocs.restore();
DocStore.getAllDocs.restore();
});
});
}); | javascript | 25 | 0.629829 | 85 | 34.008197 | 122 | starcoderdata |
const DOT_FROM_RIGHT = 2; // index of . from left
const DEFAULT_CURRENCY = '$';
const centsToDollarString = (cents, symbol) => {
let cStr = cents.toString();
let isNegative = false;
if (cents <= 0) {
// remove minus sign:
cStr = cStr.slice(1);
// only set isNegative flag if not 0
if (cents !== 0) {
isNegative = true;
}
}
if (cStr.length > DOT_FROM_RIGHT) {
const cArr = cStr.split('');
cArr.splice(-DOT_FROM_RIGHT, 0, '.');
cStr = cArr.join('');
} else if (cStr.length === DOT_FROM_RIGHT) {
cStr = '0.' + cStr;
} else if (cStr.length === DOT_FROM_RIGHT - 1) {
cStr = '0.0' + cStr;
} else {
cStr = '0.00';
}
// add minus sign back in if necessary
if (isNegative) {
cStr = '-' + cStr;
}
// if sign is provided, add it beginning
if (typeof symbol !== 'undefined') {
cStr = symbol + cStr;
}
return cStr;
};
module.exports = {
centsToDollarString,
DEFAULT_CURRENCY
}; | javascript | 15 | 0.567735 | 50 | 20.021739 | 46 | starcoderdata |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddIndexToTranslationTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Addd indexes
try {
Schema::table('translation_texts', function (Blueprint $table) {
$table->index('translation_key_id');
$table->index('translation_text');
$table->index('translation_locale');
});
} catch (Exception $e) {
}
// Add unique
try {
Schema::table('translation_texts', function (Blueprint $table) {
$table->unique(['translation_key_id', 'translation_locale'])->change();
});
} catch (Exception $e) {
}
// Add new indexes
try {
Schema::table('translation_keys', function (Blueprint $table) {
$table->index('translation_namespace');
$table->index('translation_key');
$table->index('translation_group');
});
} catch (Exception $e) {
}
// Drop old uniques
try {
Schema::table('translation_keys', function (Blueprint $table) {
$table->dropUnique('translation_keys_translation_key_unique');
});
} catch (Exception $e) {
}
/* // Add new unique
try {
// If we support utf8 bin
Schema::table('translation_keys', function (Blueprint $table) {
$table->text('translation_key')->collation('utf8_bin')->change();
});
// Then make unique
Schema::table('translation_keys', function (Blueprint $table) {
$table->unique(['translation_key', 'translation_group', 'translation_namespace'], 'translation_kgn_unique')->change();
});
} catch (Exception $e) {
}*/
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
} | php | 21 | 0.508189 | 134 | 24.452381 | 84 | starcoderdata |
<?php
namespace Drupal\Tests\upgrade_status\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Defines shared functions used by some of the functional tests.
*/
abstract class UpgradeStatusTestBase extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Modules to install.
*
* @var array
*/
public static $modules = [
'upgrade_status',
'upgrade_status_test_error',
'upgrade_status_test_no_error',
'upgrade_status_test_submodules_a',
'upgrade_status_test_submodules_with_error',
'upgrade_status_test_contrib_error',
'upgrade_status_test_contrib_no_error',
'upgrade_status_test_theme_functions',
'upgrade_status_test_twig',
'upgrade_status_test_library',
'upgrade_status_test_library_exception',
];
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->container->get('theme_installer')->install(['upgrade_status_test_theme']);
}
/**
* Perform a full scan on all test modules.
*/
protected function runFullScan() {
$edit = [
'contrib[data][installed][upgrade_status]' => TRUE,
'custom[data][installed][upgrade_status_test_error]' => TRUE,
'custom[data][installed][upgrade_status_test_no_error]' => TRUE,
'custom[data][installed][upgrade_status_test_submodules]' => TRUE,
'custom[data][installed][upgrade_status_test_submodules_with_error]' => TRUE,
'custom[data][installed][upgrade_status_test_twig]' => TRUE,
'custom[data][installed][upgrade_status_test_theme]' => TRUE,
'custom[data][installed][upgrade_status_test_theme_functions]' => TRUE,
'custom[data][installed][upgrade_status_test_library]' => TRUE,
'custom[data][installed][upgrade_status_test_library_exception]' => TRUE,
'contrib[data][installed][upgrade_status_test_contrib_error]' => TRUE,
'contrib[data][installed][upgrade_status_test_contrib_no_error]' => TRUE,
];
$this->drupalPostForm('admin/reports/upgrade-status', $edit, 'Scan selected');
}
} | php | 12 | 0.671911 | 95 | 31.253731 | 67 | starcoderdata |
# Copyright (C) 2015 Midokura SARL
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutron_lib.api import validators
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
from oslo_utils import excutils
from networking_l2gw import extensions as l2gateway_ext
from networking_l2gw.services.l2gateway.common import l2gw_validators
from networking_l2gw.services.l2gateway import plugin as l2gw_plugin
from neutron.api import extensions as neutron_extensions
from midonet.neutron.common import constants as mido_const
from midonet.neutron.db import l2gateway_midonet as l2gw_db
from midonet.neutron.services.l2gateway.common import l2gw_midonet_validators
LOG = logging.getLogger(__name__)
class MidonetL2GatewayPlugin(l2gw_plugin.L2GatewayPlugin,
l2gw_db.MidonetL2GatewayMixin):
"""Implementation of the Neutron l2 gateway Service Plugin.
This class manages the workflow of Midonet l2 Gateway request/response.
The base plugin methods are overridden because the MidoNet driver requires
specific ordering of events. For creation, the Neutron data must be
created first, with the resource UUID generated. Also, for both creation
and deletion, by invoking the Neutron DB methods first, all the
validations, such as 'check_admin()' are executed prior to attempting to
modify the MidoNet data, preventing potential data inconsistency.
"""
def __init__(self):
# Dynamically change the validators so that they are applicable to
# the MidoNet implementation of L2GW.
# REVISIT(yamamoto): These validator modifications should not
# have been here in the first place. We should either put them
# in upstream or remove them.
l2gw_validators.validate_gwdevice_list = (l2gw_midonet_validators.
validate_gwdevice_list)
val_type = validators._to_validation_type('l2gwdevice_list')
validators.validators.pop(val_type, None)
validators.add_validator(
val_type,
l2gw_midonet_validators.validate_gwdevice_list)
l2gw_validators.validate_network_mapping_list = (
l2gw_midonet_validators.
validate_network_mapping_list_without_seg_id_validation)
neutron_extensions.append_api_extensions_path(l2gateway_ext.__path__)
super(MidonetL2GatewayPlugin, self).__init__()
def add_port_mac(self, context, port_dict):
# This function is not implemented now in MidoNet plugin.
# We block this function in plugin level to prevent from loading
# l2gw driver in upstream.
self._get_driver_for_provider(mido_const.MIDONET_L2GW_PROVIDER
).add_port_mac(context, port_dict)
def delete_port_mac(self, context, port):
# This function is not implemented now in MidoNet plugin.
# We block this function in plugin level to prevent from loading
# l2gw driver in upstream.
self._get_driver_for_provider(mido_const.MIDONET_L2GW_PROVIDER
).delete_port_mac(context, port)
def create_l2_gateway(self, context, l2_gateway):
# Gateway Device Management Service must be enabled
# when Midonet L2 Gateway is used.
self._check_and_get_gw_dev_service()
self.validate_l2_gateway_for_create(context, l2_gateway)
return l2gw_db.MidonetL2GatewayMixin.create_l2_gateway(
self, context, l2_gateway)
@log_helpers.log_method_call
def create_l2_gateway_connection(self, context, l2_gateway_connection):
self.validate_l2_gateway_connection_for_create(
context, l2_gateway_connection)
l2_gw_conn = (l2gw_db.MidonetL2GatewayMixin.
create_l2_gateway_connection(
self, context, l2_gateway_connection))
# Copy over the ID so that the MidoNet driver knows about it. ID is
# necessary for MidoNet to process its translation.
gw_connection = l2_gateway_connection[self.connection_resource]
gw_connection["id"] = l2_gw_conn["id"]
try:
self._get_driver_for_provider(mido_const.MIDONET_L2GW_PROVIDER
).create_l2_gateway_connection(
context, l2_gateway_connection)
except Exception as ex:
with excutils.save_and_reraise_exception():
LOG.error("Failed to create a l2 gateway connection "
"%(gw_conn_id)s in Midonet:%(err)s",
{"gw_conn_id": l2_gw_conn["id"], "err": ex})
try:
l2gw_db.MidonetL2GatewayMixin.delete_l2_gateway_connection(
self, context, l2_gw_conn["id"])
except Exception:
LOG.exception("Failed to delete a l2 gateway conn %s",
l2_gw_conn["id"])
return l2_gw_conn
@log_helpers.log_method_call
def delete_l2_gateway_connection(self, context, l2_gateway_connection):
l2gw_db.MidonetL2GatewayMixin.delete_l2_gateway_connection(
self, context, l2_gateway_connection)
self._get_driver_for_provider(mido_const.MIDONET_L2GW_PROVIDER
).delete_l2_gateway_connection(
context, l2_gateway_connection) | python | 19 | 0.659459 | 79 | 47.079365 | 126 | starcoderdata |
from fractions import Fraction
from hypothesis import given
from hypothesis.strategies import *
from kite.num import Integer, Float, Rational
from .util import rationals, floats_
@given(integers(), floats_())
def test_addition_0(iv, fv):
t = Fraction(iv) + Fraction(fv)
assert Integer(iv).add(Float(fv)) == t
assert Float(fv).add(Integer(iv)) == t
@given(floats_(), rationals())
def test_addition_1(fv, rv):
t = Fraction(fv) + Fraction(*rv)
assert Float(fv).add(Rational(*rv)) == t
assert Rational(*rv).add(Float(fv)) == t
@given(integers(), rationals())
def test_addition_2(iv, rv):
t = Fraction(iv) + Fraction(*rv)
assert Integer(iv).add(Rational(*rv)) == t
assert Rational(*rv).add(Integer(iv)) == t
@given(integers(), floats_(), rationals())
def test_addition_3(iv, fv, rv):
t = Fraction(iv) + Fraction(fv) + Fraction(*rv)
assert Rational(*rv).add(Integer(iv), Float(fv)) == t | python | 11 | 0.658714 | 57 | 25.777778 | 36 | starcoderdata |
import React from "react"
import { Provider, useSelector } from 'react-redux'
import "./App.scss"
import Header from "./layout/Header"
import NpmMetrics from "./npm-metrics"
import Foosball from "./foosball"
import Photos from "./photos/Photos"
import MessageBoard from "./message-board/MessageBoard"
import ConfRoomSchedule from "./conference-room-schedule/ConfRoomSchedule"
import Kudos from "./kudos/KudosContainer"
import configureStore from './store';
export default function App() {
return <Provider store={configureStore()}>
<GridContainer />
}
function FoosballWrapper() {
const isLoggedIn = useSelector(state => state.loggedIn);
return (
<div id="foos" className="box padding">
<Foosball isLoggedIn={isLoggedIn}>
)
}
function KudosWrapper() {
const isLoggedIn = useSelector(state => state.loggedIn);
return (
<div id="kudos">
<Kudos isLoggedIn={isLoggedIn} />
)
}
function MessageBoardWrapper() {
const isLoggedIn = useSelector(state => state.loggedIn);
return (
<div id="message-board" className="box padding">
<MessageBoard isLoggedIn={isLoggedIn} />
)
}
function PhotosWrapper() {
const isLoggedIn = useSelector(state => state.loggedIn);
return (
<div id="photo">
<Photos isLoggedIn={isLoggedIn} />
)
}
export class GridContainer extends React.Component {
componentDidMount() {
(function () {
var mouseTimer = null, cursorVisible = true;
function disappearCursor() {
mouseTimer = null;
document.body.style.cursor = "none";
cursorVisible = false;
}
document.onmousemove = function () {
if (mouseTimer) {
window.clearTimeout(mouseTimer);
}
if (!cursorVisible) {
document.body.style.cursor = "default";
cursorVisible = true;
}
mouseTimer = window.setTimeout(disappearCursor, 5000);
};
})();
}
wrapInId = (id, component) => {
return (
<div id={id} className="box padding">
{component}
)
}
render() {
return (
<div id="container">
<HeaderWrapper />
{this.wrapInId("calendar", <ConfRoomSchedule />)}
<PhotosWrapper />
<FoosballWrapper />
{this.wrapInId("npm", <NpmMetrics />)}
<KudosWrapper />
<MessageBoardWrapper />
)
}
}
export class HeaderWrapper extends React.Component {
render() {
return (
<div id="header">
<Header />
)
}
} | javascript | 22 | 0.616538 | 74 | 20.487603 | 121 | starcoderdata |
R3SurfelObject *
CreateObject(R3SurfelScene *scene,
R3SurfelNode *source_node, const R3SurfelConstraint *constraint,
R3SurfelObject *parent_object, const char *object_name,
R3SurfelNode *parent_node, const char *node_name,
RNBoolean copy_surfels)
{
// Get tree
R3SurfelTree *tree = scene->Tree();
if (!tree) return NULL;
// Get source node
if (!source_node) source_node = tree->RootNode();
// Get parent object
if (!parent_object) parent_object = scene->RootObject();
// Create object
R3SurfelObject *object = new R3SurfelObject(object_name);
if (!object) return NULL;
// Insert object into scene
scene->InsertObject(object, parent_object);
// Check if should copy surfels
if (copy_surfels) {
// Create node
R3SurfelNode *node = CreateNode(scene, source_node, constraint, parent_node, node_name, copy_surfels);
if (!node) return NULL;
// Insert node into object
object->InsertNode(node);
}
else {
// Get surfel tree
R3SurfelTree *tree = scene->Tree();
if (!tree) return NULL;
// Split leaf nodes
RNArray<R3SurfelNode *> nodes;
tree->SplitLeafNodes(source_node, *constraint, &nodes);
if (nodes.IsEmpty()) return NULL;
// Insert nodes satisfying constraint into object
for (int i = 0; i < nodes.NEntries(); i++) {
R3SurfelNode *node = nodes.Kth(i);
R3SurfelObject *old_object = node->Object();
if (old_object) old_object->RemoveNode(node);
object->InsertNode(node);
}
}
// Update properties
object->UpdateProperties();
// Return object
return object;
} | c++ | 12 | 0.665217 | 106 | 26.305085 | 59 | inline |
#ifndef __CBASESOCKET_H__
#define __CBASESOCKET_H__
/**
Comments will be added later on when using CLion
*/
#include "typedefs.h"
class CBaseSocket
{
public:
CBaseSocket(){
s = 0; // descriptor
socket_state = STATE_INIT;
}
virtual ~CBaseSocket() { /* ... */ }
virtual int CreateSocket(void)= 0;
virtual int CloseSocket(void)=0;
virtual int BindSocket(void)=0;
virtual int Send(UINT8 *tx_buf, UINT32 max_buffer_size, UINT32 buf_len)=0;
virtual int Receive(UINT8 *rx_buf, UINT32 max_buffer_size, UINT32 *buf_len)=0;
/**
Socket
*/
void Set(SOCKET value){s = value;}
SOCKET Get(void) const{return s;}
/**
State
*/
void SetState(RUN_STATE state){socket_state = state;}
RUN_STATE GetState(void) const {return socket_state;}
/**
Buffer
*/
private:
SOCKET s; // descriptor
RUN_STATE socket_state;
};
#endif // __CBASESOCKET_H__ | c | 10 | 0.677528 | 79 | 19.72093 | 43 | starcoderdata |
int qr_code_parse(const void * buffer,
size_t line_bits,
size_t line_stride,
size_t line_count,
struct qr_data ** data)
{
/* TODO: more informative return values for errors */
struct qr_bitmap src_bmp;
struct qr_code code;
enum qr_ec_level ec;
int mask;
struct qr_bitstream * data_bits = NULL;
int status;
fprintf(stderr, "parsing code bitmap %lux%lu\n", (unsigned long) line_bits, (unsigned long) line_count);
if (line_bits != line_count
|| line_bits < 21
|| (line_bits - 17) % 4 != 0) {
/* Invalid size */
fprintf(stderr, "Invalid size\n");
return -1;
}
code.version = (line_bits - 17) / 4;
fprintf(stderr, "assuming version %d\n", code.version);
src_bmp.bits = (unsigned char *) buffer; /* dropping const! */
src_bmp.mask = NULL;
src_bmp.stride = line_stride;
src_bmp.width = line_bits;
src_bmp.height = line_count;
if (code.version >= 7 && read_version(&src_bmp) != code.version) {
fprintf(stderr, "Invalid version info\n");
return -1;
}
if (read_format(&src_bmp, &ec, &mask) != 0) {
fprintf(stderr, "Failed to read format\n");
return -1;
}
fprintf(stderr, "detected ec type %d; mask %d\n", ec, mask);
code.modules = qr_bitmap_clone(&src_bmp);
if (code.modules == NULL) {
status = -1;
goto cleanup;
}
qr_mask_apply(code.modules, mask);
qr_layout_init_mask(&code);
data_bits = qr_bitstream_create();
if (data_bits == NULL) {
status = -1;
goto cleanup;
}
status = read_bits(&code, ec, data_bits);
if (status != 0)
goto cleanup;
*data = malloc(sizeof(**data));
if (*data == NULL) {
status = -1;
goto cleanup;
}
(*data)->version = code.version;
(*data)->ec = ec;
(*data)->bits = data_bits;
(*data)->offset = 0;
data_bits = 0;
status = 0;
cleanup:
if (data_bits)
qr_bitstream_destroy(data_bits);
if (code.modules)
qr_bitmap_destroy(code.modules);
return status;
} | c | 11 | 0.467512 | 112 | 28.360465 | 86 | inline |
package core
// Links represents the links available for a Moltin entity
type Links struct {
Self string `json:"self"`
} | go | 7 | 0.751553 | 59 | 22 | 7 | starcoderdata |
node *find_op_node(node* p, char find_op)
{
node * ret; /* node to return */
if(p->com == OPERATOR && p->op == find_op)
ret = p;
else if(p->com == NUMBER)
ret = &NULL_NODE;
else
{
ret = find_op_node(p->lchild, find_op);
if(ret == &NULL_NODE)
ret = find_op_node(p->rchild, find_op);
}
return ret;
} | c | 14 | 0.538922 | 45 | 19.9375 | 16 | inline |
//
// Copyright 2013 PclUnit Contributors
//
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using PclUnit.Run.Attributes;
using PclUnit.Util;
namespace PclUnit.Run
{
internal class DefaultDiscovery : TestFixtureDiscoveryAttribute
{
public override FixtureGenerator Generator
{
get
{
return a => a.GetExportedTypes()
.Select(t => new Fixture(t.GetTopMostCustomAttribute t))
.Where(f => f.Attribute != null);
}
}
}
public class Runner:IJsonSerialize
{
public Runner()
{
Assemblies = new List
Tests = new List
}
protected Runner(string platform):this()
{
Platform = platform;
}
public string Platform { get; set; }
public IList Assemblies { get; set; }
public IList Tests { get; set; }
public void RunAll(Action resultCallBack, TestFilter testFilter = null)
{
testFilter = testFilter ?? new TestFilter();
foreach (var test in Tests)
{
if (!testFilter.ShouldRun(test))
{
test.ParameterSetRelease();
continue;
}
var result = test.Run(Platform);
resultCallBack(result);
}
}
public string ToListJson()
{
return String.Format("{{Platform:\"{1}\", Assemblies:[{0}]}}",
String.Join(",", Assemblies.Select(it => it.ToListJson()).ToArray()), Platform);
}
public string ToItemJson()
{
return ToListJson();
}
public static Runner Create(string platformId, IEnumerable assemblies)
{
var runner = new Runner(platformId);
foreach (var assembly in assemblies)
{
var assemblyMeta = new AssemblyMeta(assembly);
runner.Assemblies.Add(assemblyMeta);
var generators = assembly.GetCustomAttributes(true)
.OfType
generators.Add(new DefaultDiscovery());
foreach (var generator in generators)
{
foreach (var fixture in generator.Generator(assembly))
{
assemblyMeta.Fixtures.Add(fixture);
foreach (var testHarness in fixture.GetHarnesses())
{
int i = 0;
foreach (var constructorSet in fixture.ParameterSets())
{
int j = 0;
constructorSet.Index = i++;
foreach (var testSet in testHarness.ParameterSets())
{
testSet.Index = j++;
var test = new Test(fixture, constructorSet,
testHarness, testSet);
fixture.Tests.Add(test);
runner.Tests.Add(test);
}
}
}
}
}
}
return runner;
}
}
} | c# | 26 | 0.48892 | 114 | 31.240602 | 133 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CRM.Web.Models.Entity
{
public class Account
{
// ID int primary key identity(10000,1) not null,
//OpenID varchar(64) not null default replace(newid(),'-',''),
//UserID int not null ,
//UserName varchar(32) not null,
//[Password] varchar(32) not null,
//CreateTime datetime default getdate(),
//IsEnable bit default 1,
//Remark varchar(1000),
public int ID { get; set; }
public string OpenID { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime CreateTime { get; set; }
public bool IsEnable { get; set; }
public string Remark { get; set; }
public string ReturnUrl { get; set; }
}
} | c# | 8 | 0.617391 | 64 | 29.724138 | 29 | starcoderdata |
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX RS
#include "ob_snapshot_info_manager.h"
#include "share/ob_snapshot_table_proxy.h"
#include "share/schema/ob_schema_utils.h"
#include "lib/mysqlclient/ob_mysql_transaction.h"
#include "ob_rs_event_history_table_operator.h"
using namespace oceanbase::common;
using namespace oceanbase::share;
using namespace oceanbase::share::schema;
namespace oceanbase {
namespace rootserver {
int ObSnapshotInfoManager::init(const ObAddr& self_addr)
{
int ret = OB_SUCCESS;
if (!self_addr.is_valid()) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid argument", K(ret), K(self_addr));
} else {
self_addr_ = self_addr;
}
return ret;
}
int ObSnapshotInfoManager::set_index_building_snapshot(
common::ObMySQLTransaction& trans, const int64_t index_table_id, const int64_t snapshot_ts)
{
int ret = OB_SUCCESS;
ObSqlString sql;
int64_t affected_rows = 0;
int64_t tenant_id = extract_tenant_id(index_table_id);
if (OB_INVALID_ID == index_table_id || snapshot_ts <= 0) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid argument", K(ret), K(index_table_id), K(snapshot_ts));
} else if (OB_FAIL(sql.assign_fmt("UPDATE %s SET BUILDING_SNAPSHOT = %ld WHERE TABLE_ID = %lu AND TENANT_ID = %ld",
OB_ALL_ORI_SCHEMA_VERSION_TNAME,
snapshot_ts,
ObSchemaUtils::get_extract_schema_id(tenant_id, index_table_id),
ObSchemaUtils::get_extract_tenant_id(tenant_id, tenant_id)))) {
LOG_WARN("fail to update index building snapshot", KR(ret), K(index_table_id), K(snapshot_ts));
} else if (OB_FAIL(trans.write(tenant_id, sql.ptr(), affected_rows))) {
LOG_WARN("fail to write sql", KR(ret), K(sql));
} else if (1 != affected_rows && 0 != affected_rows) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("update get invalid affected_rows, should be one or zero", KR(ret), K(affected_rows));
}
return ret;
}
int ObSnapshotInfoManager::acquire_snapshot_for_building_index(
common::ObMySQLTransaction& trans, const ObSnapshotInfo& snapshot, const int64_t index_table_id)
{
int ret = OB_SUCCESS;
ObSnapshotTableProxy snapshot_proxy;
if (!snapshot.is_valid()) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid argument", K(ret), K(snapshot));
} else if (OB_FAIL(set_index_building_snapshot(trans, index_table_id, snapshot.snapshot_ts_))) {
LOG_WARN("fail to set index building snapshot", KR(ret), K(snapshot));
} else if (OB_FAIL(snapshot_proxy.add_snapshot(trans, snapshot))) {
LOG_WARN("fail to add snapshot", K(ret));
}
ROOTSERVICE_EVENT_ADD("snapshot", "acquire_snapshot", K(ret), K(snapshot), K(index_table_id), "rs_addr", self_addr_);
return ret;
}
int ObSnapshotInfoManager::acquire_snapshot(common::ObMySQLTransaction& trans, const ObSnapshotInfo& snapshot)
{
int ret = OB_SUCCESS;
ObSnapshotTableProxy snapshot_proxy;
if (!snapshot.is_valid()) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid argument", K(ret), K(snapshot));
} else if (OB_FAIL(snapshot_proxy.add_snapshot(trans, snapshot))) {
LOG_WARN("fail to add snapshot", K(ret));
}
ROOTSERVICE_EVENT_ADD("snapshot", "acquire_snapshot", K(ret), K(snapshot), "rs_addr", self_addr_);
return ret;
}
int ObSnapshotInfoManager::release_snapshot(common::ObMySQLTransaction& trans, const ObSnapshotInfo& snapshot)
{
int ret = OB_SUCCESS;
ObSnapshotTableProxy snapshot_proxy;
if (!snapshot.is_valid()) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid argument", K(ret), K(snapshot));
} else if (OB_FAIL(snapshot_proxy.remove_snapshot(trans, snapshot))) {
LOG_WARN("fail to remove snapshot", K(ret), K(snapshot));
}
ROOTSERVICE_EVENT_ADD("snapshot", "release_snapshot", K(ret), K(snapshot), "rs_addr", self_addr_);
return ret;
}
int ObSnapshotInfoManager::get_snapshot(common::ObMySQLProxy& proxy, const int64_t tenant_id,
share::ObSnapShotType snapshot_type, const char* extra_info, ObSnapshotInfo& snapshot_info)
{
int ret = OB_SUCCESS;
ObSnapshotTableProxy snapshot_proxy;
if (OB_FAIL(snapshot_proxy.get_snapshot(proxy, tenant_id, snapshot_type, extra_info, snapshot_info))) {
if (OB_ITER_END == ret) {
} else {
LOG_WARN("fail to get snapshot", K(ret));
}
}
return ret;
}
int ObSnapshotInfoManager::get_snapshot(common::ObMySQLProxy& proxy, const int64_t tenant_id,
share::ObSnapShotType snapshot_type, const int64_t snapshot_ts, share::ObSnapshotInfo& snapshot_info)
{
int ret = OB_SUCCESS;
ObSnapshotTableProxy snapshot_proxy;
if (OB_FAIL(snapshot_proxy.get_snapshot(proxy, tenant_id, snapshot_type, snapshot_ts, snapshot_info))) {
if (OB_ITER_END == ret) {
} else {
LOG_WARN("fail to get snapshot", K(ret));
}
}
return ret;
}
int ObSnapshotInfoManager::check_restore_point(
common::ObMySQLProxy& proxy, const int64_t tenant_id, const int64_t table_id, bool& is_exist)
{
int ret = OB_SUCCESS;
is_exist = false;
ObSnapshotTableProxy snapshot_proxy;
if (OB_FAIL(snapshot_proxy.check_snapshot_exist(
proxy, tenant_id, table_id, share::SNAPSHOT_FOR_RESTORE_POINT, is_exist))) {
LOG_WARN("fail to check snapshot exist", K(ret), K(tenant_id), K(table_id));
}
return ret;
}
int ObSnapshotInfoManager::get_snapshot_count(
common::ObMySQLProxy& proxy, const int64_t tenant_id, share::ObSnapShotType snapshot_type, int64_t& count)
{
int ret = OB_SUCCESS;
ObSnapshotTableProxy snapshot_proxy;
if (OB_FAIL(snapshot_proxy.get_snapshot_count(proxy, tenant_id, snapshot_type, count))) {
LOG_WARN("fail to get snapshot count", K(ret), K(tenant_id), K(snapshot_type));
}
return ret;
}
} // namespace rootserver
} // namespace oceanbase | c++ | 20 | 0.697267 | 119 | 38.067901 | 162 | starcoderdata |
package mobiledev.unb.ca.threadinghandlermessages;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class LoadIconTask extends Thread {
private final UIHandler mHandler;
private final Context mContext;
LoadIconTask(Context context) {
mContext = context;
mHandler = new UIHandler();
}
public void run() {
Message message = mHandler.obtainMessage(HandlerMessagesActivity.SET_PROGRESS_BAR_VISIBILITY,
ProgressBar.VISIBLE);
mHandler.sendMessage(message);
int mResId = R.drawable.painter;
final Bitmap tmp = BitmapFactory.decodeResource(mContext.getResources(), mResId);
for (int i = 1; i < 11; i++) {
sleep();
message = mHandler.obtainMessage(HandlerMessagesActivity.PROGRESS_UPDATE, i * 10);
mHandler.sendMessage(message);
}
message = mHandler.obtainMessage(HandlerMessagesActivity.SET_BITMAP, tmp);
mHandler.sendMessage(message);
message = mHandler.obtainMessage(HandlerMessagesActivity.SET_PROGRESS_BAR_VISIBILITY, ProgressBar.INVISIBLE);
mHandler.sendMessage(message);
}
public LoadIconTask setImageView(ImageView imageView) {
mHandler.setImageView(imageView);
return this;
}
public LoadIconTask setProgressBar(ProgressBar progressBar) {
mHandler.setProgressBar(progressBar);
return this;
}
private void sleep() {
try {
int mDelay = 500;
Thread.sleep(mDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class UIHandler extends Handler {
private ImageView mImageView;
private ProgressBar mProgressBar;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HandlerMessagesActivity.SET_PROGRESS_BAR_VISIBILITY: {
mProgressBar.setVisibility((Integer) msg.obj);
break;
}
case HandlerMessagesActivity.PROGRESS_UPDATE: {
mProgressBar.setProgress((Integer) msg.obj);
break;
}
case HandlerMessagesActivity.SET_BITMAP: {
mImageView.setImageBitmap((Bitmap) msg.obj);
break;
}
}
}
void setImageView(ImageView mImageView) {
this.mImageView = mImageView;
}
void setProgressBar(ProgressBar mProgressBar) {
this.mProgressBar = mProgressBar;
}
}
} | java | 16 | 0.619523 | 117 | 29.857143 | 91 | starcoderdata |
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using Dryv.Rules;
namespace Dryv.Translation.Visitors
{
internal class AsyncMethodCallModifier : ExpressionVisitor
{
private readonly TranslationContext translationContext;
private readonly JavaScriptTranslator translator;
private bool disabled;
private DryvCompiledRule rule;
public AsyncMethodCallModifier(JavaScriptTranslator translator, TranslationContext translationContext)
{
this.translator = translator;
this.translationContext = translationContext;
}
public Dictionary<StringBuilder, ParameterExpression> AsyncCalls { get; set; } = new Dictionary<StringBuilder, ParameterExpression>();
public TExpression ApplyPromises rule, TExpression expression)
where TExpression : Expression
{
this.rule = rule;
return (TExpression)this.Visit(expression);
}
protected override Expression VisitConditional(ConditionalExpression node)
{
this.disabled = true;
return base.VisitConditional(node);
}
protected override Expression VisitMethodCall(MethodCallExpression expression)
{
if (this.disabled)
{
return expression;
}
var sb = new StringBuilder();
var context = this.translationContext.Clone
context.IsAsync = false;
this.translator.Translate(expression, context);
if (!context.IsAsync)
{
return expression;
}
this.rule.IsAsync = true;
var parameter = Expression.Parameter(expression.Type, context.GetVirtualParameter());
this.AsyncCalls.Add(sb, parameter);
return parameter;
}
}
} | c# | 16 | 0.638847 | 142 | 30.396825 | 63 | starcoderdata |
import { importJWK } from '../key/import.js';
async function parseJwk(jwk, alg, octAsKeyObject) {
return importJWK(jwk, alg, octAsKeyObject);
}
export { parseJwk };
export default parseJwk; | javascript | 5 | 0.745968 | 53 | 34.428571 | 7 | starcoderdata |
<?php
/**
* 更多可以研究 入口文件 中的 app->run() 源码,trigger(self::EVENT_AFTER_REQUEST)+trigger(AFTER)
* @author 44533
* 订阅者!
*/
namespace app\controllers;
use yii\web\Controller;
use yii\base\Event;
use vendor\animal\Cat;
use vendor\animal\Mouse;
use vendor\animal\Dog;
use app\behaviors\Behavior1;
/**
* 事件机制 的应用场景
*/
class AnimalController extends Controller
{
/**
* 事件触发机制I
*/
public function actionIndex()
{
//实例化猫和老鼠
$cat = new Cat;
$mouse = new Mouse;
//在控制器里
//绑定事件(为猫的某些个事件,绑定若干其它类方法~如老鼠跑等)
$cat->on('miao', [$mouse, 'run']); //on方法来自继承的Component父类[第一个参数是指绑定什么事件如miao;第二个参数是要做什么;]
//猫叫一下(触发事件)
$cat->shout(); //将触发miao事件!(导致上边的绑定:老鼠run!!)
}
/**
* 事件触发机制II - 类级别的‘监听’!!
*/
public function actionIndex2()
{
//实例化猫和老鼠
$cat = new Cat;
$cat2 = new Cat; //只有是类级别的 Event::on(定义的事件绑定!) 才能让cat2触发miao~
$mouse = new Mouse;
//在控制器里
//绑定事件(为猫的某些个事件,绑定若干其它类方法~如老鼠跑等)
Event::on(Cat::className(), 'miao', [$mouse, 'run']); //on方法来自继承的Component父类[第一个参数是指绑定什么事件如miao;第二个参数是要做什么;]
//猫叫一下(触发事件)
$cat->shout(); //将触发miao事件!(导致上边的绑定:老鼠run!!)
$cat2->shout(); //类级别的监听,所以cat2对象依然可以触发事件 miao!~
}
/**
* 事件触发机制III - $app事件捕捉!(非类级别的‘监听’!!)
* 【$app 也是继承自 Compenent 组件类,所以也有 on 方法。】
*/
public function actionIndex3()
{
//实例化猫
$cat = new Cat;
//先定义
//$app 的处理请求,前后都触发了事件!如何监听之
\YII::$app->on(\yii\base\Application::EVENT_AFTER_ACTION, [$cat, 'shout']); // app 事件带动了 猫叫,猫叫又带动了老鼠跑路。。。(联动机制!)
//后定义(整个app请求结束后)
//定义老鼠 随猫联动~
$mouse = new Mouse;
$cat->on('miao', [$mouse, 'run']);
//此echo仍在 app 的整个请求之中(参照物)
echo 'Hello index3 action...
}
/**
* MixIn注入(新属性)机制 之 行为【类的混合】
*/
public function actionDogmixin()
{
//实例化猫
$dog = new Dog();
$dog->look();
$dog->eat(); //Component父类,提供了事件机制的on;以及Mixin机制的行为注入;
//触发wang事件
$dog->trigger('wang');
}
/**
* MixIn注入(新属性)机制 之 行为【对象的混合】
* 将某些个对象的属性,注入另一个对象中使用!
*/
public function actionDogmixin2()
{
//实例化猫
$dog = new Dog();
$behavior1 = new Behavior1(); //行为的对象
$dog->attachBehavior('beh1', $behavior1);
$dog->eat(); //
}
} | php | 13 | 0.513173 | 124 | 22.546296 | 108 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.