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 |
---|---|---|---|---|---|---|---|
operators.c
// Bitwise Operations
// For More: 1) http://graphics.stanford.edu/~seander/bithacks.html
// 2) http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/
<< left shift (equivalent to multiplication by 2)
>> right shift (equivalent to division by 2)
/*
Example:
unsigned short i, j;
i = 13 (binary 0000000000001101)
j = i << 2 (binary 0000000000110100) (equal to 52) (i.e. multiply by 2 two times)
j = i >> 2 (binary 0000000000000011) (equal to 3) (i.e. divide by 2 two times 13/4 == 3)
// Note: Shifting is much faster than actual multiplication or division.
Note: i >>= 2 is same as i = i >> 2,
i <<= 2 is same as i = i << 2
*/
/** WARNING ** -- Beware of shift like this: **/
a << -5
// What does it mean? It is undefined. (on some machine it shift left 27 bits). So avoid this
~ unary operator (bitwise complement)
& bitwise and
^ bitwise exclusive or (XOR)
| bitwise inclusive or (OR) (PIPE)
// `~` operator produces the complement of its operand, with zeros replaced by ones and ones replaced by zeros.
// `&` operator performs boolean `and` operation on all corresponding bits in its two operands.
// `^` and `|` operators are similar (both performs a Boolean `or` operation on the bits in their operands);
// however, `^` produces 0 whenever both operands have a `1` bit, whereas `|` produces 1.
/*
Example:
0 ^ 0 = 0; 0 | 0 = 0;
0 ^ 1 = 1; 0 | 1 = 1;
1 ^ 0 = 1; 1 | 0 = 1;
1 ^ 1 = 0; 1 | 1 = 1;
*/
// Also note that these boolean bitwise operators checks on both operands not on single operands.
// (i.e. in the case of a || b, it checks for one of a or b, but in case of a | b, it checks for both a and b)
/* example */
unsigned short i, j, k;
i = 21; // (binary : 0000000000010101)
j = 56; // (binary : 0000000000111000)
k = ~i; // k is now 65514 (binary : 1111111111101010)
k = i & j; // k is now 16 (binary : 0000000000010000)
k = i ^ j; // k is now 45 (binary : 0000000000101101)
k = i | j; // k is now 61 (binary : 0000000000111101)
Precedence
Highest ~
&
^
Lowest |
/**
* -------------------- Important tricks ----------------------
*/
/**
* Sometimes, you see the constant define as
* 0100, 0200, 0400 -- these are 64, 128, 256 in decimal (by converting from octal to decimal)
*/
|
c
| 13 | 0.616576 | 111 | 34.147059 | 68 |
starcoderdata
|
using Microsoft.EntityFrameworkCore;
using SimpleFormsService.Domain.Entities;
using SimpleFormsService.Domain.Repositories;
namespace SimpleFormsService.Persistence.Repositories
{
internal sealed class FormSubmissionRepository : RepositoryBase IFormSubmissionRepository
{
private readonly SimpleFormsServiceDbContext _dbContext;
public FormSubmissionRepository(SimpleFormsServiceDbContext dbContext) : base(dbContext) => _dbContext = dbContext;
public async Task GetFormSubmissionByIdAsync(string id, CancellationToken cancellationToken = default)
{
var formSubmission = await _dbContext.FormSubmissions
.Where(x => x.Id.ToString() == id)
.SingleOrDefaultAsync(cancellationToken: cancellationToken);
return formSubmission;
}
public async Task GetFormSubmissionByIdTemplateIdAsync(string id, string templateId, CancellationToken cancellationToken = default)
{
var formSubmission = await _dbContext.FormSubmissions
.Where(x => x.Id.ToString() == id)
.Where(x => x.TemplateId.ToString() == templateId)
.SingleOrDefaultAsync(cancellationToken: cancellationToken);
return formSubmission;
}
public async Task GetFormSubmissionsByTemplateIdAsync(string templateId, CancellationToken cancellationToken = default)
{
var formSubmissions = await _dbContext.FormSubmissions
.Where(x => x.TemplateId.ToString() == templateId)
.ToListAsync(cancellationToken: cancellationToken);
return formSubmissions;
}
}
}
|
c#
| 24 | 0.696418 | 155 | 41.926829 | 41 |
starcoderdata
|
def __init__(self, config):
# call the super constructor
Device.__init__(self, config)
self._device_type = "air_conditioner_simple"
self._device_name = config.get("device_name", "air_conditioner_simple")
# maximim power output, default to 500 W if no value given
self._max_power_output = config.get("max_power_output", 500.0)
self._current_temperature = config.get("current_temperature", 25.0)
self._temperature_max_delta = config.get("temperature_max_delta", 0.5)
self._set_point = config.get("set_point", 23.0)
self._setpoint_reassesment_interval = config.get("setpoint_reassesment_interval", 60.0 * 10.0) # 10 mins.
# create the function that gives the set point from the current price of fuel
# this will be changed on init() if there's a price schedule present
self.get_set_point_from_price = lambda: self._set_point
# precooling configuration
precooling_config = config.get("precooling", {})
self._precooling_enabled = precooling_config.get("enabled", False)
# if set, any price below the threshold will start precooling
# if set to None then precooling would always be enabled
self._precooling_price_threshold = precooling_config.get("price_threshold", None)
# sum the total energy used
self._total_energy_use = 0.0
self._last_total_energy_update_time = 0
# holds the raw set point schedule
self._set_point_schedule = None
if type(config) is dict and config.has_key("set_point_schedule") and type(config["set_point_schedule"]) is list:
self._set_point_schedule = config["set_point_schedule"]
self._temperature_hourly_profile = None
self._temperature_file_name = "weather_5_secs.json"
self._current_outdoor_temperature = None
self._temperature_update_interval = 60.0 * 5.0 # every 10 minutes?
self._last_temperature_update_time = 0.0 # the time the last internal temperature update occured
# rate at which the indoor temperature changes due to the compressor being on
# units are C/hr
self._temperature_change_rate_hr_comp = config.get("temperature_change_rate_hr_comp", 2.0)
# rate at which the indoor temperature changes due to the outside air (oa)
self._temperature_change_rate_hr_oa = config.get("temperature_change_rate_hr_oa", 0.1)
# keep track of the compressor operation on/off
self._compressor_is_on = False
|
python
| 10 | 0.661944 | 120 | 49.84 | 50 |
inline
|
<?php
class KEditor extends CWidget{
/*
* TEXTAREA输入框的属性,保证js调用KE失败时,文本框的样式。
*/
public $textareaOptions=array();
/*
* 编辑器属性集。
*/
public $properties=array();
/*
* TEXTAREA输入框的name,必须设置。
* 数据类型:String
*/
public $name;
/*
* TEXTAREA的id,可为空
*/
public $id;
public $model;
public $baseUrl;
public static function getUploadPath(){
$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
if(isset(Yii::app()->params->uploadPath)){
return Yii::getPathOfAlias('webroot').str_replace(
'/',DIRECTORY_SEPARATOR,
Yii::app()->params->
uploadPath);
}
return Yii::app()->getAssetmanager()
->getPublishedPath($dir).DIRECTORY_SEPARATOR.'upload';
}
public static function getUploadUrl(){
$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
if(isset(Yii::app()->params->uploadPath)){
return Yii::app()->baseUrl.Yii::app()->params->uploadPath;
}
return Yii::app()->getAssetManager()->publish($dir).'/upload';
}
public function init(){
if($this->name===null)
throw new CException(Yii::t('zii','The id property cannot be empty.'));
$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
$this->baseUrl=Yii::app()->getAssetManager()->publish($dir);
$cs=Yii::app()->getClientScript();
$cs->registerCssFile($this->baseUrl.'/themes/default/default.css');
if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.'/kindeditor.js');
else $cs->registerScriptFile($this->baseUrl.'/kindeditor-min.js');
}
public function run(){
$cs=Yii::app()->getClientScript();
$textAreaOptions=$this->gettextareaOptions();
$textAreaOptions['name']=CHtml::resolveName($this->model,$this->name);
$this->id=$textAreaOptions['id']=CHtml::getIdByName($textAreaOptions['name']);
echo CHtml::activeTextArea($this->model,$this->name,$textAreaOptions);
$properties_string = CJavaScript::encode($this->getKeProperties());
$js=<<<EOF
KindEditor.ready(function(K) {
var editor_$this->id = K.create('#$this->id',
$properties_string
);
});
EOF;
$cs->registerScript('KE'.$this->name,$js,CClientScript::POS_HEAD);
}
public function gettextareaOptions(){
//允许获取的属性
$allowParams=array('rows','cols','style');
//准备返回的属性数组
$params=array();
foreach($allowParams as $key){
if(isset($this->textareaOptions[$key]))
$params[$key]=$this->textareaOptions[$key];
}
$params['name']=$params['id']=$this->name;
return $params;
}
public function getKeProperties(){
$properties_key=array(
'width',
'height',
'minWidth',
'minHeight',
'items',
'noDisableItems',
'filterMode',
'htmlTags',
'wellFormatMode',
'resizeType',
'themeType',
'langType',
'designMode',
'fullscreenMode',
'basePath',
'themesPath',
'pluginsPath',
'langPath',
'minChangeSize',
'urlType',
'newlineTag',
'pasteType',
'dialogAlignType',
'shadowMode',
'useContextmenu',
'syncType',
'indentChar',
'cssPath',
'cssData',
'bodyClass',
'colorTable',
'afterCreate',
'afterChange',
'afterTab',
'afterFocus',
'afterBlur',
'afterUpload',
'uploadJson',
'fileManagerJson',
'allowPreviewEmoticons',
'allowImageUpload',
'allowFlashUpload',
'allowMediaUpload',
'allowFileUpload',
'allowFileManager',
'fontSizeTable',
'imageTabIndex',
'formatUploadUrl',
'fullscreenShortcut',
'extraFileUploadParams',
);
//准备返回的属性数组
$params=array();
foreach($properties_key as $key){
if(isset($this->properties[$key]))
$params[$key]=$this->properties[$key];
}
return $params;
}
}
|
php
| 16 | 0.620985 | 80 | 22.592105 | 152 |
starcoderdata
|
package optifine;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.settings.GameSettings;
import shadersmod.client.GuiButtonShaderOption;
import shadersmod.client.ShaderOption;
import shadersmod.client.ShaderOptionProfile;
public class TooltipProviderShaderOptions extends TooltipProviderOptions
{
public String[] getTooltipLines(GuiButton p_getTooltipLines_1_, int p_getTooltipLines_2_)
{
if (!(p_getTooltipLines_1_ instanceof GuiButtonShaderOption))
{
return null;
}
else
{
GuiButtonShaderOption guibuttonshaderoption = (GuiButtonShaderOption)p_getTooltipLines_1_;
ShaderOption shaderoption = guibuttonshaderoption.getShaderOption();
String[] astring = this.makeTooltipLines(shaderoption, p_getTooltipLines_2_);
return astring;
}
}
private String[] makeTooltipLines(ShaderOption p_makeTooltipLines_1_, int p_makeTooltipLines_2_)
{
if (p_makeTooltipLines_1_ instanceof ShaderOptionProfile)
{
return null;
}
else
{
String s = p_makeTooltipLines_1_.getNameText();
String s1 = Config.normalize(p_makeTooltipLines_1_.getDescriptionText()).trim();
String[] astring = this.splitDescription(s1);
GameSettings gamesettings = Config.getGameSettings();
String s2 = null;
if (!s.equals(p_makeTooltipLines_1_.getName()) && gamesettings.advancedItemTooltips)
{
s2 = "\u00a78" + Lang.get("of.general.id") + ": " + p_makeTooltipLines_1_.getName();
}
String s3 = null;
if (p_makeTooltipLines_1_.getPaths() != null && gamesettings.advancedItemTooltips)
{
s3 = "\u00a78" + Lang.get("of.general.from") + ": " + Config.arrayToString((Object[])p_makeTooltipLines_1_.getPaths());
}
String s4 = null;
if (p_makeTooltipLines_1_.getValueDefault() != null && gamesettings.advancedItemTooltips)
{
String s5 = p_makeTooltipLines_1_.isEnabled() ? p_makeTooltipLines_1_.getValueText(p_makeTooltipLines_1_.getValueDefault()) : Lang.get("of.general.ambiguous");
s4 = "\u00a78" + Lang.getDefault() + ": " + s5;
}
List list = new ArrayList();
list.add(s);
list.addAll(Arrays.
if (s2 != null)
{
list.add(s2);
}
if (s3 != null)
{
list.add(s3);
}
if (s4 != null)
{
list.add(s4);
}
String[] astring1 = this.makeTooltipLines(p_makeTooltipLines_2_, list);
return astring1;
}
}
private String[] splitDescription(String p_splitDescription_1_)
{
if (p_splitDescription_1_.length() <= 0)
{
return new String[0];
}
else
{
p_splitDescription_1_ = StrUtils.removePrefix(p_splitDescription_1_, "//");
String[] astring = p_splitDescription_1_.split("\\. ");
for (int i = 0; i < astring.length; ++i)
{
astring[i] = "- " + astring[i].trim();
astring[i] = StrUtils.removeSuffix(astring[i], ".");
}
return astring;
}
}
private String[] makeTooltipLines(int p_makeTooltipLines_1_, List p_makeTooltipLines_2_)
{
FontRenderer fontrenderer = Config.getMinecraft().fontRendererObj;
List list = new ArrayList();
for (int i = 0; i < p_makeTooltipLines_2_.size(); ++i)
{
String s = (String)p_makeTooltipLines_2_.get(i);
if (s != null && s.length() > 0)
{
for (String s1 : fontrenderer.listFormattedStringToWidth(s, p_makeTooltipLines_1_))
{
list.add(s1);
}
}
}
String[] astring = (String[])((String[])list.toArray(new String[list.size()]));
return astring;
}
}
|
java
| 17 | 0.559935 | 175 | 32.369231 | 130 |
starcoderdata
|
package com.hwy.shipyard.mapper;
import com.hwy.shipyard.dataobject.Ship;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface ShipMapper {
@Select("select * from ship_info")
List getAllShip();
@Select("select count(*) as count from ship_info")
Integer getCount();
@Select("select * from ship_info where ship_name = #{shipName}")
Ship getShipByName(@Param("shipName") String shipName);
@Select("SELECT * FROM user WHERE ship_imo_number = #{shipImoNumber}")
Ship getShipByIMO(@Param("shipImoNumber") String shipImoNumber);
@Insert("insert into ship_info values (#{shipImoNumber}," +
"#{shipName},#{shipType},#{shipRegistration},#{shipNumber}," +
"#{shipCallSign},#{shipGrade},#{shipRoute},#{shipField0}," +
"#{shipField1},#{shipField2},#{shipField3})")
void addShip(Ship ship);
@Delete("delete from ship_info where ship_imo_number = #{shipImoNumber}")
void delShip(String shipId);
@Update("update ship_info set ship_type=#{shipType}," +
"ship_registration=#{shipRegistration}," +
"ship_name=#{shipName}," +
"ship_number=#{shipNumber}," +
"ship_callsign=#{shipCallSign}," +
"ship_grade=#{shipGrade}," +
"ship_route=#{shipRoute}," +
"ship_field0=#{shipField0}," +
"ship_field1=#{shipField1}," +
"ship_field2=#{shipField2}," +
"ship_field3=#{shipField3} " +
"where ship_imo_number=#{shipImoNumber}")
void update(Ship ship);
}
|
java
| 19 | 0.610063 | 77 | 34.333333 | 45 |
starcoderdata
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using Fusion.Resources.Database.Authentication;
using Fusion.Resources.Database;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using System.Data.Common;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace Microsoft.Extensions.DependencyInjection
{
public static class DatabaseConfigurationExtensions
{
public static IServiceCollection AddResourceDatabase IServiceCollection services, IConfiguration configuration)
where TTokenProvider : class, ISqlTokenProvider
{
var connectionString = configuration.GetConnectionString(nameof(ResourcesDbContext));
string migrationAssemblyName = Assembly.GetExecutingAssembly().FullName!;
services.AddDbContext => {
// Connection string is handled by auth manager.
options.UseSqlServer(setup => setup.MigrationsAssembly(migrationAssemblyName));
});
services.AddSingleton<ISqlAuthenticationManager, AzureTokenAuthenticationManager>();
services.AddScoped<ITransactionScope, EFTransactionScope>();
services.AddSingleton<ISqlTokenProvider, TTokenProvider>();
return services;
}
public static DbContextOptionsBuilder UseSqlServer(this DbContextOptionsBuilder optionsBuilder, Action sqlServerOptionsAction = null)
{
sqlServerOptionsAction?.Invoke(new SqlServerDbContextOptionsBuilder(optionsBuilder));
return optionsBuilder;
}
}
}
|
c#
| 21 | 0.776657 | 176 | 41.489796 | 49 |
starcoderdata
|
window.exports = getQuantity = (e, input) => {
// Quantity items Products
const isNumber = (val) => {
val = parseInt(val);
return ((typeof val === "number") && (!isNaN(val)) && (val !== 0)) ? val : 1;
}
((e, input) => {
const form = input.closest('form');
const btn = form.querySelector('button.btn-add');
const cart = form.closest('.cart__product');
if (e.classList.contains("product-qty__plus")) {
const preload = GetPreload({
'wrap': input,
'class': 'lds-dual-ring'
});
input.value = isNumber(input.value) + 1; // add to cart axios
xmlHttpRequest(form.action, {inc: "++"}, (data) => {
refreshCart(data.cartItemTotalSum, data.cartTotalSum, data.cartCount, cart);
preload.remove();
flash(data.dataMsg.message, data.dataMsg.status);
if (data.dataMsg.status === 'info') {
underOrder(data.dataMsg, form);
} else {
underOrder(null, form);
}
});
} else if (e.classList.contains("product-qty__minus")) {
if (input.value > 1) {
const preload = GetPreload({
'wrap': input,
'class': 'lds-dual-ring'
});
input.value = isNumber(input.value) - 1; // add to cart axios
xmlHttpRequest(form.action, {inc: "--"}, (data) => {
refreshCart(data.cartItemTotalSum, data.cartTotalSum, data.cartCount, cart);
preload.remove();
flash(data.dataMsg.message, data.dataMsg.status);
if (data.dataMsg.status === 'info') {
underOrder(data.dataMsg, form);
} else {
underOrder(null, form);
}
});
} else {
if (!btn)
return;
btn.classList.remove('btn-hide');
}
}
input.addEventListener("input", function (e) {
input.value = isNumber(input.value);
const preload = GetPreload({
'wrap': input,
'class': 'lds-dual-ring'
});
xmlHttpRequest(form.action, input.value, (data) => {
preload.remove();
}); // add to cart axios
});
})(e, input);
}
|
javascript
| 26 | 0.459343 | 96 | 37.757576 | 66 |
starcoderdata
|
let $dom;
let sensor;
before(function() {
$('body').append(
'<div id="ResizeSensor" style="width: 200px; height: 100px;">
);
$dom = $('#ResizeSensor');
sensor = new ResizeSensor($dom[0]);
sensor = new ResizeSensor($dom[0]);
});
after(function() {
sensor.destroy();
sensor.destroy();
$dom.remove();
});
it('detect resize', function(done) {
let i = 0;
sensor.addListener(function() {
i++;
});
$dom.css('width', 100);
setTimeout(() => {
expect(i).to.be.above(0);
done();
}, 100);
});
it('no resize', function(done) {
let i = 0;
sensor.addListener(function() {
i++;
});
$dom.css('width', 100);
setTimeout(() => {
expect(i).to.equal(0);
done();
}, 100);
});
|
javascript
| 18 | 0.5025 | 76 | 18.512195 | 41 |
starcoderdata
|
package com.javarush.test.level18.lesson08.task04;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/* UnsupportedFileName
Измените класс TxtInputStream так, чтобы он работал только с txt-файлами (*.txt)
Например, first.txt или name.1.part3.txt
Если передан не txt-файл, например, file.txt.exe, то конструктор должен выбрасывать исключение UnsupportedFileNameException
*/
public class TxtInputStream extends FileInputStream {
public TxtInputStream(String fileName) throws FileNotFoundException, UnsupportedFileNameException
{
super(fileName);
if (!fileName.endsWith(".txt"))
throw new UnsupportedFileNameException();
}
}
|
java
| 11 | 0.772595 | 123 | 33.3 | 20 |
starcoderdata
|
auto foeGfxVkDescriptorSetLayoutPool::get(
VkDescriptorSetLayoutCreateInfo const *pDescriptorSetLayoutCI) -> VkDescriptorSetLayout {
std::scoped_lock lock{mSync};
// Check if we already have this layout
for (auto const &it : mLayouts) {
if (pDescriptorSetLayoutCI->bindingCount != it.layoutCI.bindingCount ||
pDescriptorSetLayoutCI->flags != it.layoutCI.flags)
continue;
bool same{true};
for (uint32_t i = 0; i < it.layoutCI.bindingCount; ++i) {
if (!compare_VkDescriptorSetLayoutBinding(pDescriptorSetLayoutCI->pBindings[i],
it.layoutBindings[i])) {
same = false;
break;
}
}
if (same)
return it.layout;
}
FOE_LOG(foeVkGraphics, Verbose, "Creating a new DescriptorSetLayout");
VkDescriptorSetLayout newLayout;
std::error_code errc =
vkCreateDescriptorSetLayout(mDevice, pDescriptorSetLayoutCI, nullptr, &newLayout);
if (errc) {
FOE_LOG(foeVkGraphics, Error, "vkCreateDescriptorSetLayout failed with error: {}",
errc.message());
return VK_NULL_HANDLE;
}
Layout newEntry{
.layout = newLayout,
.layoutCI = *pDescriptorSetLayoutCI,
};
for (uint32_t i = 0; i < pDescriptorSetLayoutCI->bindingCount; ++i) {
newEntry.layoutBindings.emplace_back(pDescriptorSetLayoutCI->pBindings[i]);
}
mLayouts.emplace_back(std::move(newEntry));
return newLayout;
}
|
c++
| 14 | 0.615974 | 93 | 32.319149 | 47 |
inline
|
/*
* 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.dtstack.flink.sql.table;
import com.dtstack.flink.sql.util.ClassUtil;
import com.dtstack.flink.sql.util.DtStringUtil;
import org.apache.flink.calcite.shaded.com.google.common.collect.Lists;
import org.apache.flink.shaded.curator.org.apache.curator.shaded.com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Reason:
* Date: 2018/7/4
* Company: www.dtstack.com
* @author xuchao
*/
public abstract class AbsTableParser {
private static final String PRIMARY_KEY = "primaryKey";
private static Pattern primaryKeyPattern = Pattern.compile("(?i)PRIMARY\\s+KEY\\s*\\((.*)\\)");
public static Map<String, Pattern> keyPatternMap = Maps.newHashMap();
public static Map<String, ITableFieldDealHandler> keyHandlerMap = Maps.newHashMap();
static {
keyPatternMap.put(PRIMARY_KEY, primaryKeyPattern);
keyHandlerMap.put(PRIMARY_KEY, AbsTableParser::dealPrimaryKey);
}
protected boolean fieldNameNeedsUpperCase() {
return true;
}
public abstract TableInfo getTableInfo(String tableName, String fieldsInfo, Map<String, Object> props) throws Exception;
public boolean dealKeyPattern(String fieldRow, TableInfo tableInfo){
for(Map.Entry<String, Pattern> keyPattern : keyPatternMap.entrySet()){
Pattern pattern = keyPattern.getValue();
String key = keyPattern.getKey();
Matcher matcher = pattern.matcher(fieldRow);
if(matcher.find()){
ITableFieldDealHandler handler = keyHandlerMap.get(key);
if(handler == null){
throw new RuntimeException("parse field [" + fieldRow + "] error.");
}
handler.dealPrimaryKey(matcher, tableInfo);
return true;
}
}
return false;
}
public void parseFieldsInfo(String fieldsInfo, TableInfo tableInfo){
String[] fieldRows = DtStringUtil.splitIgnoreQuotaBrackets(fieldsInfo, ",");
for(String fieldRow : fieldRows){
fieldRow = fieldRow.trim();
boolean isMatcherKey = dealKeyPattern(fieldRow, tableInfo);
if(isMatcherKey){
continue;
}
String[] filedInfoArr = fieldRow.split("\\s+");
if(filedInfoArr.length < 2){
throw new RuntimeException(String.format("table [%s] field [%s] format error.", tableInfo.getName(), fieldRow));
}
//Compatible situation may arise in space in the fieldName
String[] filedNameArr = new String[filedInfoArr.length - 1];
System.arraycopy(filedInfoArr, 0, filedNameArr, 0, filedInfoArr.length - 1);
String fieldName = String.join(" ", filedNameArr);
String fieldType = filedInfoArr[filedInfoArr.length - 1 ].trim();
Class fieldClass = ClassUtil.stringConvertClass(fieldType);
tableInfo.addField(fieldName);
tableInfo.addFieldClass(fieldClass);
tableInfo.addFieldType(fieldType);
}
tableInfo.finish();
}
public static void dealPrimaryKey(Matcher matcher, TableInfo tableInfo){
String primaryFields = matcher.group(1).trim();
String[] splitArry = primaryFields.split(",");
List primaryKes = Lists.newArrayList(splitArry);
tableInfo.setPrimaryKeys(primaryKes);
}
}
|
java
| 17 | 0.668839 | 128 | 35.726496 | 117 |
starcoderdata
|
public static bool IsValidUKPostcode(string InPostCode, out string PostCode)
{
PostCode = InPostCode.ToUpper();
PostCode = PostCode.Trim();
// remove the space
PostCode = PostCode.Replace(" ", "");
switch (PostCode.Length)
{
case 5:
PostCode = PostCode.Substring(0, 2) + " " + PostCode.Substring(2, 3);
break;
case 6:
PostCode = PostCode.Substring(0, 3) + " " + PostCode.Substring(3, 3);
break;
case 7:
PostCode = PostCode.Substring(0, 4) + " " + PostCode.Substring(4, 3);
break;
}
Regex postcode = new Regex(@"(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?" +
"|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|" +
"R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]" +
"|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2})",
RegexOptions.Singleline);
Match m = postcode.Match(PostCode);
return m.Success;
}
|
c#
| 15 | 0.470189 | 115 | 41.774194 | 31 |
inline
|
public void displaySelectedRows(CyNetwork cyNetwork) {
List<Object> selectedRowKeys = new ArrayList<>();
OVConnection ovCon = this.getConnection(cyNetwork);
if(ovCon == null) {
// The network is not connected to the table, so we display all the rows
this.selectAllRows();
return;
}
CyTable nodeTable = cyNetwork.getDefaultNodeTable();
for(CyNode node : cyNetwork.getNodeList()) {
CyRow nodeRow = nodeTable.getRow(node.getSUID());
if(nodeRow.get(CyNetwork.SELECTED, Boolean.class)) {
List<CyRow> linkedRows = ovCon.getLinkedRows(node);
for(CyRow tableRow : linkedRows) {
selectedRowKeys.add(tableRow.getRaw(OVShared.OVTABLE_COLID_NAME));
}
}
}
this.tableModel.setSelectedRowKeys(selectedRowKeys);
}
|
java
| 15 | 0.71504 | 75 | 32 | 23 |
inline
|
private Properties filterLookupParameters(Properties infraParamList) {
List<String> amiLookupSupportParameters = new ArrayList<>();
Properties lookupParams = new Properties();
//Currently supports OS & JDK only.
//Make this to read params from a external file once there are multiple parameters.
amiLookupSupportParameters.add(AMI_TAG_OS);
amiLookupSupportParameters.add(AMI_TAG_OS_VERSION);
for (String supportParam : amiLookupSupportParameters) {
for (String infraParamType : infraParamList.stringPropertyNames()) {
if (infraParamType.equals(supportParam)) {
lookupParams.setProperty(infraParamType, infraParamList.getProperty(infraParamType));
break;
}
}
}
lookupParams.setProperty(AMI_TAG_AGENT_READY, "true");
return lookupParams;
}
|
java
| 14 | 0.651087 | 105 | 45.05 | 20 |
inline
|
<?php
namespace App\Form;
use App\Form\Services\CommentBuilder;
use Symfony\Component\Form\AbstractType;
use App\Entity\Actuality\ActualityComment;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ActualityCommentsType extends AbstractType
{
private $commentBuilder;
public function __construct(CommentBuilder $commentBuilder)
{
$this->commentBuilder = $commentBuilder;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->commentBuilder->addOptions($builder);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => ActualityComment::class,
]);
}
}
|
php
| 12 | 0.720871 | 76 | 24.193548 | 31 |
starcoderdata
|
#! /usr/bin/env python3
'''
Test X and mR of control_charts.py
time -f '%e' ./control_charts.py
./control_charts.py
'''
import time
from datasense import control_charts as cc
import matplotlib.pyplot as plt
import datasense as ds
import pandas as pd
output_url = 'plot_x_mr_test.html'
header_title = 'plot_x_mr_test'
header_id = 'plot-x-mr-test'
graph_x_file_name = 'plot_x_test.svg'
graph_mr_file_name = 'plot_mr_test.svg'
figsize = (8, 6)
def main():
start_time = time.time()
original_stdout = ds.html_begin(
output_url=output_url,
header_title=header_title,
header_id=header_id
)
data = ds.random_data(
distribution='norm',
size=42,
loc=69,
scale=13
)
data = pd.DataFrame(
data=data,
columns=['X']
)
# print('dtype:', type(data).__name__)
# print(data.head())
# Create X control chart
ds.page_break()
fig = plt.figure(figsize=figsize)
x = cc.X(data=data)
# print('class:', type(x).__name__)
ax = x.ax(fig)
fig.savefig(fname=graph_x_file_name)
ds.html_figure(file_name=graph_x_file_name)
print(
f'X Report\n'
f'============\n'
f'UCL : {x.ucl.round(3)}\n'
f'Xbar : {x.mean.round(3)}\n'
f'LCL : {x.lcl.round(3)}\n'
f'Sigma(X) : {x.sigma.round(3)}\n'
)
# Create mr chart
fig = plt.figure(figsize=figsize)
mr = cc.mR(data=data)
# print('class:', type(x).__name__)
ax = mr.ax(fig)
fig.savefig(fname=graph_mr_file_name)
ds.html_figure(file_name=graph_mr_file_name)
print(
f'mR Report\n'
f'============\n'
f'UCL : {mr.ucl.round(3)}\n'
f'mRbar : {mr.mean.round(3)}\n'
f'LCL : {round(mr.lcl, 3)}\n'
f'Sigma(mR) : {mr.sigma.round(3)}\n'
)
stop_time = time.time()
ds.page_break()
ds.report_summary(
start_time=start_time,
stop_time=stop_time
)
ds.html_end(
original_stdout=original_stdout,
output_url=output_url
)
if __name__ == '__main__':
main()
|
python
| 12 | 0.547842 | 48 | 23.227273 | 88 |
starcoderdata
|
#Caluculate the statrting point and end point of a rotated rectangle from 2 points and degree.
import numpy as np
def calcPos(deg, cx, cy, x, y):
point = np.array([x - cx, y - cy])
#deg = deg * 30
rad = deg * np.pi / 180
rMat = np.array([[np.cos(rad), -np.sin(rad)],[np.sin(rad), np.cos(rad)]])
spin = np.dot(rMat, point)
rx = spin[0]
ry = spin[1]
return int(rx) + cx, int(ry) + cy
def getRotatedRectanglePos(deg, cx, cy, fx, fy, ex, ey, width, height): #Degree, CenterX, CenterY, LeftUpperX, LeftUpperY, RightLowerX, LeftLowerY, Width, Height
deg = deg * -1
x1, y1 = calcPos(deg, cx, cy, fx, fy)
x2, y2 = calcPos(deg, cx, cy, ex, fy)
x3, y3 = calcPos(deg, cx, cy, ex, ey)
x4, y4 = calcPos(deg, cx, cy, fx, ey)
fsx = min(x1, x2, x3, x4)
fsy = min(y1, y2, y3, y4)
esx = max(x1, x2, x3, x4)
esy = max(y1, y2, y3, y4)
if fsx < 0:
fsx = 0
if fsy < 0:
fsy = 0
if esx > width:
esx = width -1
if esy > height:
esy = height - 1
#Calculate the length of width and height from 2 points
xL = abs(esx - fsx)
yL = abs(esy - fsy)
return fsx, fsy, esx, esy, xL, yL #LeftUpperX, LeftUpperY, RightLowerX, LeftLowerY, Width, Height
|
python
| 12 | 0.569697 | 161 | 34.694444 | 36 |
starcoderdata
|
package basic
import "fmt"
type HttpRequestError string
func (h HttpRequestError) Error() string {
return fmt.Sprintf("http request error: %s", string(h))
}
|
go
| 9 | 0.73913 | 56 | 16.888889 | 9 |
starcoderdata
|
def get_streams(name=None, url=None, parser=None, db_name=None, is_dynamic=False, places=all_places):
""" Load the streams from some media.
If database support is set, this will be the only place where
streams will be searched. Only if the database is still not
populated, other places will be searched.
Execution order:
- DB (populated from any subsequent media)
- Cache (populated from "External URL" only)
- External URL
- Fallback file
"""
tmp = config.get('cache', 'dir')
cached_data = None
if Place.db in places:
content = _get_from_db(db_name)
if content:
return content
if Place.cache in places:
basename = path.basename(name)
tmp = path.join(tmp, basename)
valid_for = config.getint('cache', 'valid_for')
try:
cached_data = _get_from_file(tmp)
if time.time() - path.getmtime(tmp) < valid_for:
populate_database(db_name, cached_data)
return cached_data
except IOError:
pass
except Exception as e:
show.error("Error when loading streams data from cache:", repr(e))
if Place.url in places:
try:
save = None
if Place.cache in places:
save = tmp
url_data = _get_from_url(url, parser, save=save)
populate_database(db_name, url_data)
return url_data
except Exception as e:
show.error("Error when loading streams data from web:", repr(e))
if cached_data:
warnings.warn('Using possibly outdated cache for %r provider '
'because no other source was available' % name)
return cached_data
if Place.file in places:
if len(places) > 1: # Any other place should have higher priority
warnings.warn('Using locally stored data %r for provider '
'as last resort.' % path.basename(name))
file_data = _get_from_file(path.join(dirname, name))
populate_database(db_name, file_data)
return file_data
if is_dynamic:
# The database may be populated later
return []
raise ValueError('Could not load stream from: %s' %
[x.name for x in places])
|
python
| 13 | 0.580247 | 101 | 34.606061 | 66 |
inline
|
Viewer/app/src/main/java/com/example/markus/mediadbviewer/PreviewScrollView.java
package com.example.markus.mediadbviewer;
import android.content.Context;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
/**
* Created by markus on 10.02.16.
*/
public class PreviewScrollView extends ScrollView{
private int currentStartX = 0;
private int startX = 0;
private int currentDistance = 0;
private int distance = 0;
private MainActivity activity;
private String imdbID;
private int dimension;
private boolean preview = false;
private int width;
private LinearLayout parent;
private ListView list;
public void setActivity(MainActivity activity) {
this.activity = activity;
Point size = new Point();
this.activity.getWindowManager().getDefaultDisplay().getSize(size);
this.width = size.x;
}
public void setPreview() {
this.preview = true;
this.parent = (LinearLayout) this.getParent().getParent();
this.list = (ListView) ((ViewGroup) this.parent.getParent()).findViewById(android.R.id.list);
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public void setDimension(int dimension) {
this.dimension = dimension;
}
public PreviewScrollView(Context context) {
super(context);
}
public PreviewScrollView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public PreviewScrollView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent (MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onDragEvent(DragEvent event) {
Log.d("Dragged", "");
return super.onDragEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (this.preview) {
int x = (int) event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = x;
currentStartX = x;
currentDistance = 0;
break;
case MotionEvent.ACTION_MOVE:
currentDistance = currentStartX - x;
distance = startX -x;
if (currentDistance > 0 && distance > 75) {
this.currentStartX = x;
/*
if (this.parent.getLayoutParams().width == 0) {
this.parent.setLayoutParams(new LinearLayout.LayoutParams((this.width / 2), LinearLayout.LayoutParams.MATCH_PARENT));
}
*/
//this.parent.getLayoutParams() += currentDistance;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(this.width/2, LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(this.distance,0,0,0);
this.parent.setLayoutParams(params);
this.parent.requestLayout();
}
break;
case MotionEvent.ACTION_UP:
if (this.distance > (0.45 * this.width)) {
MovieDetailedFragment fragment = new MovieDetailedFragment();
fragment.setImdbID(this.imdbID);
fragment.setDimensions(this.dimension);
this.activity.getSupportFragmentManager().beginTransaction().replace(R.id.mainContent, fragment, "movieDetailedFragment").addToBackStack("movieDetailedFragment").commit();
}
if (parent.getLayoutParams().width != 0) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(this.width/2, LinearLayout.LayoutParams.MATCH_PARENT);
parent.setLayoutParams(params);
//parent.getLayoutParams().width = this.width/2;
parent.requestLayout();
}
break;
}
}
return true;
}
}
|
java
| 17 | 0.596809 | 195 | 33.057971 | 138 |
starcoderdata
|
public static void Shake(View viewToAnimate, Runnable onAnimationStart, Runnable onAnimationEnd)
{
// Create the animation set
AnimationSet animationSet = new AnimationSet(true);
animationSet.setInterpolator(new CycleInterpolator(3)); // Repeat 3 times
// Create movement
TranslateAnimation shake = new TranslateAnimation(0, ScreenMetrics.ConvertDipToPx(viewToAnimate.getContext(), 3), 0, 0);
shake.setDuration(600);
animationSet.addAnimation(shake);
// Run the animation:
Animate(viewToAnimate, animationSet, onAnimationStart, onAnimationEnd);
}
|
java
| 11 | 0.783451 | 122 | 39.642857 | 14 |
inline
|
using RPSLS.Game.Client.Models;
namespace RPSLS.Game.Client.Services
{
public abstract class GameService
{
public string Username { get; set;}
public bool IsTwitterUser { get; set; }
public int Pick { get; set; }
public ChallengerDto Challenger { get; set; }
public ResultDto GameResult { get; set; }
}
}
|
c#
| 8 | 0.633333 | 53 | 24.714286 | 14 |
starcoderdata
|
package com.velasteguicorps.analisisconexiones.Model;
/**
*
* @author luis
*/
public interface Controller {
void setOutput(String out);
}
|
java
| 6 | 0.677419 | 53 | 15.222222 | 9 |
starcoderdata
|
package cn.jbone.sys.dao.repository;
import cn.jbone.sys.dao.domain.RbacOrganizationEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface RbacOrganizationRepository extends JpaRepository {
List findByPid(int pid);
List findByIdIn(int[] ids);
}
|
java
| 8 | 0.840948 | 148 | 35.9375 | 16 |
starcoderdata
|
def choose_load_pose(self, message="Load Pose"):
"""
Loads a Pose through the tk File Dialog
"""
infilename = tkinter.filedialog.askopenfilename(initialdir=global_variables.current_directory, title=message)
if not infilename:return
global_variables.current_directory= os.path.dirname(infilename)
print(global_variables.current_directory)
self.load_pose(infilename)
|
python
| 9 | 0.689977 | 117 | 42 | 10 |
inline
|
import React, { Component } from 'react';
import {withRouter} from "react-router-dom";
import {connect} from "react-redux";
import './UserEvents.scss';
import Divider from '@material-ui/core/Divider';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import EventsService from "../../services/events.service";
import {closeSnackbar, openSnackbar} from "../../actions/snackbar";
import CloseIcon from '@material-ui/icons/Close';
import Snackbar from "@material-ui/core/Snackbar";
import Icon from "@material-ui/core/Icon";
class UserEventsPage extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
selectedEvent: '',
events: []
};
this.eventsService = new EventsService();
this.fetchEvents();
}
fetchEvents() {
this.eventsService.getEventsUser().then((response) => {
this.setState({
events: response.data,
});
});
}
handleClickOpen = (event) => {
this.setState({
open: true,
selectedEvent: event,
});
};
handleClickClose = () => {
this.setState({
open: false,
selectedEvent: null,
});
};
signInToEvent = () => {
this.eventsService.signUpEvent(this.state.selectedEvent.id).then((response) => {
this.props.openSnackbar(response.data.message);
this.handleClickClose();
setTimeout(() => {
this.props.closeSnackbar();
}, 3000);
});
};
render() {
return (
<div className="meetings-container">
<h2 className="meetings-header">
Upcoming events
<Divider />
name
date
date
{ this.state.events.map((event) => {
return (
<TableCell component="th" scope="row">{ event.name }
event.location }
<TableCell align="left">{ event.startDate + " " + event.startTime }
<TableCell align="left">{ event.endDate + " " + event.endTime }
<IconButton aria-label="Delete" onClick={() => { this.handleClickOpen(event) }}>
)
}) }
<Dialog
open={this.state.open}
onClose={this.handleClickClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Do you want to sign in to this event?"}
<DialogContentText id="alert-dialog-description">
This event is going to be added in your calendar.
<Button onClick={this.handleClickClose} color="secondary">
Cancel
<Button onClick={() => { this.signInToEvent(); }} color="primary" autoFocus>
Yes
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'center',
}}
open={this.props.snackbar.open}
autoHideDuration={6000}
onClose={this.handleClose}
ContentProps={{
'aria-describedby': 'message-id',
}}
message={<span id="message-id">{ this.props.snackbar.message }
action={[
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={this.props.closeSnackbar}
>
<CloseIcon />
]}
/>
)
}
}
const mapDispatchToProps = dispatch => {
return {
openSnackbar: (message) => {
dispatch(openSnackbar(message));
},
closeSnackbar: () => {
dispatch(closeSnackbar());
}
};
};
const mapStateToProps = state => {
return {
snackbar: state.snackbar,
}
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(UserEventsPage))
|
javascript
| 26 | 0.571239 | 102 | 28.909091 | 176 |
starcoderdata
|
/**
*
*
*/
#include "basicmacros.h"
#ifndef LTFAT_COMPLEX_OPERATIONS
#define LTFAT_COMPLEX_OPERATIONS
#if defined(__cplusplus)
# define ltfat_real(x) std::real(x)
# define ltfat_imag(x) std::imag(x)
# define ltfat_abs(x) std::abs(x)
# define ltfat_arg(x) std::arg(x)
#else
# define ltfat_complex_d(r,i) ((float)(r) + ((float)(i))*I)
# define ltfat_complex_s(r,i) ((double)(r) + ((double)(i))*I)
# define ltfat_real(x) creal(x)
# define ltfat_imag(x) cimag(x)
# define ltfat_abs(x) fabs(x)
# define ltfat_arg(x) carg(x)
#endif
# define ltfat_energy(x) ( ltfat_real(x)*ltfat_real(x) + ltfat_imag(x)*ltfat_imag(x) )
#endif
#ifdef LTFAT_COMPLEX
#undef LTFAT_COMPLEX
#endif
#ifdef LTFAT_REAL_MIN
#undef LTFAT_REAL_MIN
#endif
#ifdef LTFAT_REAL
#undef LTFAT_REAL
#endif
#ifdef LTFAT_TYPE
#undef LTFAT_TYPE
#endif
#ifdef LTFAT_NAME
#undef LTFAT_NAME
#endif
#ifdef LTFAT_NAME_REAL
#undef LTFAT_NAME_REAL
#endif
#ifdef LTFAT_NAME_COMPLEX
#undef LTFAT_NAME_COMPLEX
#endif
#ifdef LTFAT_FFTW
#undef LTFAT_FFTW
#endif
#ifdef LTFAT_KISS
#undef LTFAT_KISS
#endif
#ifdef LTFAT_MX_CLASSID
#undef LTFAT_MX_CLASSID
#endif
#ifdef LTFAT_MX_COMPLEXITY
#undef LTFAT_MX_COMPLEXITY
#endif
#ifdef LTFAT_COMPLEXH
#undef LTFAT_COMPLEXH
#endif
#ifdef LTFAT_DOUBLE
# ifndef I
# define I ltfat_complex_d(0.0,1.0)
# endif
# define LTFAT_REAL_MIN DBL_MIN
# define LTFAT_REAL double
# define LTFAT_COMPLEX ltfat_complex_d
# define LTFAT_FFTW(name) fftw_ ## name
# define LTFAT_KISS(name) kiss_ ## name ## _d
# define LTFAT_NAME_REAL(name) LTFAT_NAME_DOUBLE(name)
# define LTFAT_NAME_COMPLEX(name) LTFAT_NAME_COMPLEXDOUBLE(name)
# define LTFAT_COMPLEXH(name) name
# define LTFAT_MX_CLASSID mxDOUBLE_CLASS
# if defined(LTFAT_COMPLEXTYPE)
# define LTFAT_TYPE LTFAT_COMPLEX
# define LTFAT_NAME(name) LTFAT_NAME_COMPLEXDOUBLE(name)
# define LTFAT_MX_COMPLEXITY mxCOMPLEX
# else
# define LTFAT_TYPE LTFAT_REAL
# define LTFAT_NAME(name) LTFAT_NAME_DOUBLE(name)
# define LTFAT_MX_COMPLEXITY mxREAL
# endif
#endif
#ifdef LTFAT_SINGLE
# ifndef I
# define I ltfat_complex_s(0.0,1.0)
# endif
# define LTFAT_REAL_MIN FLT_MIN
#define LTFAT_REAL float
#define LTFAT_COMPLEX ltfat_complex_s
#define LTFAT_MX_CLASSID mxSINGLE_CLASS
#define LTFAT_NAME_REAL(name) LTFAT_NAME_SINGLE(name)
#define LTFAT_NAME_COMPLEX(name) LTFAT_NAME_COMPLEXSINGLE(name)
#define LTFAT_FFTW(name) fftwf_ ## name
#define LTFAT_KISS(name) kiss_ ## name ## _s
#define LTFAT_COMPLEXH(name) name ## f
# if defined(LTFAT_COMPLEXTYPE)
# define LTFAT_TYPE LTFAT_COMPLEX
# define LTFAT_NAME(name) LTFAT_NAME_COMPLEXSINGLE(name)
# define LTFAT_MX_COMPLEXITY mxCOMPLEX
# else
# define LTFAT_TYPE LTFAT_REAL
# define LTFAT_NAME(name) LTFAT_NAME_SINGLE(name)
# define LTFAT_MX_COMPLEXITY mxREAL
# endif
#endif
#if defined(__cplusplus)
// The following is constexpr only since C++17, so it is disabled for the time being
// static_assert(std::is_trivially_copyable
#endif
|
c
| 8 | 0.716748 | 88 | 25.059322 | 118 |
starcoderdata
|
<?php
namespace App\Nova\Lenses\Users;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Lenses\Lens;
use Laravel\Nova\Fields\Gravatar;
use Laravel\Nova\Fields\Password;
use Laravel\Nova\Http\Requests\LensRequest;
class Banned extends Lens
{
/**
* Get the query builder / paginator for the lens.
*
* @param \Laravel\Nova\Http\Requests\LensRequest $request
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return mixed
*/
public static function query(LensRequest $request, $query)
{
return $request->withOrdering($request->withFilters(
$query->banned()
));
}
/**
* Get the fields available to the lens.
*
* @param \Illuminate\Http\Request $request
*
* @return array
*/
public function fields(Request $request)
{
return [
ID::make()
->sortable(),
Gravatar::make(),
Text::make('Email')
->sortable()
->rules('required', 'email', 'max:255')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
Password::make('Password')
->onlyOnForms()
->creationRules('required', 'string', 'min:6')
->updateRules('nullable', 'string', 'min:6'),
];
}
/**
* Get the URI key for the lens.
*
* @return string
*/
public function uriKey()
{
return 'banned';
}
}
|
php
| 16 | 0.551852 | 67 | 22.823529 | 68 |
starcoderdata
|
# -*- coding: utf-8 -*-
"""attrition.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1if7BEMzB5bQ6F4tN1mkr6dPHaOTqGPCa
"""
import pandas as pd
import numpy as np
df = pd.read_csv("hr.csv")
df.head()
dept = np.unique(df['department'])
dept
sal = np.unique(df['salary'])
sal
feats = ['department','salary']
dp_final = pd.get_dummies(df,columns=feats,drop_first=True)
dp_final
from sklearn.model_selection import train_test_split
x = dp_final.drop(['left'],axis=1).values
y = dp_final['left'].values
! pip install tensorflow
x_train,x_test,y_train,y_test =train_test_split(x,y,test_size=0.3)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test= sc.transform(x_test)
import keras
from keras.models import Sequential
from keras.layers import Dense
classifier = Sequential()
classifier.add(Dense(9, kernel_initializer = "uniform",activation = "relu",input_dim=18))
classifier.add(Dense(1, kernel_initializer = "uniform",activation = "sigmoid"))
classifier.compile(optimizer ="adam",loss ="binary_crossentropy",metrics=["accuracy"])
import time
a = [10,20,30,40,50,60]
for i in a :
start = time.time()
classifier.fit(x_train,y_train,batch_size = i,epochs=10)
end = time.time()
print(end - start)
print (i)
y_pred = classifier.predict(x_test)
y_pred
y_pred = (y_pred>0.5)
from sklearn.metrics import confusion_matrix
cm=confusion_matrix(y_test,y_pred)
cm
new_pred=classifier.predict(sc.transform(np.array([[0.26,0.7,3.,238.,6.,0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,0.,0.,1.]])))
new_pred =(new_pred >0.5)
new_pred
new_pred =(new_pred >0.6)
new_pred
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
def make_classifier():
classifier = Sequential()
classifier.add(Dense(9, kernel_initializer = "uniform",activation ="relu",input_dim =18))
classifier.add(Dense(1, kernel_initializer = "uniform",activation ="sigmoid"))
classifier.compile(optimizer ="adam",loss ="binary_crossentropy",metrics=["accuracy"])
return classifier
classifier = KerasClassifier(build_fn=make_classifier,batch_size =10,nb_epoch =1)
accuracies = cross_val_score(estimator = classifier, X = x_train, y = y_train,cv= 10)
mean = accuracies.mean()
mean
variance = accuracies.var()
variance
from keras.layers import Dropout
classifier = Sequential()
classifier.add(Dense(9, kernel_initializer = "uniform",activation ="relu",input_dim =18))
classifier.add(Dropout(rate = 0.1))
classifier.add(Dense(1, kernel_initializer = "uniform",activation ="sigmoid"))
classifier.compile(optimizer ="adam",loss ="binary_crossentropy",metrics=["accuracy"])
from sklearn.model_selection import GridSearchCV
def make_classifier(optimizer):
classifier = Sequential()
classifier.add(Dense(9, kernel_initializer = "uniform",activation ="relu",input_dim =18))
classifier.add(Dense(1, kernel_initializer = "uniform",activation ="sigmoid"))
classifier.compile(optimizer ="adam",loss ="binary_crossentropy",metrics=["accuracy"])
return classifier
classifier = KerasClassifier(build_fn = make_classifier)
params = {
'batch_size' : [20,35],
'epochs': [2,3],
'optimizer':['adam','rmsprop']
}
grid_search =GridSearchCV(estimator =classifier,param_grid =params,scoring ='accuracy',cv=2)
grid_search = grid_search.fit(x_train,y_train)
best_param = grid_search.best_params_
best_accuracy = grid_search.best_score_
best_param
best_accuracy
|
python
| 11 | 0.727375 | 115 | 25.242647 | 136 |
starcoderdata
|
package crosby.binary.file;
import java.io.IOException;
import java.io.InputStream;
public class BlockInputStream {
// TODO: Should be seekable input stream!
public BlockInputStream(InputStream input, BlockReaderAdapter adaptor) {
this.input = input;
this.adaptor = adaptor;
}
public void process() throws IOException {
while (input.available() > 0) {
FileBlock.process(input, adaptor);
}
adaptor.complete();
}
public void close() throws IOException {
input.close();
}
InputStream input;
BlockReaderAdapter adaptor;
}
|
java
| 10 | 0.649435 | 76 | 22.807692 | 26 |
starcoderdata
|
<?php
/**
* Material filter form.
*
* @package Servicepool2.0
* @subpackage filter
* @author Your name here
* @version SVN: $Id: sfDoctrineFormFilterTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class MaterialFormFilter extends BaseMaterialFormFilter
{
public function configure()
{
$this->manageActivities();
$this->managerCategories();
}
protected function manageActivities() {
$this->widgetSchema['activities_list'] = new sfWidgetFormDoctrineChoice(array('model' => 'Activity', 'query' => Doctrine::getTable('Activity')->getActivitesList(), 'add_empty' => true, 'multiple' => false, 'method' => 'getIdName'));
$this->validatorsSchema['activities_list'] = new sfValidatorDoctrineChoice(array('model' => 'Activity', 'multiple' => false, 'required' => false));
}
protected function managerCategories() {
$this->widgetSchema['categories_list'] = new sfWidgetFormDoctrineChoice(array('model' => 'MaterialCategory', 'query' => Doctrine::getTable('MaterialCategory')->getCategoriesList(), 'add_empty' => true, 'multiple' => false, 'method' => 'getName'));
$this->validatorsSchema['categories_list'] = new sfValidatorDoctrineChoice(array('model' => 'MaterialCategory', 'multiple' => false, 'required' => false));
}
public function doBuildQuery(array $values)
{
$q = parent::doBuildQuery($values);
if (isset($values['activities_list']) && !empty($values['activities_list'])) {
$materials = ActivityMaterialsTable::getInstance()->createQuery()->select('material_id')->where('activity_id = ?', $values['activities_list'])->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
if (count($materials) > 0) {
$materials_ids = array_map(function ($material) {
return $material['material_id'];
}, $materials);
$q->whereIn('id', $materials_ids);
} else {
$q->where('id = ?', -1);
}
}
if (isset($values['categories_list']) && !empty($values['categories_list'])) {
$q->andWhere('category_id = ?', $values['categories_list']);
}
return $q;
}
}
|
php
| 19 | 0.613116 | 255 | 41.074074 | 54 |
starcoderdata
|
using CreditInterestCalc;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public class CreditCardShould
{
private CreditCard sut;
private const string name = "CardName";
private const double balance = 100;
private const double interest = 0.15;
private const int months = 1;
[SetUp]
public void Setup()
{
sut = new CreditCard
{
CardName = name,
Balance = balance,
InterestRate = interest
};
}
[Test]
public void CalculateInterestCorrectly()
{
Assert.That(sut.CalculateInterest(months), Is.EqualTo(15));
}
[Test]
public void ApplyInterestCorrectly()
{
sut.ApplyInterest(months);
Assert.That(sut.Balance, Is.EqualTo(115));
}
}
}
|
c#
| 14 | 0.542948 | 71 | 22.02439 | 41 |
starcoderdata
|
package com.fcz.oauth.controller.page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
* @author Mr.F
* @since 2019/7/11 10:40
**/
@Controller
@RequestMapping("/page/test")
public class TestPageController {
@RequestMapping("/test")
public String test(@RequestParam("token") String token, Map<String, Object> map){
map.put("token", token);
return "test";
}
}
|
java
| 10 | 0.71978 | 85 | 22.73913 | 23 |
starcoderdata
|
// IPC - Signal Mechanism
#define SIGNAL_N (sizeof(sigset_t) * 8)
#define SIGFN_IGN ((sigfunc_t) (-1))
#define SIGFN_KILL ((sigfunc_t) (-2))
// We allow at most 64 signals
typedef uint64 sigset_t;
// User-space signal handler/restorer function
typedef void (*sigfunc_t)(int);
typedef void (*sigrestorer_t)();
// Signal action
struct sigaction {
sigfunc_t fn;
sigrestorer_t restorer;
};
// Signal pending queue entry
struct sigpend {
int signo;
struct sigpend *next;
};
// Per-process signal pending queue
struct sigqueue {
// Number of pending signals whose handlers are not SIG_IGN
int n;
struct sigpend *head, *tail;
};
// Per-process signal handler
struct sighand {
struct sigaction actions[SIGNAL_N];
};
// Per-process signal descriptor
struct sigdesc {
struct spinlock lock;
struct sigqueue sigqueue;
struct sighand sighand;
};
// Signal frame
struct sigframe {
uint64 epc;
uint64 ra;
uint64 gp;
uint64 tp;
uint64 t0;
uint64 t1;
uint64 t2;
uint64 s0;
uint64 s1;
uint64 a0;
uint64 a1;
uint64 a2;
uint64 a3;
uint64 a4;
uint64 a5;
uint64 a6;
uint64 a7;
uint64 s2;
uint64 s3;
uint64 s4;
uint64 s5;
uint64 s6;
uint64 s7;
uint64 s8;
uint64 s9;
uint64 s10;
uint64 s11;
uint64 t3;
uint64 t4;
uint64 t5;
uint64 t6;
};
int signal_init(struct proc *p);
int signal_copy(struct proc *, struct proc *);
void signal_deinit(struct proc *p);
int signal_send(struct proc *p, int signo);
void signal_deliver();
int signal_pending();
|
c
| 6 | 0.646078 | 63 | 17.609195 | 87 |
starcoderdata
|
class CFSHeader extends HTMLElement {
static get observedAttributes() {
return ["templateid"];
}
get templateid() {
return this.getAttribute("templateid");
}
set templateid(val) {
this.setAttribute("templateid", val);
}
constructor() {
super();
const template = document.getElementById(this.templateid).content;
this.attachShadow({ mode: "open" }).appendChild(template.cloneNode(true));
}
}
window.customElements.define("cfs-header", CFSHeader);
|
javascript
| 12 | 0.688623 | 78 | 22.857143 | 21 |
starcoderdata
|
from collections import defaultdict
class Vocabulary:
def __init__(self, vocab_path):
self.bpe_lookup_dict = None
self.bpe_cache = None
self.vocab_dim = None
self.w2i = None
self.i2w = None
self.vocab_path = vocab_path
self.load_vocab()
def load_vocab(self):
with open(self.vocab_path, encoding="utf-8") as f:
subtokens = [l.rstrip() for l in f]
self.i2w = {ix + 1: w for ix, w in enumerate(subtokens)}
self.i2w[0] = "
self.w2i = {w: ix for ix, w in self.i2w.items()}
self.vocab_dim = len(self.i2w)
self.bpe_cache = {}
self.bpe_lookup_dict = defaultdict(set)
for token in self.w2i.keys():
self.bpe_lookup_dict[token[:2]].add(token)
def translate(self, token, is_subtokenized=False):
return (
self.lookup(token)
if is_subtokenized
else [self.lookup(t) for t in self.tokenize(token)]
)
def lookup(self, token):
return self.w2i[token] if token in self.w2i else self.w2i["
def tokenize(self, token):
token += "#" # Add terminal symbol first
tokens = []
ix = 0
if token in self.bpe_cache:
return self.bpe_cache[token]
while ix < len(token):
if ix == len(token) - 2:
tokens.append(token[ix:])
break
else:
candidates = self.bpe_lookup_dict.get(token[ix : ix + 2], [])
if not candidates:
top_candidate = token[ix]
else:
candidates = [
t
for t in candidates
if t == token[ix : ix + len(t)]
and not len(token) == ix + len(t) + 1
]
if not candidates:
top_candidate = token[ix]
else:
top_candidate = max(candidates, key=lambda e: len(e))
tokens.append(top_candidate)
ix += len(top_candidate)
self.bpe_cache[token] = tokens
return tokens
|
python
| 24 | 0.472624 | 77 | 33.123077 | 65 |
starcoderdata
|
@Override
public void run() {
List<WeatherForecastPOJO> weatherForecastPOJOList = AppDatabase.getsDbInstance(context).weatherForecastDao().getWeatherEntriesList();
if(!weatherForecastPOJOList.isEmpty())
{
updateValues(views,weatherForecastPOJOList,context);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
|
java
| 9 | 0.592233 | 149 | 50.6 | 10 |
inline
|
package com.kyleduo.digging.translucentstatusbar;
import android.view.MenuItem;
/**
* for DiggingTranslucentStatusBar
* Created by kyleduo on 2017/5/5.
*/
public class Demo1Activity extends BaseActivity {
@Override
protected int getLayoutResId() {
return R.layout.act_demo1;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
java
| 11 | 0.656028 | 57 | 20.692308 | 26 |
starcoderdata
|
const Pool = require('pg').Pool;
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DATABASE,
password:
port: process.env.DB_PORT,
});
const getUsers = callback => pool.query("SELECT * FROM users ORDER BY id ASC;", (error, results) => {
if (error) return error;
return callback(results.rows);
});
const createUser = (config, callback) => {
const { username, email, password, role } = config;
pool.query("INSERT INTO users (username, email, password, role) VALUES ($1, $2, $3, $4)",
[username, email, password, role],
(error, results) => {
if (error) throw new Error(error);
callback(results);
});
};
module.exports = {
getUsers,
createUser
};
|
javascript
| 14 | 0.65625 | 101 | 24.806452 | 31 |
starcoderdata
|
# *args
def some_func(*args):
print(args)
some_func(1, 2, 3)
some_func("peter", "george")
some_func(True, False)
def f(*args):
current_min = args[0]
for x in args:
if x < current_min:
current_min = x
print(current_min)
f(1, 2, 3, 4, 5, 6) # 1
f(1, 2, 3, 4, 5, 6, -4) # -4
# всички стойности отиват в *args / tuple /
def f_kwargs(**kwargs):
print(kwargs)
f_kwargs(name="Pesho", age=11)
# {'name': 'Pesho', 'age': 11}
def my_min(x, *args):
current_min = x
for x in args:
if x < current_min:
current_min = x
print(current_min)
my_min(10, 1)
# Задължително се подават данни, иначе хвърля грешка.
# Намираме най-малкото число.
def f(x, **kwargs):
print(x)
print(kwargs)
f(3, name = " Pesho", age = 11)
# 3
# {'name': ' Pesho', 'age': 11}
def f2(*args, **kwargs):
print(args)
print(kwargs)
f2(3, name=" Pesho", age=11)
# (3,)
# {'name': ' Pesho', 'age': 11}
def f3(x, *args, **kwargs):
print(x)
print(args)
print(kwargs)
f3(3, name=" Pesho", age=11)
|
python
| 9 | 0.54689 | 53 | 13.36 | 75 |
starcoderdata
|
<?php
namespace Logger\Tools;
/**
* Logging levels from syslog protocol defined in RFC 5424
*/
interface Rfc5424LogLevels {
const EMERGENCY = 0;
const ALERT = 1;
const CRITICAL = 2;
const ERROR = 3;
const WARNING = 4;
const NOTICE = 5;
const INFO = 6;
const DEBUG = 7;
}
|
php
| 5 | 0.680851 | 58 | 16.625 | 16 |
starcoderdata
|
// Copyright (C) 2022
// This code is licensed under MIT license (see LICENSE for details)
#pragma once
#include
#include
#include "MapArea.h"
#include "Typedefs.h"
#include "ImageLoader.h"
#include "ModelLoader.h"
#include "MouseHandler.h"
#include "TextGraphics.h"
#include "Vector3.h"
#include "ObjectsBehaviour.h"
#include "ICustomCursor.h"
#include "IFpsCounter.h"
#include "IFullscreenController.h"
#include "IGameLoop.h"
#include "IKeyboardHandler.h"
#include "ISceneManager.h"
#include "Player.h"
#include "PlanetWorldMap.h"
namespace Forradia
{
class IEngine
{
public:
IEngine (
IKeyboardHandler* _keyboardHandler,
ICustomCursor* _customCursor,
IFpsCounter* _fpsCounter,
IFullscreenController* _fullscreenController,
IGameLoop* _gameLoop,
ISceneManager* _sceneManager
)
: keyboardHandler(*_keyboardHandler),
cursor(*_customCursor),
fpsCounter(*_fpsCounter),
fullscreenController(*_fullscreenController),
gameLoop(*_gameLoop),
sceneManager(*_sceneManager) {}
virtual void DrawImage(
std::string imageName,
float x,
float y,
float w,
float h
) const = 0;
virtual void DrawImage(
int imageNameHash,
float x,
float y,
float w,
float h
) const = 0;
virtual void FillRect(
SDL_Color color,
float x,
float y,
float w,
float h
) const = 0;
virtual void DrawRect(
SDL_Color color,
float x,
float y,
float w,
float h
) const = 0;
virtual void DrawLine(SDL_Color color, LineF line) const = 0;
virtual void DrawLine(
SDL_Color color,
float x0,
float y0,
float x1,
float y1
) const = 0;
virtual void DrawString(
std::string message,
SDL_Color color,
Point2F point,
bool centerAlign = false,
float specificScaling = 1.0f
) = 0;
virtual void DrawString(
std::string message,
SDL_Color color,
float x,
float y,
bool centerAlign = false,
float specificScaling = 1.0f
) = 0;
virtual void DrawModel(
std::string modelName,
float x,
float y,
float z,
float rotation = 0.0f,
float specificScaling = 1.0f,
float Opacity = 1.0f
) const = 0;
virtual void DrawModel(
int modelNameHash,
float x,
float y,
float z,
float rotation = 0.0f,
float specificScaling = 1.0f,
float opacity = 1.0f
) const = 0;
virtual void FillRect(SDL_Color color, RectF rect) const = 0;
virtual void DrawRect(SDL_Color color, RectF rect) const = 0;
virtual SizeF GetImageSizeF(std::string imageName) const = 0;
virtual MapArea& GetCurrMapArea() const = 0;
Player& GetPlayer() const;
WindowPtr window;
IKeyboardHandler& keyboardHandler;
ICustomCursor& cursor;
IFpsCounter& fpsCounter;
IFullscreenController& fullscreenController;
IGameLoop& gameLoop;
ISceneManager& sceneManager;
MouseHandler mouseHandler;
ImageLoader imageLoader;
ModelLoader modelLoader;
TextGraphics textGraphics;
ObjectsBehaviour objectsContent;
UPtr world;
UPtr playerPtrPtr;
std::string text;
char* composition;
Sint32 textCursor = 0;
Sint32 selection_len = 0;
};
}
|
c
| 16 | 0.643752 | 69 | 21.893333 | 150 |
starcoderdata
|
package com.transcendence.wan.module.mine.adapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import java.util.List;
public class FragmentTabAdapter implements RadioGroup.OnCheckedChangeListener {
private List fragments; // 一个tab页面对应一个Fragment
private RadioGroup radioGroups; // 用于切换tab
private FragmentActivity fragmentActivity; // Fragment所属的Activity
private int fragmentContentId; // Activity中所要被替换的区域的id
private int currentTab;
private OnTabCheckedListener onTabCheckedListener;
private long currentTime;
public FragmentTabAdapter(FragmentActivity fragmentActivity, List fragments, int fragmentContentId,
RadioGroup rgs, int currentId) {
this.fragments = fragments;
this.radioGroups = rgs;
this.fragmentActivity = fragmentActivity;
this.fragmentContentId = fragmentContentId;
// 默认显示第一页
FragmentTransaction ft = this.fragmentActivity.getSupportFragmentManager().beginTransaction();
ft.add(this.fragmentContentId, this.fragments.get(currentId));
ft.commit();
this.radioGroups.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
if (System.currentTimeMillis() - currentTime < 100) {
((RadioButton) radioGroups.getChildAt(0)).setChecked(true);
Fragment fragment = fragments.get(0);
fragment.onResume();
return;
}
currentTime = System.currentTimeMillis();
for (int i = 0; i < radioGroups.getChildCount(); i++) {
int childId = radioGroups.getChildAt(i).getId();
if (childId == checkedId) {
Fragment fragment = fragments.get(i);
FragmentTransaction ft = obtainFragmentTransaction();
getCurrentFragment().onPause(); // 暂停当前tab
if (fragment.isAdded()) {
fragment.onResume(); // 启动目标tab的onResume()
} else {
ft.add(fragmentContentId, fragment);
}
showTab(i); // 显示目标tab
ft.commitAllowingStateLoss();
// 如果设置了切换tab额外功能功能接口
if (null != onTabCheckedListener) {
onTabCheckedListener.onTabChecked(radioGroup, checkedId, i);
}
return;
}
}
}
private void showTab(int idx) {
for (int i = 0; i < fragments.size(); i++) {
Fragment fragment = fragments.get(i);
if (fragment.isAdded()) {
FragmentTransaction ft = obtainFragmentTransaction();
if (idx == i) {
ft.show(fragment);
} else {
ft.hide(fragment);
}
ft.commitAllowingStateLoss();
}
}
currentTab = idx; // 更新目标tab为当前tab
}
public void switchTo(int index) {
RadioButton childAt = (RadioButton) radioGroups.getChildAt(index);
childAt.setChecked(true);
}
private FragmentTransaction obtainFragmentTransaction() {
FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
return ft;
}
public int getCurrentTab() {
return currentTab;
}
public Fragment getCurrentFragment() {
return fragments.get(currentTab);
}
public OnTabCheckedListener getOnTabCheckedListener() {
return onTabCheckedListener;
}
public void setOnTabCheckedListener(OnTabCheckedListener onTabCheckedListener) {
this.onTabCheckedListener = onTabCheckedListener;
}
public interface OnTabCheckedListener {
void onTabChecked(RadioGroup radioGroup, int checkedId, int index);
}
}
|
java
| 14 | 0.626803 | 113 | 31.435484 | 124 |
starcoderdata
|
private async Task RefreshKnowledgeBaseAsync(KBInfo kb, Guid correlationId, System.Threading.CancellationToken cancelToken)
{
Exception refreshError = null;
try
{
await this.refreshHelper.RefreshKnowledgeBaseAsync(kb, correlationId);
}
catch (Exception ex)
{
refreshError = ex;
this.logProvider.LogWarning($"Failed to refresh KB {kb.KBId}: {ex.Message}", exception: ex, correlationId: correlationId);
}
// Log success/failure of the knowledge base refresh
var properties = new Dictionary<string, string>
{
{ "KnowledgeBaseId", kb.KBId },
{ "KnowledgeBaseName", kb.KBName },
{ "Success", (refreshError != null).ToString() },
};
if (refreshError != null)
{
properties["LastRefreshDateTime"] = kb.LastRefreshDateTime.ToString("u");
properties["ErrorMessage"] = refreshError.Message;
}
this.logProvider.LogEvent("KnowledgeBaseRefresh", properties, correlationId: correlationId);
}
|
c#
| 15 | 0.56276 | 138 | 40.517241 | 29 |
inline
|
<div class="appointments-container">
<div class="appointments-appointment">
<form method="post" class="appointments-search">
vous
<?php // echo date('Ymd', time()) ?>
<?php // echo $this->html_m->form_input('id', $this->input->get('id')) ?>
<?= $this->html_m->form_input('appointment_date', $this->input->post('appointment_date'), ' class="form-control" placeholder="Date au format AAAAMMJJ en commencant par la gauche"') ?>
<?php // echo $this->html_m->form_input('user_id', $this->input->get('user_id')) ?>
<?php echo $this->html_m->form_input('first_name', $this->input->get('first_name')) ?>
<?php echo $this->html_m->form_input('last_name', $this->input->get('last_name')) ?>
<?php
echo '';
// echo $this->html_m->form_input('last_name', $this->input->get('last_name')) ?>
<?php // $this->html_m->form_input('for_user', $this->input->post('for_user'), ' class="form-control"') ?>
<label for="for_user">Pour l'utilisateur
<div class="for_user_ui" >
<a onclick="setField('for_user', this)"
class="btn btn-primary btn-sm">Oui
<a onclick="setField('for_user', this)"
class="btn btn-primary btn-sm">Non
<?php // $this->html_m->form_input('for_user', $this->input->post('for_user'), ' class="form-control"') ?>
<?php echo form_hidden('for_user', $this->input->post('for_user') ) ?>
<?= $this->html_m->form_input('doctor_id', $this->input->post('doctor_id'), ' class="form-control"') ?>
<label for="futur_past">Futurs ou passés
<div class="futur_past_ui" >
<a onclick="setField('futur_past', this)"
class="btn btn-primary btn-sm"
data-value="futur">Future
<a onclick="setField('futur_past', this)"
class="btn btn-primary btn-sm"
data-value="past">Passé
<?php $this->html_m->form_input('futur_past', $this->input->post('futur_past'), ' class="form-control"') ?>
<?php echo form_hidden('futur_past', $this->input->post('futur_past') ) ?>
<button class="btn btn-primary" type="submit" name="searchBtn" value="<?= lang('appointments:search') ?>" /><?= lang('appointments:search') ?>
<a class="btn btn-default" href="/appointments/listing"><?= lang('appointments:reset') ?>
<div class="appointments-data">
<table cellpadding="0" cellspacing="0" class="table table-striped table-hover ">
<?= $this->html_m->table_header('appointment_date') ?>
<?= $this->html_m->table_header('appointment_time') ?>
<?= $this->html_m->table_header('for_user') ?>
<?= $this->html_m->table_header('first_name') ?>
<?= $this->html_m->table_header('last_name') ?>
<?= $this->html_m->table_header('name') ?>
<!-- Here we loop through the $items array -->
{{ appointments }}
echo ''; ?>
href="{{ url:site }}appointments/view/{{id}}" class=""><i class="glyphicon glyphicon-plus-sign">
helper:date format="d/m/Y" timestamp=appointment_date }}
{{month}}
{{if doc_speciality}} • {{doc_speciality}}{{endif}}
<!-- total_pretax }} €
total_final }} €
<!--
{{ if appointment_status == "prep" }}
{{ helper:lang line="appointments:status_prep" }}
{{ endif }}
{{ if appointment_status == "delivery" }}
{{ helper:lang line="appointments:status_seeing" }}
{{ endif }}
{{ if appointment_status == "delivered" }}
{{ helper:lang line="appointments:status_seen" }}
{{ endif }}
{{ if appointment_status == "waiting" }}
{{ helper:lang line="appointments:status_waiting" }}
{{ endif }}
<!-- maiden_name }}
area_name }}
district }}
town }}
<!--
{{appointment_date}}
{{ helper:date format="d/m/Y H:i:s" timestamp=appointment_date }}
{{ /appointments }}
<p class="alert alert-info"> <i class="close">×
{{ if count == 1 }} {{ count }} enregistrement{{ endif }}
{{ if count > 1 }} {{ count }} enregistrements{{ endif }}
{{ pagination:links }}
|
php
| 9 | 0.391325 | 196 | 62.920792 | 101 |
starcoderdata
|
/*
* $Id:$
*
* Source file for the os-specific logging things
*
*/
#include "fwkLog.h"
#include
#include
enum FwkLogLevel
fwkLogLevelFromStr(
const char *inputString
) {
if ( strcmp(inputString, "ERROR") == 0 ) {
return FWK_LOG_LEVEL_ERROR;
}
if ( strcmp(inputString, "WARNING") == 0 ) {
return FWK_LOG_LEVEL_WARNING;
}
if ( strcmp(inputString, "INFO") == 0 ) {
return FWK_LOG_LEVEL_INFO;
}
if ( strcmp(inputString, "DEBUG") == 0 ) {
return FWK_LOG_LEVEL_DEBUG;
}
if ( strcmp(inputString, "DEVEL") == 0 ) {
return FWK_LOG_LEVEL_DEVEL;
}
return FWK_LOG_LEVEL_INVALID;
}
|
c
| 9 | 0.589958 | 49 | 19.757576 | 33 |
starcoderdata
|
#def test_link(app):
# smParticipants = app.smParticipants
# smParticipantsCustomers = app.smParticipantsCustomers
# smParticipantsSuppliers = app.smParticipantsSuppliers
# smPurchases = app.smPurchases
# smPrices = app.smPrices
# smCertificates = app.smCertificates
# smLicences = app.smLicences
# smKontrol = app.smKontrol
# smreports = app.smreports
# smMonitorinds = app.smMonitorinds
# smcompany_list = app.smcompany_list
# smPurchases_list = app.smPurchases_list
# smNmckList = app.smNmckList
# smUser_History = app.smUser_History
# for i in list[smParticipants, smParticipantsCustomers, smParticipantsSuppliers, smPurchases, smPrices, smCertificates,
# smLicences, smKontrol, smreports,
# smMonitorinds, smcompany_list, smPurchases_list, smNmckList, smUser_History]:
# if i == "smParticipants":
# exp_result = "Деятельность компании"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == "smParticipantsCustomers":
# exp_result = "Заказчики"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == smParticipantsSuppliers:
# exp_result = "Поставщики"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == smPurchases:
# exp_result = "Торги и контракты"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == smPrices:
# exp_result = "Цены контрактов"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == smCertificates:
# exp_result = "Сертификаты"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == smLicences:
# exp_result = "Лицензии"
# test_sm_link_smParticipants(app, i, exp_result)
# elif i == smKontrol:
# exp_result = "Контроль"
# test_sm_link_smParticipants(app, i, exp_result)
def test_sm_link_smAdminUpravlenie(app):
app.session.open_SM_page(app.smAdminUpravlenie)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smAdminUpravlenie)
exp_result = "Пользователи"
assert (app.testhelpersm.ensure_link_work() == exp_result)
def test_sm_link_smAdminShlyuz(app):
exp_result = "Пользователи"
app.session.open_SM_page(app.smAdminShlyuz)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smAdminShlyuz)
assert (app.testhelpersm.ensure_link_work() == exp_result)
def test_sm_link_smAdminAccessManager(app):
exp_result = "Пользователи"
app.session.open_SM_page(app.smAdminAccessManager)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smAdminAccessManager)
assert (app.testhelpersm.ensure_link_work() == exp_result)
#страница удалена из админки см
#def test_sm_link_smAdminInstructions(app):
# exp_result = "Редактирование инструкций"
# app.session.open_SM_page(app.smAdminInstructions)
# app.session.ensure_login_sm(app.username, app.password)
# app.session.open_SM_page(app.smAdminInstructions)
# assert (app.testhelpersm.ensure_link_work() == exp_result)
def test_sm_link_smAdminNotifications(app):
exp_result = "Редактирование уведомлений"
app.session.open_SM_page(app.smAdminNotifications)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smAdminNotifications)
assert (app.testhelpersm.ensure_link_work() == exp_result)
def test_sm_link_smAdminNews(app):
exp_result = "Редактирование новостей"
app.session.open_SM_page(app.smAdminNews)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smAdminNews)
assert (app.testhelpersm.ensure_link_work() == exp_result)
def test_sm_link_smAdminSessions(app):
exp_result = "Сессии пользователей"
app.session.open_SM_page(app.smAdminSessions)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smAdminSessions)
assert (app.testhelpersm.ensure_link_work() == exp_result)
|
python
| 9 | 0.693778 | 123 | 42.343434 | 99 |
starcoderdata
|
using System.IO;
namespace Kentico.Kontent.ModelGenerator.Tests
{
public abstract class CodeGeneratorTestsBase
{
protected abstract string TempDir { get; }
protected const string ProjectId = "975bf280-fd91-488c-994c-2f04416e5ee3";
protected CodeGeneratorTestsBase()
{
// Cleanup
if (Directory.Exists(TempDir))
{
Directory.Delete(TempDir, true);
}
Directory.CreateDirectory(TempDir);
}
}
}
|
c#
| 14 | 0.596262 | 82 | 24.47619 | 21 |
starcoderdata
|
<?php
class Admin_model extends CI_Model{
public function __construct(){
parent::__construct();
if(!$this->session->userdata('id')){
redirect('login');
}
if($this->session->userdata('type') != 0){
redirect('login');
}
}
}
?>
|
php
| 12 | 0.469256 | 50 | 16.222222 | 18 |
starcoderdata
|
/* eslint-env mocha, es6 */
import test from 'ava';
import path from 'path';
import generate from '@gerhobbelt/markdown-it-testgen';
import markdown_it from '@gerhobbelt/markdown-it';
import { fileURLToPath } from 'url';
// see https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_no_require_exports_module_exports_filename_dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
test('markdown-it-abbr', function (t) {
const md = markdown_it({ linkify: true });
generate.load(path.join(__dirname, 'fixtures/abbr.txt'), {}, function (data) {
t.pass();
});
});
test.failing('will fail (expected failure)', t => {
t.fail();
});
if (0) {
test.only('will be the only test run', t => {
t.pass();
});
}
async function promiseFn() {
console.log('starting fast promise');
return new Promise(resolve => {
setTimeout(function () {
resolve('fast');
console.log('fast promise is done');
}, 1000);
});
}
test('async base test', async function (t) {
const value = await promiseFn();
console.error('awaited value = ', value);
t.true(value === 'fast');
return t;
});
// Async arrow function
test('promises the truth', async t => {
const value = await promiseFn();
console.error('awaited value = ', value);
t.true(value === 'fast');
});
test.cb('data.txt can be read', t => {
// `t.end` automatically checks for error as first argument
//fs.readFile('data.txt', t.end);
t.end();
});
test.todo('will think about writing this later');
|
javascript
| 16 | 0.646835 | 111 | 23.6875 | 64 |
starcoderdata
|
QModelIndex StationTreeModel::index( int row, int column,
const QModelIndex &parent /*= QModelIndex()*/ ) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
ModelTreeItem* parentItem;
if (!parent.isValid())
parentItem = (ModelTreeItem*)(_rootItem);
else
parentItem = static_cast<ModelTreeItem*>(parent.internalPointer());
ModelTreeItem* childItem = (ModelTreeItem*)(parentItem->child(row));
if (childItem)
{
QModelIndex newIndex = createIndex(row, column, childItem);
// assign ModelIndex to BaseItem so it can communicate with the model
BaseItem* item = childItem->getItem();
if ( item != nullptr )
item->setModelIndex(newIndex);
return newIndex;
}
else
return QModelIndex();
}
|
c++
| 12 | 0.685452 | 90 | 28.384615 | 26 |
inline
|
using System.Collections.Generic;
namespace Lambdajection.Generator.TemplateGeneration
{
public class Policy
{
public Policy(string policyName)
{
PolicyName = policyName;
}
public string PolicyName { get; set; }
public PolicyDocument PolicyDocument { get; private set; } = new PolicyDocument();
public Policy AddStatement(HashSet action, string effect = "Allow", string resource = "*")
{
PolicyDocument.Statement.Add(new PolicyStatement()
{
Effect = effect,
Action = action,
Resource = resource,
Principal = null,
});
return this;
}
}
}
|
c#
| 15 | 0.554667 | 106 | 24.862069 | 29 |
starcoderdata
|
func messageMetadataByID(c echo.Context) (*messageMetadataResponse, error) {
if !deps.SyncManager.IsNodeAlmostSynced() {
return nil, errors.WithMessage(echo.ErrServiceUnavailable, "node is not synced")
}
messageID, err := restapi.ParseMessageIDParam(c)
if err != nil {
return nil, err
}
cachedMsgMeta := deps.Storage.CachedMessageMetadataOrNil(messageID)
if cachedMsgMeta == nil {
return nil, errors.WithMessagef(echo.ErrNotFound, "message not found: %s", messageID.ToHex())
}
defer cachedMsgMeta.Release(true) // meta -1
metadata := cachedMsgMeta.Metadata()
var referencedByMilestone *milestone.Index = nil
referenced, referencedIndex := metadata.ReferencedWithIndex()
if referenced {
referencedByMilestone = &referencedIndex
}
messageMetadataResponse := &messageMetadataResponse{
MessageID: metadata.MessageID().ToHex(),
Parents: metadata.Parents().ToHex(),
Solid: metadata.IsSolid(),
ReferencedByMilestoneIndex: referencedByMilestone,
}
if metadata.IsMilestone() {
messageMetadataResponse.MilestoneIndex = referencedByMilestone
}
if referenced {
inclusionState := "noTransaction"
conflict := metadata.Conflict()
if conflict != storage.ConflictNone {
inclusionState = "conflicting"
messageMetadataResponse.ConflictReason = &conflict
} else if metadata.IsIncludedTxInLedger() {
inclusionState = "included"
}
messageMetadataResponse.LedgerInclusionState = &inclusionState
} else if metadata.IsSolid() {
// determine info about the quality of the tip if not referenced
cmi := deps.SyncManager.ConfirmedMilestoneIndex()
tipScore, err := deps.TipScoreCalculator.TipScore(Plugin.Daemon().ContextStopped(), cachedMsgMeta.Metadata().MessageID(), cmi)
if err != nil {
if errors.Is(err, common.ErrOperationAborted) {
return nil, errors.WithMessage(echo.ErrServiceUnavailable, err.Error())
}
return nil, errors.WithMessage(echo.ErrInternalServerError, err.Error())
}
var shouldPromote bool
var shouldReattach bool
switch tipScore {
case tangle.TipScoreNotFound:
return nil, errors.WithMessage(echo.ErrInternalServerError, "tip score could not be calculated")
case tangle.TipScoreOCRIThresholdReached, tangle.TipScoreYCRIThresholdReached:
shouldPromote = true
shouldReattach = false
case tangle.TipScoreBelowMaxDepth:
shouldPromote = false
shouldReattach = true
case tangle.TipScoreHealthy:
shouldPromote = false
shouldReattach = false
}
messageMetadataResponse.ShouldPromote = &shouldPromote
messageMetadataResponse.ShouldReattach = &shouldReattach
}
return messageMetadataResponse, nil
}
|
go
| 16 | 0.750467 | 128 | 30.880952 | 84 |
inline
|
"""Some functions around AppArmor profiles."""
import logging
import re
from ..exceptions import AppArmorFileError, AppArmorInvalidError
_LOGGER: logging.Logger = logging.getLogger(__name__)
RE_PROFILE = re.compile(r"^profile ([^ ]+).*$")
def get_profile_name(profile_file):
"""Read the profile name from file."""
profiles = set()
try:
with profile_file.open("r") as profile_data:
for line in profile_data:
match = RE_PROFILE.match(line)
if not match:
continue
profiles.add(match.group(1))
except OSError as err:
_LOGGER.error("Can't read AppArmor profile: %s", err)
raise AppArmorFileError() from err
if len(profiles) != 1:
_LOGGER.error("To many profiles inside file: %s", profiles)
raise AppArmorInvalidError()
return profiles.pop()
def validate_profile(profile_name, profile_file):
"""Check if profile from file is valid with profile name."""
if profile_name == get_profile_name(profile_file):
return True
return False
def adjust_profile(profile_name, profile_file, profile_new):
"""Fix the profile name."""
org_profile = get_profile_name(profile_file)
profile_data = []
# Process old data
try:
with profile_file.open("r") as profile:
for line in profile:
match = RE_PROFILE.match(line)
if not match:
profile_data.append(line)
else:
profile_data.append(line.replace(org_profile, profile_name))
except OSError as err:
_LOGGER.error("Can't adjust origin profile: %s", err)
raise AppArmorFileError() from err
# Write into new file
try:
with profile_new.open("w") as profile:
profile.writelines(profile_data)
except OSError as err:
_LOGGER.error("Can't write new profile: %s", err)
raise AppArmorFileError() from err
|
python
| 17 | 0.612808 | 80 | 29.757576 | 66 |
starcoderdata
|
import numpy as np
import cv2
import os
from scipy.io import loadmat
def get_frames_from_video(video_path, scale, start_at_frame):
"""
Get frame generator from video file path
Args:
start_at_frame: index of first frame to get
video_path: path of the video
scale: scale the image
Returns: generator of the frames
"""
video = cv2.VideoCapture(video_path)
video.set(cv2.CAP_PROP_POS_FRAMES, start_at_frame + 1)
has_next_frame, frame = video.read()
while has_next_frame:
# Rescale the image
frame = cv2.resize(frame, dsize=(int(320 * scale), int(240 * scale)), interpolation=cv2.INTER_CUBIC)
yield frame.astype(np.float32)
has_next_frame, frame = video.read()
def get_video_length(video_path):
video = cv2.VideoCapture(video_path)
return int(video.get(cv2.CAP_PROP_FRAME_COUNT))
def center_crop(img, joints_2d, size_x, size_y):
"""
Args:
joints_2d:
img: shape (T, width, height, 3)
size_x:
size_y:
"""
start_x = img.shape[2] // 2 - (size_x // 2)
start_y = img.shape[1] // 2 - (size_y // 2)
joints_2d[0, :, :] = joints_2d[0, :, :] - start_x
joints_2d[1, :, :] = joints_2d[1, :, :] - start_y
img = img[:, start_y:start_y + size_y, start_x:start_x + size_x, :]
return img, joints_2d
def get_order_joint_human(joints):
"""
Order:
0 RFoot, 1 RKnee, 2 RHip, 3 LHip, 4 LKnee, 5 Lfoot, 6 Hip, 7 Spine, 8 Thorax, 9 Head, 10 RHand, 11 RElbow, 12 RShoulder
13 LShoulder, 14 LElbow, 15 LHand
"""
new_order_joints = np.zeros((joints.shape[0], 32))
# actual index: position in surreal, index = position in human
# permutation = [0, 6, 1, 12, 7, 2, 4, 8, 3, 13, 5, 9, 14, 10, 11, 15, 17, 25, 18, 26, 19, 27, 16, 20]
permutation = [3, 2, 1, 6, 7, 8, 0, 12, 13, 15, 27, 26, 25, 17, 18, 19]
for k, i in enumerate(permutation):
new_order_joints[:, i] = joints[:, k]
return new_order_joints
def get_camera_matrices(cam_location):
"""
Adapted from https://github.com/gulvarol/bodynet/blob/f07dec69a6490ecdeb1dfd3758e76a3ca5887e5b/training/util/camerautils.lua#L47
Args:
cam_location: 3x1, Location of the camera in world coordinate
Returns:
- T Translation matrix 3x1
- R Rotation matrix 3x3
"""
R_world_to_cam = np.matrix("0 0 1; 0 -1 0; -1 0 0").transpose() # 3x3
T_world_to_cam = -1 * R_world_to_cam @ cam_location # 3x1
R_cam_to_cv = np.matrix("1 0 0; 0 -1 0; 0 0 -1") # 3x3
R = R_cam_to_cv @ R_world_to_cam # 3x3
T = R_cam_to_cv @ T_world_to_cam # 3x1
return T, R
def to_camera_coordinate(joints, T, R):
"""
Args:
joints: 3x24xT
T: 3x1
R: 3x3
Returns:
"""
new_joints = np.zeros_like(joints)
for t in range(joints.shape[2]):
new_joints[:, :, t] = (R @ joints[:, :, t]) + T
return new_joints
def to_world_coordinate(joints, T, R):
"""
Args:
joints: 3x24xT
T: 3x1
R: 3x3
Returns:
"""
new_joints = np.zeros_like(joints)
for t in range(joints.shape[2]):
new_joints[:, :, t] = R @ (joints[:, :, t] - T)
return new_joints
def align_3d_joints(joints):
"""
Sets Pelvis to 0
Args:
joints:
Returns: aligned joints
"""
new_joints = joints[:]
for t in range(joints.shape[2]):
new_joints[:, :, t] = new_joints[:, :, t] - np.expand_dims(joints[:, 0, t], axis=1) # pelvis at coord 0
return new_joints
def heatmat_to_2d_joints(heatmap):
"""
From a heatmap of the joint, returns the positions in 2D
Args:
heatmap: size batch x 16 x 64 x 64
Returns: joints, size: batch x 2 x 16
"""
joints = np.zeros((heatmap.shape[0], 2, heatmap.shape[1])) # batch x 2 x 16
for batch in range(heatmap.shape[0]):
for k in range(heatmap.shape[1]):
y, x = np.unravel_index(np.argmax(heatmap[batch, k], axis=None), heatmap[batch, k].shape)
joints[batch, 1, k] = y / heatmap[batch, k].shape[0]
joints[batch, 0, k] = x / heatmap[batch, k].shape[1]
return joints
def get_joints_hourglass(joints):
"""
Hourglass:
0 RFoot, 1 RKnee, 2 RHip, 3 LHip, 4 LKnee, 5 Lfoot, 6 Hip, 7 Top Spine, 8 Neck, 9 Head, 10 RHand, 11 RElbow, 12 RShoulder
13 LShoulder, 14 LElbow, 15 LHand
Surreal:
0 Hip, 1 LHip, 2 RHip, 3 SpineDown, 4 LKnee, 5 RKnee, 6 SpineMid, 7 LFoot, 8 RFoot, 9 SpineUp, 10 LToes,
11 RToes, 12 Neck, 13 LChest, 14 RChest, 15 Chin, 16 LShoulder, 17 RShoulder, 18 LElbow, 19 RElbow,
20 LWrist, 21 RWrist, 22 LHand, 23 RHand
Args:
joints: dim A x 24 x B
Returns:
dim A x 16 x B
"""
new_joints = np.zeros((joints.shape[0], 16, joints.shape[2]))
permutation = [8, 5, 2, 1, 4, 7, 0, 9, 12, 15, 23, 19, 17, 16, 18, 22]
for i, k in enumerate(permutation):
new_joints[:, i] = joints[:, k]
return new_joints
class SurrealDataset:
def __init__(self, path, data_type, run, dataset="cmu", video_training_output=False, frames_before=0,
frames_after=0):
"""
Args:
path: path ro root surreal data
data_type: train, val or test
run: run0, run1 or run2
dataset: cmu
"""
assert data_type in ['train', 'val', 'test'], "Surreal type must be in train, val or test."
assert run in ['run0', 'run1', 'run2'], "Surreal run must be between run0, run1 and run2"
assert dataset in ['cmu'], "Surreal dataset must be cmu"
self.path = path
self.frames_before = frames_before
self.frames_after = frames_after
self.video_training_output = video_training_output
self.start_video_at_frame = None
self.end_video_at_frame = None
self.video_length = None
self.cur = None
# path = os.path.abspath(path)
root_path = os.path.join(path, dataset, data_type, run)
self.files = []
self.targets = []
self.item_to_file = []
self.first_index_for_file = {}
for seq_name in os.listdir(root_path):
for video in os.listdir(os.path.join(root_path, seq_name)):
if video[-3:] == 'mp4':
video_path = os.path.join(root_path, seq_name, video)
name = video[:-4]
self.targets.append(os.path.join(root_path, seq_name, name + "_info.mat"))
self.files.append(video_path)
self.len = len(self.files)
def __len__(self):
return self.len
def set_start_frame_between(self, frame_start, relative_frame_end):
self.start_video_at_frame = frame_start
self.end_video_at_frame = relative_frame_end
self.video_length = self.start_video_at_frame - self.end_video_at_frame + 1
def __getitem__(self, item):
"""
Frames are shape (T, width, height, 3)
Args:
item: item to load
Returns:
triple (frames, joints_2d, joints_3d) of numpy arrays
n_frames = 1 + self.frames_before + self.frames_after + 1
- frames has shape (T, channels=3, height=240, width=320)
- joints_2d has shape (2, 16, T)
- joints_3d has shape (3, 16, T)
Order of the joints surreal:
- 0 Hip, 1 LHip, 2 RHip, 3 SpineDown, 4 LKnee, 5 RKnee, 6 SpineMid, 7 LFoot, 8 RFoot, 9 SpineUp, 10 LToes,
11 RToes, 12 Neck, 13 LChest, 14 RChest, 15 Chin, 16 LShoulder, 17 RShoulder, 18 LElbow, 19 RElbow,
20 LWrist, 21 RWrist, 22 LHand, 23 RHand
Order of joints at output:
0 RFoot, 1 RKnee, 2 RHip, 3 LHip, 4 LKnee, 5 Lfoot, 6 Hip, 7 Top Spine, 8 Neck, 9 Head, 10 RHand,
11 RElbow, 12 RShoulder, 13 LShoulder, 14 LElbow, 15 LHand
"""
scale = 1.1
video_info = loadmat(self.targets[item])
joints_2d = video_info["joints2D"] * scale # to correspond to the image scaling
joints_3d = video_info["joints3D"]
camera_location = video_info["camLoc"]
start_at = 0
end_at = joints_2d.shape[2]
if self.start_video_at_frame is not None:
start_at = np.random.randint(self.start_video_at_frame, joints_2d.shape[2] + self.end_video_at_frame)
self.cur = start_at
end_at = start_at + self.video_length
frames = np.array([next(get_frames_from_video(self.files[item], scale=scale, start_at_frame=start_at)) for _ in
range(end_at - start_at)])
frames /= 255
T, R = get_camera_matrices(camera_location)
joints_3d = to_camera_coordinate(joints_3d, T, R)
joints_3d = get_joints_hourglass(align_3d_joints(joints_3d))
# crop to power of two for better down/up sampling in hourglass
frames, joints_2d = center_crop(frames, joints_2d, 256, 256)
joints_2d = get_joints_hourglass(joints_2d)
# Normalize 2D positions
joints_2d[0, :] = joints_2d[0, :] / frames.shape[2]
joints_2d[1, :] = joints_2d[0, :] / frames.shape[3]
frames = frames.transpose((0, 3, 1, 2))
if self.cur is not None:
joints_2d = joints_2d[:, :, self.cur]
joints_3d = joints_3d[:, :, self.cur]
return frames, joints_2d, joints_3d
class SurrealDatasetWithVideoContinuity:
def __init__(self, path, data_type, run, dataset="cmu", frames_before=0, frames_after=0):
self.frames_before = frames_before
self.frames_after = frames_after
self.surreal = SurrealDataset(path, data_type, run, dataset)
def __len__(self):
return self.surreal.len
def __getitem__(self, item):
"""
Only returns n_frames = 1 + self.frames_before + self.frames_after + 1
on the image for the learning
Args:
item: item to load
Returns:
triple (frames, joints_2d, joints_3d) of numpy arrays
n_frames = 1 + self.frames_before + self.frames_after + 1
- frames has shape (n_frames, channels=3, height=240, width=320)
- joints_2d has shape (2, 24)
- joints_3d has shape (3, 24)
"""
self.surreal.set_start_frame_between(self.frames_before, -self.frames_after - 1)
frames, joints_2d, joints_3d = self.surreal[item]
return frames, joints_2d, joints_3d
|
python
| 18 | 0.577378 | 132 | 34.45302 | 298 |
starcoderdata
|
#include "routes.hpp"
#include
#include
#include
TEST_CASE("Manhattan distance calculator", "[woot]")
{
SECTION("My Test 1")
{
std::vector<std::pair<char, int>> a{ { 'R', 3 }, { 'D', 2 } };
std::vector<std::pair<char, int>> b{ { 'U', 2 }, { 'R', 5 }, { 'D', 4 }, { 'L', 7 } };
std::vector<std::vector<std::pair<char, int>>> data{ a, b };
Routes tmp;
tmp.addRoutes(data);
REQUIRE(tmp.getClosestIntersectionManhattanDist() == 5);
REQUIRE(tmp.getSmallestManhattanDist() == 18);
}
SECTION("Test with Advents example 1")
{
std::vector<std::pair<char, int>> a{ { 'R', 75 }, { 'D', 30 }, { 'R', 83 }, { 'U', 83 }, { 'L', 12 },
{ 'D', 49 }, { 'R', 71 }, { 'U', 7 }, { 'L', 72 } };
std::vector<std::pair<char, int>> b{ { 'U', 62 }, { 'R', 66 }, { 'U', 55 }, { 'R', 34 },
{ 'D', 71 }, { 'R', 55 }, { 'D', 58 }, { 'R', 83 } };
std::vector<std::vector<std::pair<char, int>>> data{ a, b };
Routes tmp;
tmp.addRoutes(data);
REQUIRE(tmp.getClosestIntersectionManhattanDist() == 159);
REQUIRE(tmp.getSmallestManhattanDist() == 610);
}
SECTION("Test with Advents example 2")
{
std::vector<std::pair<char, int>> a{ { 'R', 98 }, { 'U', 47 }, { 'R', 26 }, { 'D', 63 },
{ 'R', 33 }, { 'U', 87 }, { 'L', 62 }, { 'D', 20 },
{ 'R', 33 }, { 'U', 53 }, { 'R', 51 } };
std::vector<std::pair<char, int>> b{ { 'U', 98 }, { 'R', 91 }, { 'D', 20 }, { 'R', 16 }, { 'D', 67 },
{ 'R', 40 }, { 'U', 7 }, { 'R', 15 }, { 'U', 6 }, { 'R', 7 } };
std::vector<std::vector<std::pair<char, int>>> data{ a, b };
Routes tmp;
tmp.addRoutes(data);
REQUIRE(tmp.getClosestIntersectionManhattanDist() == 135);
REQUIRE(tmp.getSmallestManhattanDist() == 410);
}
}
|
c++
| 16 | 0.423778 | 110 | 45.355556 | 45 |
starcoderdata
|
<?php
namespace DragonCode\Notifex\Services;
use DragonCode\Notifex\Facades\App;
use DragonCode\Notifex\Facades\Http;
use Exception;
use Illuminate\View\Factory;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
use Throwable;
class ExceptionHandler
{
/**
* The view factory implementation.
*
* @var \Illuminate\View\Factory
*/
protected $view;
/**
* Create a new exception handler instance.
*
* @param \Illuminate\View\Factory $view
*/
public function __construct(Factory $view)
{
$this->view = $view;
}
/**
* Create a string for the given exception.
*
* @param Throwable $exception
*
* @return string
*/
public function convertExceptionToString(Throwable $exception)
{
$environment = $this->environment();
$host = $this->host();
return $this->view
->make('notifex::subject', compact('exception', 'environment', 'host'))
->render();
}
/**
* Create a html for the given exception.
*
* @param Throwable $exception
*
* @return string
*/
public function convertExceptionToHtml(Throwable $exception)
{
$flat = $this->getFlattenedException($exception);
$handler = new SymfonyExceptionHandler();
return $this->decorate($handler->getContent($flat), $handler->getStylesheet($flat), $flat);
}
/**
* Converts the Exception in a PHP Exception to be able to serialize it.
*
* @param Throwable $exception
*
* @return \Symfony\Component\Debug\Exception\FlattenException
*/
protected function getFlattenedException(Throwable $exception)
{
if (! $exception instanceof FlattenException) {
$exception = FlattenException::createFromThrowable($exception);
}
return $exception;
}
/**
* Get the html response content.
*
* @param string $content
* @param string $css
* @param Exception|Throwable $exception
*
* @return string
*/
protected function decorate($content, $css, $exception)
{
return $this->view
->make('notifex::body', compact('content', 'css', 'exception'))
->render();
}
protected function environment(): string
{
return App::environment();
}
protected function host(): string
{
return Http::host();
}
}
|
php
| 14 | 0.605325 | 99 | 23.09434 | 106 |
starcoderdata
|
package net
import (
"net"
)
// IsLoopback returns if and only if the provided address
// is a loopback address.
func IsLoopback(addr string) bool {
a, err := net.ResolveTCPAddr("tcp", addr)
return err == nil && a.IP.IsLoopback()
}
|
go
| 9 | 0.691983 | 57 | 18.75 | 12 |
starcoderdata
|
namespace WorkInOrder
{
public enum Format
{
Neutral,
Highlight,
Positive,
Negative,
}
}
|
c#
| 4 | 0.527778 | 22 | 12.181818 | 11 |
starcoderdata
|
__author__ = 'beast'
import unittest, json
from flask import testing
from granule.granular.store import Store
from granule.granular.auth import LDAPAuth
from granule.application import app
class TestFlaskUnit(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def tearDown(self):
pass
def test_get_home(self):
response = self.app.get("/")
self.assertEqual(response.status_code, 200)
def test_get_activities(self):
response = self.app.get("/api/2015-05-30/activity/")
self.assertEqual(response.status_code, 401)
self.assertTrue('WWW-Authenticate' in response.headers)
class TestLDAPAuthUnit(unittest.TestCase):
def setUp(self):
self.auth = LDAPAuth('172.17.0.1', port=389, encryption=None, user_dn="cn=%s,dc=example,dc=org", supported_group="group")
def tearDown(self):
pass
def test_setup_ldap(self):
self.assertIsNotNone(self.auth)
def test_auth_success(self):
self.assertTrue(self.auth.authenticate("admin", "admin"))
self.assertIsNotNone(self.auth)
def test_auth_failure(self):
self.assertFalse(self.auth.authenticate("admin", "fail"))
self.assertIsNotNone(self.auth)
def test_group_failure(self):
self.assertFalse(self.auth.check_user_in_group("admin"))
self.assertIsNotNone(self.auth)
class TestGranuleUnit(unittest.TestCase):
def setUp(self):
self.g = Store("172.17.0.1")
def tearDown(self):
self.g.r.flushdb()
def get_user_id(self):
username = "user_99"
password = "
user_object = self.g.create_user(username, password)
user_object_loggedin = self.g.login(username, password)
return user_object_loggedin["user_id"]
def test_basic_get_activity(self):
self.get_user_id()
inputs = json.dumps({"id_a":1})
activity = {"input": inputs,"id":1}
result = self.g.run_activity(inputs)
self.assertIsNotNone(result)
self.assertEquals(result, 1)
self.assertEquals(activity, self.g.get_activity(result))
def test_basic_get_result(self):
self.get_user_id()
inputs = json.dumps({"id_a":1})
results = json.dumps({"result_a":123})
activity = {"input": inputs,"id":1}
activity_id = self.g.run_activity(inputs)
self.g.add_result(activity_id, results)
activity_with_result = activity
activity_with_result["result"] = results
self.assertEquals(activity_with_result, self.g.get_activity(activity_id))
def test_get_activities(self):
self.get_user_id()
inputs = json.dumps({"id_a":1})
activity_id = self.g.run_activity(inputs)
activity_id_two = self.g.run_activity(inputs)
activity_id_three = self.g.run_activity(inputs)
self.assertEquals([str(activity_id), str(activity_id_two), str(activity_id_three)], self.g.get_all_activities())
def test_get_user_activities(self):
user_id = self.get_user_id()
inputs = json.dumps({"id_a":1})
activity_id = self.g.run_activity(inputs)
activity_id_two = self.g.run_activity(inputs)
activity_id_three = self.g.run_activity(inputs)
self.assertEquals([str(activity_id), str(activity_id_two), str(activity_id_three)], self.g.get_user_activities(user_id))
def test_login(self):
username = "user_1"
password = "
user_object = self.g.create_user(username, password)
user_object_loggedin = self.g.login(username, password)
self.assertIsNotNone(user_object)
self.assertIsNotNone(user_object_loggedin)
self.assertEquals(user_object, user_object_loggedin)
def test_create_user(self):
username = "user_1"
password = "
user_object = self.g.create_user(username, password)
self.assertIsNotNone(user_object)
self.assertEquals(user_object["user_id"],'1')
if __name__ == '__main__':
unittest.main()
|
python
| 12 | 0.631106 | 129 | 22.254237 | 177 |
starcoderdata
|
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the CC-by-NC license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
try:
from lattices import c_lattices
swig_ptr = c_lattices.swig_ptr
except ImportError:
c_lattices = None
class Comb:
""" a Pascal triangle """
def __init__(self, npas=100):
pascal = [[1] for i in range(npas)]
for i in range(npas):
for j in range(1, i + 1):
pascal[i].append(pascal[i - 1][j] + pascal[i - 1][j - 1])
pascal[i].append(0)
self.pascal = pascal
def __call__(self, n, k):
return self.pascal[n][k] if k <= n else 0
# function to compute a binomial coefficient
if c_lattices is None:
comb = Comb()
else:
comb = c_lattices.cvar.comb
def count_comb(x):
"""count number of distinct permutations of an array that contains
duplicate values"""
x = np.array(x)
n = len(x)
accu = 1
for v in np.unique(x):
nv = int((x == v).sum())
accu *= int(comb(n, nv))
n -= nv
# bits used for signs
accu *= 2 ** int((x != 0).sum())
return accu
def sum_of_sq(total, v, n):
"""find all positive integer vectors of size n:
- whose squared elements sum to total
- maximium value is v
"""
if total < 0:
return []
elif total == 0:
return [[0] * n]
elif n == 1:
while v * v > total:
v -= 1
if v * v == total:
return [[v]]
else:
return []
else:
res = []
for vi in range(v, -1, -1):
res += [[vi] + vv for vv in
sum_of_sq(total - vi * vi, vi, n - 1)]
return res
def compute_atoms(d, r2):
"""Find atoms that define the Zn sphere of dimension d and squared
radius r2"""
v = int(1 + np.sqrt(r2)) # max value of a component
if c_lattices is None:
atoms = sum_of_sq(r2, v, d)
return np.array(atoms)
else:
atoms = c_lattices.sum_of_sq(r2, v, d)
return c_lattices.vector_to_array(atoms).reshape(-1, d)
class ZnCodecC:
def __init__(self, d, r2):
self.znc = c_lattices.ZnSphereCodec(d, r2)
atoms = c_lattices.vector_to_array(self.znc.voc)
atoms = atoms.reshape(-1, d)
# recompute instead of using self.znc.nv because it is limited
# to 64 bit
self.nv = sum([count_comb(atom) for atom in atoms])
self.code_size = self.znc.code_size
if d & (d - 1) == 0:
# d is a power of 2. Then we can use a ZnSphereCodecRec as
# codec (faster for decoding)
self.znc_rec = c_lattices.ZnSphereCodecRec(d, r2)
else:
self.znc_rec = None
def quantize(self, x):
x = np.ascontiguousarray(x, dtype='float32')
n, d = x.shape
assert d == self.znc.dim
c = np.empty((n, d), dtype='float32')
dps = np.empty(n, dtype='float32')
self.znc.search_multi(n,
swig_ptr(x), swig_ptr(c),
swig_ptr(dps))
return c
def encode(self, x):
assert self.nv < 2 ** 64
n, d = x.shape
assert d == self.znc.dim
codes = np.empty(n, dtype='uint64')
if not self.znc_rec:
self.znc.encode_multi(n, swig_ptr(x),
swig_ptr(codes))
else:
# first quantizer then encode
centroids = self.quantize(x)
self.znc_rec.encode_multi(n, swig_ptr(centroids),
swig_ptr(codes))
return codes
def decode(self, codes):
n, = codes.shape
x = np.empty((n, self.znc.dim), dtype='float32')
decoder = self.znc_rec or self.znc
decoder.decode_multi(n, swig_ptr(codes),
swig_ptr(x))
return x
def find_nn(self, codes, xq):
""" find the nearest code of each vector of xq
(returns dot products, not distances)
"""
assert self.nv < 2 ** 64
nc, = codes.shape
nq, d = xq.shape
assert d == self.znc.dim
ids = np.empty(nq, dtype='int64')
dis = np.empty(nq, dtype='float32')
decoder = self.znc_rec or self.znc
decoder.find_nn(nc, swig_ptr(codes), nq, swig_ptr(xq),
swig_ptr(ids), swig_ptr(dis))
return ids, dis
class ZnCodecPy:
def __init__(self, d, r2):
self.atoms = compute_atoms(d, r2)
self.atoms = np.sort(self.atoms, axis=1)
self.nv = sum([count_comb(atom) for atom in self.atoms])
def quantize(self, x):
n, d = x.shape
assert d == self.atoms.shape[1]
x_abs = np.abs(x)
x_mod = np.sort(x_abs, axis=1)
x_order = np.argsort(np.argsort(x_abs, axis=1), axis=1)
matches = np.argmax(np.dot(x_mod, self.atoms.T), axis=1)
x_recons = self.atoms[matches]
q_abs = x_recons[np.tile(np.arange(n).reshape(-1, 1), d), x_order]
q = q_abs * np.sign(x)
return q.astype('float32')
if c_lattices is None:
ZnCodec = ZnCodecPy
else:
ZnCodec = ZnCodecC
|
python
| 16 | 0.529947 | 74 | 27.989011 | 182 |
research_code
|
#include "odfaeg/Graphics/Vulkan/swapchain.hpp"
#include
#include
#include
#include "odfaeg/Graphics/Vulkan/device.hpp"
#include "odfaeg/Graphics/Vulkan/instance.hpp"
#include "odfaeg/Graphics/Vulkan/vulkan_window.hpp"
namespace odfaeg {
namespace {
[[nodiscard]] VkSurfaceFormatKHR choose_surface_format(std::span<const VkSurfaceFormatKHR> availableFormats) {
for (const auto &availableFormat : availableFormats) {
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLORSPACE_SRGB_NONLINEAR_KHR) {
return availableFormat;
}
}
return *availableFormats.begin();
}
[[nodiscard]] VkPresentModeKHR choose_present_mode(std::span<const VkPresentModeKHR> availablePresentModes) {
for (const auto &availablePresentMode : availablePresentModes) {
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
[[nodiscard]] VkExtent2D choose_extent(VkSurfaceCapabilitiesKHR capabilities, GLFWwindow *window) {
if (capabilities.currentExtent.width != std::numeric_limits ||
capabilities.currentExtent.height != std::numeric_limits {
return capabilities.currentExtent;
} else {
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D extent = {static_cast static_cast
extent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, extent.width));
extent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, extent.height));
return extent;
}
}
} // namespace
Swapchain::Swapchain(std::shared_ptr instance, std::shared_ptr device, const VulkanWindow &window)
: m_instance(std::move(instance)), m_device(std::move(device)) {
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_device->getPhysicalDEvice(), m_instance->getWindowSurface(), &m_capabilities);
// query surface formats
auto surfaceFormatCount = 0u;
vkGetPhysicalDeviceSurfaceFormatsKHR(m_device->getPhysicalDEvice(), m_instance->getWindowSurface(), &surfaceFormatCount, nullptr);
m_formats.resize(surfaceFormatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(m_device->getPhysicalDEvice(), m_instance->getWindowSurface(), &surfaceFormatCount, m_formats.data());
// query surface present modes
auto surfacePresentModeCount = 0u;
vkGetPhysicalDeviceSurfacePresentModesKHR(m_device->getPhysicalDEvice(), m_instance->getWindowSurface(), &surfacePresentModeCount, nullptr);
m_present_modes.resize(surfacePresentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(m_device->getPhysicalDEvice(), m_instance->getWindowSurface(), &surfacePresentModeCount, m_present_modes.data());
m_swapchain = createSwapchain(window);
}
Swapchain::~Swapchain() noexcept { vkDestroySwapchainKHR(m_device->getLogicalDevice(), m_swapchain, nullptr); }
[[nodiscard]] VkSwapchainKHR Swapchain::createSwapchain(const VulkanWindow &window) {
auto surfaceFormat = choose_surface_format(m_formats);
auto presentMode = choose_present_mode(m_present_modes);
auto surfaceExtent = choose_extent(m_capabilities, window.getWindow());
m_image_count = m_capabilities.minImageCount + 1;
if (m_capabilities.maxImageCount > 0 && m_image_count > m_capabilities.maxImageCount) {
m_image_count = m_capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR swapchainInfo{};
swapchainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainInfo.surface = m_instance->getWindowSurface();
swapchainInfo.minImageCount = m_image_count;
swapchainInfo.imageFormat = surfaceFormat.format;
swapchainInfo.imageColorSpace = surfaceFormat.colorSpace;
swapchainInfo.imageExtent = surfaceExtent;
swapchainInfo.imageArrayLayers = 1;
swapchainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
const std::array familyIndices = {m_device->getFamilyIndices().graphics_family.value(), m_device->getFamilyIndices().present_family.value()};
if (m_device->getFamilyIndices().graphics_family != m_device->getFamilyIndices().present_family) {
swapchainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swapchainInfo.queueFamilyIndexCount = 1;
swapchainInfo.pQueueFamilyIndices = familyIndices.data();
} else {
swapchainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
swapchainInfo.preTransform = m_capabilities.currentTransform;
swapchainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchainInfo.presentMode = presentMode;
swapchainInfo.clipped = VK_TRUE;
VkSwapchainKHR swapchain = nullptr;
if (vkCreateSwapchainKHR(m_device->getLogicalDevice(), &swapchainInfo, nullptr, &swapchain) != VK_SUCCESS) {
return swapchain;
} else {
throw std::runtime_error("failed to create swapchain!");
}
}
} // namespace odfaeg
|
c++
| 18 | 0.679845 | 163 | 48.486957 | 115 |
starcoderdata
|
/*Include des librairies*/
#include
#include
/*Termine l'application*/
extern void quit(Widget, void *);
extern Widget Entete, Question, Reponse, Nbrpoints, Nbrpointstotal, Nomjoueur, Bquit, NiveauDifficulte, Difficile, Facile;
extern Widget bouton_validation_reponse, bouton_question_suivante,Fin,Aide, aide1, aide2,scrolniveau,niveau_jeu,temps_ecoule,nb_quest_faite;
extern void init_graine_random(void);
extern void validation_question(char*);
extern void questsuiv(Widget,void*);
extern void aide(Widget, void* );
extern void questfac(Widget , void *);
extern void questdif(Widget , void *);
extern void scroll_func(Widget,float,void*);
extern void Pour_temp(void*,XtIntervalId*);
extern void fin_questions(Widget, void*);
|
c
| 6 | 0.765152 | 140 | 25.4 | 30 |
starcoderdata
|
# Solution to day 25 of AOC 2020, Combo Breaker.
# https://adventofcode.com/2020/day/25
import sys
VERBOSE = ('-v' in sys.argv)
def transforms(subject_number: int, target_pk) -> int:
"""For the parm subject number. Transform the subject number several times until it matches the target public key.
Return the number of iterations needed"""
# "To transform a subject number, start with the value 1."
result = 1
loop = 0
# "Then, a number of times called the loop size, perform the following steps:
# Set the value to itself multiplied by the subject number.
# Set the value to the remainder after dividing the value by 20201227."
while result != target_pk:
loop += 1
result = (result * subject_number) % 20201227
# if VERBOSE:
# print('loop, result:', loop, result)
return loop
def calc_encryption_key(subject_number: int, loop_size: int) -> int:
"""For a parm subject number (a PK) and loop size, return the encryption key."""
# "Transforming the subject number of 17807724 (the door's public key) with a loop size of 8 (the card's loop size)
# produces the encryption key, 14897079."
result = 1
for loop in range(loop_size):
result = (result * subject_number) % 20201227
return result
def main():
filename = sys.argv[1]
f = open(filename)
whole_text = f.read()
f.close()
card_pk_txt, door_pk_txt = whole_text.split('\n')
card_pk, door_pk = int(card_pk_txt), int(door_pk_txt)
if VERBOSE:
print('card_pk, door_pk', card_pk, door_pk)
card_loop_size = transforms(subject_number=7, target_pk=card_pk)
door_loop_size = transforms(subject_number=7, target_pk=door_pk)
if VERBOSE:
print('card_loop_size, door_loop_size:', card_loop_size, door_loop_size)
encryption_key = calc_encryption_key(subject_number=card_pk, loop_size=door_loop_size)
print('Part 1:', encryption_key)
if __name__ == "__main__":
main()
|
python
| 10 | 0.651198 | 119 | 28.470588 | 68 |
starcoderdata
|
// Copyright by 2012. Licensed under MIT License: http://www.opensource.org/licenses/MIT
package com.barrybecker4.game.multiplayer.poker.ui.dialog;
import com.barrybecker4.common.geometry.ByteLocation;
import com.barrybecker4.game.multiplayer.poker.hand.Hand;
import com.barrybecker4.game.multiplayer.poker.ui.render.HandRenderer;
import javax.swing.*;
import java.awt.*;
/**
* Shows the player the contents of their hand so they can bet on it.
* @author
*/
final class PokerHandViewer extends JPanel {
private Hand hand;
private HandRenderer handRenderer = new HandRenderer();
public PokerHandViewer(Hand hand) {
this.hand = new Hand(hand.getCards());
this.hand.setFaceUp(true);
this.setPreferredSize(new Dimension(400, 120));
}
@Override
protected void paintComponent(Graphics g) {
handRenderer.render((Graphics2D) g, new ByteLocation(0, 2), hand, 22);
}
}
|
java
| 3 | 0.732817 | 96 | 31.28125 | 32 |
starcoderdata
|
/*-
* #%L
* Coffee
* %%
* Copyright (C) 2020 i-Cell Mobilsoft Zrt.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package hu.icellmobilsoft.coffee.module.mongodb.codec.time.internal;
import java.text.MessageFormat;
import java.time.DateTimeException;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.enterprise.inject.Vetoed;
import org.bson.BsonInvalidOperationException;
import org.bson.BsonReader;
import org.bson.BsonType;
import org.bson.Document;
import org.bson.codecs.Decoder;
import org.bson.codecs.DecoderContext;
/**
* CodecsUtil for handling value exceptions, and documents
*
* https://github.com/cbartosiak/bson-codecs-jsr310
*
* @author balazs.joo
* @since 1.0.0
*/
@Vetoed
public final class CodecsUtil {
private CodecsUtil() {
}
/**
* Unifies encode runtime exceptions.
*
* @param valueSupplier
* value supplier
* @param valueConsumer
* value consumer
* @param
* input value type
*/
public static void translateEncodeExceptions(Supplier valueSupplier, Consumer valueConsumer) {
Value value = valueSupplier.get();
try {
valueConsumer.accept(value);
} catch (ArithmeticException | DateTimeException | NumberFormatException ex) {
throw new BsonInvalidOperationException(MessageFormat.format("The value [{0}] is not supported", value), ex);
}
}
/**
* Unifies decode runtime exceptions.
*
* @param valueSupplier
* value supplier
* @param valueConverter
* value converter function
* @param
* input value type
* @param
* decoded result type
* @return decoding result
*/
public static <Value, Result> Result translateDecodeExceptions(Supplier valueSupplier, Function<Value, Result> valueConverter) {
Value value = valueSupplier.get();
try {
return valueConverter.apply(value);
} catch (ArithmeticException | DateTimeException | IllegalArgumentException ex) {
throw new BsonInvalidOperationException(MessageFormat.format("The value [{0}] is not supported", value), ex);
}
}
/**
* Reads BSON documents and decodes fields.
*
* @param reader
* BSON reader
* @param decoderContext
* context
* @param fieldDecoders
* {@link Map} of field decoders
* @return BSON {@link Document}
*/
public static Document readDocument(BsonReader reader, DecoderContext decoderContext, Map<String, Decoder fieldDecoders) {
Document document = new Document();
reader.readStartDocument();
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
String fieldName = reader.readName();
if (fieldDecoders.containsKey(fieldName)) {
document.put(fieldName, fieldDecoders.get(fieldName).decode(reader, decoderContext));
} else {
throw new BsonInvalidOperationException(MessageFormat.format("The field [{0}] is not expected here", fieldName));
}
}
reader.readEndDocument();
return document;
}
/**
* Returns field value from document.
*
* @param document
* document to return field value from
* @param key
* key of field to return
* @param clazz
* class of value to return
* @param
* type of value to return
* @return desired field value
*/
public static Value getFieldValue(Document document, Object key, Class clazz) {
try {
Value value = document.get(key, clazz);
if (value == null) {
throw new BsonInvalidOperationException(MessageFormat.format("The value of the field [{0}] is null", key));
}
return value;
} catch (ClassCastException ex) {
throw new BsonInvalidOperationException(
MessageFormat.format("The value of the field [{0}] is not of the type [{1}]", key, clazz.getName()), ex);
}
}
}
|
java
| 15 | 0.631342 | 139 | 32.027027 | 148 |
starcoderdata
|
<?php
return [
'genders' => [
'MALE' => 'Masculino',
'FEMALE' => 'Feminino',
],
'boolean' => [
'0' => 'Não',
'1' => 'Sim'
],
'payment_status' => [
'DONE' => 'Realizado',
'NOT_DONE' => 'Não Realizado',
'PENDING' => 'Pendente',
],
/*'receiving_ways' => [
'ADDRESS' => 'Endereço do cliente',
'IN_STORE' => 'Retirar na Loja',
],*/
'crop' => [
'image' => [
"width" => 800,
"height" => 600,
],
],
];
|
php
| 9 | 0.367459 | 43 | 19.259259 | 27 |
starcoderdata
|
using UnityEngine;
using System.Collections;
public class ClickHeatcore : MonoBehaviour {
void OnMouseDown()
{
print ("mouse down on heatcore");
Skills.HeatcoreNum ++;
Destroy (this.gameObject);
}
}
|
c#
| 11 | 0.720379 | 44 | 16.583333 | 12 |
starcoderdata
|
function oneToLeft() {
var len= document.getElementById("select1").options.length;
for (var i = 0; i < len; i++)
{
if (document.getElementById("select1").options[i].selected==true)
{
var txt = document.getElementById("select1").options[i].text;
var val = document.getElementById("select1").options[i].value;
var newOption = new Option(txt, val);
document.getElementById("select2").options[document.getElementById("select2").options.length]=newOption;
var selectedIndex = document.getElementById("select1").options.selectedIndex;
document.getElementById("select1").options[selectedIndex] = null;
}
}
}
function allToLeft() {
var len= document.getElementById("select1").options.length;
for (var i = 0; i < len; i++)
{
var txt = document.getElementById("select1").options[i].text;
var val = document.getElementById("select1").options[i].value;
var newOption = new Option(txt, val);
document.getElementById("select2").options[document.getElementById("select2").options.length]=newOption;
}
document.getElementById("select1").options.length = 0;
}
function oneToRight() {
var len= document.getElementById("select2").options.length;
for (var i = 0; i < len; i++)
{
if (document.getElementById("select2").options[i].selected==true)
{
var txt = document.getElementById("select2").options[i].text;
var val = document.getElementById("select2").options[i].value;
var newOption = new Option(txt, val);
document.getElementById("select1").options[document.getElementById("select1").options.length]=newOption;
var selectedIndex = document.getElementById("select2").options.selectedIndex;
document.getElementById("select2").options[selectedIndex] = null;
}
}
}
function allToRight() {
var len= document.getElementById("select2").options.length;
for (var i = 0; i < len; i++)
{
var txt = document.getElementById("select2").options[i].text;
var val = document.getElementById("select2").options[i].value;
var newOption = new Option(txt, val);
document.getElementById("select1").options[document.getElementById("select1").options.length]=newOption;
}
document.getElementById("select2").options.length = 0;
}
|
javascript
| 15 | 0.702679 | 106 | 37.637931 | 58 |
starcoderdata
|
#ifndef SIAR_MODEL__HPP__
#define SIAR_MODEL__HPP__
#include "siar_controller/command_evaluator.hpp"
#include "siar_planner/NodeState.hpp"
#include "ros/ros.h"
#include
#include
class SiarModel
{
public:
//! @brief Constructor from NodeHandles
SiarModel(ros::NodeHandle &nh, ros::NodeHandle &pn);
void occupancyGridCallback(nav_msgs::OccupancyGridConstPtr msg);
visualization_msgs::Marker testIntegration(NodeState &st, bool relaxed = false);
//! @brief Integrates the model and returns the cost associated with
//! @return Negative --> collision. Positive --> Arc's longitude
double integrate(NodeState &st, geometry_msgs::Twist &cmd, double T, bool relaxed = false);
double integrateTransition(NodeState &st, geometry_msgs::Twist &cmd, double T);
double integrateTransition2(NodeState &st, geometry_msgs::Twist &cmd, double T);
//! @brief Integrates the model and returns the cost associated with
//! @return Negative --> collision. Positive --> Arc's longitude
double integrate(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T, bool relaxed);
double integrateTransition(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T);
double integrateTransition2(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T);
virtual geometry_msgs::Twist generateRandomCommand();
virtual geometry_msgs::Twist generateRandomCommandJustRot();
inline bool isInit() const {return map_init;}
// inline double costWheelsQnew() const {return cost_wheels;}
double costWheelsQnear(double x, double y, double th);
inline std::string getFrameID() const {
if (map_init) {
return m_world.header.frame_id;
}
}
visualization_msgs::Marker getMarker(NodeState &st, int id = 0);
inline bool isCollision(NodeState &st) {
bool ret_val;
m_ce.applyFootprint(st.state[0], st.state[1], st.state[2], m_world, ret_val);
return ret_val;
}
inline bool isCollisionTransition(NodeState &st) {
bool ret_val, r2;
m_ce.applyFootprintTransition(st.state[0], st.state[1], st.state[2], m_world, ret_val, r2);
return ret_val;
}
inline double getMinWheel() const {
// return m_ce.getMinWheel();
return -1.0;
}
inline void decreaseWheels(double decrement, double last_wheel) {
double m_w = m_ce.getMinWheelLeft() - decrement; // Decrease the minimum allowed wheel on the floor
m_w = (m_w < last_wheel)?last_wheel:m_w; // Check if the allowed wheel is below the maximum
m_ce.setMinWheelLeft(m_w);
// Right wheel
m_w = m_ce.getMinWheelRight() - decrement; // Decrease the minimum allowed wheel on the floor
m_w = (m_w < last_wheel)?last_wheel:m_w; // Check if the allowed wheel is below the maximum
m_ce.setMinWheelRight(m_w);
}
inline void setMinWheel(double v) {
m_ce.setMinWheelLeft(v);
m_ce.setMinWheelRight(v);
}
inline double getWorldMaxX() const{
return m_world.info.resolution * m_world.info.height * 0.5;
}
inline double getWorldMaxY() const{
return m_world.info.resolution * m_world.info.width * 0.5;
}
siar_controller::CommandEvaluator m_ce;
nav_msgs::OccupancyGrid m_world;
protected:
// nav_msgs::OccupancyGrid m_world;
// siar_controller::CommandEvaluator m_ce;
double cost_wheels, cost_wheels_q_near;
bool map_init;
template< class RealType = double > class uniform_real_distribution;
// Random numbers
std::random_device rd;
std::mt19937 gen;
std::uniform_real_distribution<> dis;
ros::Subscriber map_sub;
visualization_msgs::Marker m;
};
SiarModel::SiarModel(ros::NodeHandle &nh, ros::NodeHandle& pn):m_ce(pn), map_init(false), gen(rd()), dis(-m_ce.getCharacteristics().theta_dot_max, m_ce.getCharacteristics().theta_dot_max)
{
map_sub = nh.subscribe("/altitude_map", 2, &SiarModel::occupancyGridCallback, this);
}
void SiarModel::occupancyGridCallback(nav_msgs::OccupancyGridConstPtr msg)
{
map_init = true;
m_world = *msg;
m_ce.initializeFootprint(*msg);
}
double SiarModel::integrate(NodeState& st, geometry_msgs::Twist& cmd, double T, bool relaxed)
{
return integrate(m, st, cmd, T, relaxed);
}
double SiarModel::integrate(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T, bool relaxed)
{
geometry_msgs::Twist v_ini;
v_ini.linear.x = m_ce.getCharacteristics().v_max;
if (st.state.size() < 3) {
ROS_ERROR("SiarModel::integrate --> cannot integrate the model --> too few states. State size: %u", (unsigned int) st.state.size());
}
m_ce.setDeltaT(T);
double ret_val;
if (!relaxed)
ret_val = m_ce.evaluateTrajectory(v_ini, cmd, cmd, m_world, m, st.state[0], st.state[1], st.state[2]);
else
ret_val = m_ce.evaluateTrajectoryRelaxed(v_ini, cmd, cmd, m_world, m, st.state[0], st.state[1], st.state[2]);
st.state = m_ce.getLastState();
return ret_val;
}
double SiarModel::integrateTransition(NodeState& st, geometry_msgs::Twist& cmd, double T)
{
return integrateTransition(m, st, cmd, T);
}
double SiarModel::integrateTransition(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T)
{
geometry_msgs::Twist v_ini;
v_ini.linear.x = m_ce.getCharacteristics().v_max;
if (st.state.size() < 3) {
ROS_ERROR("SiarModel::integrate --> cannot integrate the model --> too few states. State size: %u", (unsigned int) st.state.size());
}
m_ce.setDeltaT(T);
double ret_val;
ret_val = m_ce.evaluateTrajectoryTransition(v_ini, cmd, cmd, m_world, m, st.state[0], st.state[1], st.state[2]);
st.state = m_ce.getLastState();
cost_wheels = m_ce.getCostWheelsQnew();
return ret_val;
}
double SiarModel::integrateTransition2(NodeState& st, geometry_msgs::Twist& cmd, double T)
{
return integrateTransition2(m, st, cmd, T);
}
double SiarModel::integrateTransition2(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T)
{
geometry_msgs::Twist v_ini;
v_ini.linear.x = m_ce.getCharacteristics().v_max;
if (st.state.size() < 3) {
ROS_ERROR("SiarModel::integrate --> cannot integrate the model --> too few states. State size: %u", (unsigned int) st.state.size());
}
m_ce.setDeltaT(T);
double ret_val;
ret_val = m_ce.evaluateTrajectoryTransition(v_ini, cmd, cmd, m_world, m, st.state[0], st.state[1], st.state[2]);
st.state = m_ce.getLastState();
cost_wheels = m_ce.getCostWheelsQnew();
return ret_val;
}
double SiarModel::costWheelsQnear(double x, double y, double th){
bool collision = false;
bool collision_wheels=false;
double cost_wheels_q_near = m_ce.applyFootprintTransition(x, y, th, m_world, collision, collision_wheels);
return cost_wheels_q_near;
}
// double SiarModel::integrate(visualization_msgs::Marker& m, NodeState& st, geometry_msgs::Twist& cmd, double T, bool relaxed)
// {
// geometry_msgs::Twist v_ini;
// double ret_val;
// if (st.state.size() < 3) {
// ROS_ERROR("SiarModel::integrate --> cannot integrate the model --> too few states. State size: %u", (unsigned int) st.state.size());
// }
// v_ini.linear.x = m_ce.getCharacteristics().v_max;
// m_ce.setDeltaT(T);
// ret_val = m_ce.evaluateTrajectoryTransition(v_ini, cmd, cmd, m_world, m, st.state[0], st.state[1], st.state[2]);
// st.state = m_ce.getLastState();
// return ret_val;
// }
geometry_msgs::Twist SiarModel::generateRandomCommand() {
geometry_msgs::Twist ret;
ret.linear.x = m_ce.getCharacteristics().v_max;
ret.angular.z = dis(gen);
ret.linear.y = ret.linear.z = ret.angular.x = ret.angular.y = 0.0;
return ret;
}
geometry_msgs::Twist SiarModel::generateRandomCommandJustRot() {
geometry_msgs::Twist ret;
ret.linear.x = 0.02;
ret.angular.z = (dis(gen));
ret.linear.y = ret.linear.z = ret.angular.x = ret.angular.y = 0.0;
return ret;
}
visualization_msgs::Marker SiarModel::getMarker(NodeState& st, int id)
{
visualization_msgs::Marker m;
if (m_ce.getFootprint() != NULL) {
m_ce.getFootprint()->addPoints(st.state[0], st.state[1], st.state[2], m, id, true, m_world.header.frame_id);
} else {
ROS_ERROR("SiarModel::getMarker: --> Footprint is not initialized");
}
return m;
}
visualization_msgs::Marker SiarModel::testIntegration(NodeState& st, bool relaxed)
{
auto comm = generateRandomCommand();
double cost = integrate(st, comm, 0.5, relaxed);
ROS_INFO("SiarModel::testIntegration --> Command = %f, %f --> Cost = %f", comm.linear.x, comm.angular.z, cost);
return m;
}
#endif
|
c++
| 13 | 0.683426 | 187 | 29.575972 | 283 |
starcoderdata
|
package com.mvc.controller;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.mvc.entity.Student;
import com.mvc.service.StudentService;
@Controller
@RequestMapping("/student.do")
public class StudentController {
protected final transient Log log = LogFactory
.getLog(StudentController.class);
@Autowired
private StudentService studentService;
public StudentController(){
}
@RequestMapping
public String load(ModelMap modelMap){
List list = studentService.getStudentList();
modelMap.put("list", list);
return "student";
}
@RequestMapping(params = "method=add")
public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
return "student_add";
}
@RequestMapping(params = "method=save")
public String save(HttpServletRequest request, ModelMap modelMap) throws Exception{
String user = new String(request.getParameter("user").getBytes("iso-8859-1"), "utf-8");
String psw = new String(request.getParameter("psw").getBytes("iso-8859-1"), "utf-8");
// String user = request.getParameter("user");
// String psw = request.getParameter("psw");
System.out.println("user="+user);
System.out.println("pwd="+psw);
Student st = new Student();
st.setUser(user);
st.setPsw(psw);
try{
studentService.save(st);
modelMap.put("addstate", "添加成功");
}
catch(Exception e){
log.error(e.getMessage());
modelMap.put("addstate", "添加失败");
}
return "student_add";
}
@RequestMapping(params = "method=del")
public void del(@RequestParam("id") String id, HttpServletResponse response){
try{
Student st = new Student();
st.setId(Integer.valueOf(id));
studentService.delete(st);
response.getWriter().print("{\"del\":\"true\"}");
}
catch(Exception e){
log.error(e.getMessage());
e.printStackTrace();
}
}
}
|
java
| 13 | 0.708734 | 91 | 26.831325 | 83 |
starcoderdata
|
package com.smart.framework.proxy;
import java.lang.reflect.Method;
import java.util.List;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* 基于CGLIB的代理工厂类
*/
public class ProxyFactory {
private Class targetClass;
private List proxyList;
public ProxyFactory(Class targetClass, List proxyList) {
this.targetClass = targetClass;
this.proxyList = proxyList;
}
@SuppressWarnings("unchecked")
public T createProxy() {
return (T) Enhancer.create(targetClass, new MethodInterceptor() {
@Override
public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {
ProxyChain proxyChain = new ProxyChain(targetClass, target, method, args, proxy, proxyList);
proxyChain.doProxyChain();
return proxyChain.getMethodResult();
}
});
}
}
|
java
| 17 | 0.670465 | 118 | 29.085714 | 35 |
starcoderdata
|
pub fn send(&mut self, evt: ClientSendEvent) {
use websocket::ws::sender::Sender;
// Turn the event into a network message
let msg = evt.to_network_msg();
self.sender.send_message(&msg.to_message()).unwrap();
}
|
rust
| 11 | 0.611336 | 61 | 34.428571 | 7 |
inline
|
package Layouts
import (
"fmt"
)
type TestRow struct {
Row
ID int `excelLayout:"column:A,required,min:1"`
Username string `excelLayout:"column:B,required,minLength:6"`
Password string `excelLayout:"column:C,required,minLength:8"`
Avatar string `excelLayout:"column:D,url"`
Fullname string `excelLayout:"column:E,required,maxLength:25"`
Email string `excelLayout:"column:F,required,email,unique"`
Age int `excelLayout:"column:G,required,min:18,max:50"`
Key string `excelLayout:"column:H,required,regex:p([a-z]+)ch"`
}
/**
* Field Tag Parser Test struct
*/
type FiledTagsParserTests struct {
input string
expected fieldTags
errExpected error
}
/**
* Compare expected data with parameter
*/
func (pt *FiledTagsParserTests) compareTo(ft *fieldTags) (bool, []string) {
errors := []string{}
if pt.expected.Column != ft.Column {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Column, recieved: \"%v\"",
pt.expected.Column, ft.Column,
))
}
if pt.expected.CommaSeparatedValue != ft.CommaSeparatedValue {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field CommaSeparatedValue, recieved: \"%v\"",
pt.expected.Column, ft.Column,
))
}
if pt.expected.Email != ft.Email {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Email, recieved: \"%v\"",
pt.expected.Email, ft.Email,
))
}
if pt.expected.Required != ft.Required {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Required, recieved: \"%v\"",
pt.expected.Required, ft.Required,
))
}
if pt.expected.Regex != ft.Regex {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Regex, recieved: \"%v\"",
pt.expected.Regex, ft.Regex,
))
}
if pt.expected.Max != ft.Max {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Max, recieved: \"%v\"",
pt.expected.Max, ft.Max,
))
}
if pt.expected.Min != ft.Min {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Min, recieved: \"%v\"",
pt.expected.Min, ft.Min,
))
}
if pt.expected.Url != ft.Url {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Url, recieved: \"%v\"",
pt.expected.Url, ft.Url,
))
}
if pt.expected.Unique != ft.Unique {
errors = append(errors, fmt.Sprintf(
"Expected \"%v\" for field Unique, recieved: \"%v\"",
pt.expected.Unique, ft.Unique,
))
}
return len(errors) == 0, errors
}
/**
* Row Parser Test struct
*/
type RowParserTests struct {
input []string
expected TestRow
errExpected []error
}
/**
* Compare expected data with parameter
*/
func (rt *RowParserTests) compareTo(r *TestRow) (bool, []string) {
errors := []string{}
if r.ID != rt.expected.ID {
errors = append(
errors,
fmt.Sprintf("ID expected \"%v\", Recived: \"%v\"", rt.expected.ID, r.ID),
)
}
if r.Username != rt.expected.Username {
errors = append(
errors,
fmt.Sprintf("Username expected \"%v\", Recived: \"%v\"", rt.expected.Username, r.Username),
)
}
if r.Password != rt.expected.Password {
errors = append(
errors,
fmt.Sprintf("Password expected \"%v\", Recived: \"%v\"", rt.expected.Password, r.Password),
)
}
if r.Avatar != rt.expected.Avatar {
errors = append(
errors,
fmt.Sprintf("Avatar expected \"%v\", Recived: \"%v\"", rt.expected.Avatar, r.Avatar),
)
}
if r.Fullname != rt.expected.Fullname {
errors = append(
errors,
fmt.Sprintf("Fullname expected \"%v\", Recived: \"%v\"", rt.expected.Fullname, r.Fullname),
)
}
if r.Age != rt.expected.Age {
errors = append(
errors,
fmt.Sprintf("Age expected \"%v\", Recived: \"%v\"", rt.expected.Age, r.Age),
)
}
return len(errors) == 0, errors
}
/**
* Check if an error is in expected errors list
*/
func (rt *RowParserTests) IsErrorExpected(e error) bool {
if rt.errExpected == nil {
return false
}
for _, err := range rt.errExpected {
if err == e {
return true
}
}
return false
}
type StructParserTests struct {
input TestRow
errExpected []error
}
/**
* Check if an error is in expected errors list
*/
func (rt *StructParserTests) IsErrorExpected(e error) bool {
if rt.errExpected == nil {
return false
}
for _, err := range rt.errExpected {
if err == e {
return true
}
}
return false
}
|
go
| 13 | 0.640359 | 94 | 22.365591 | 186 |
starcoderdata
|
using System;
using System.IO;
using System.Windows.Forms;
namespace Encrypter
{
public partial class Form_EULA : Form
{
public Form_EULA()
{
InitializeComponent();
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Accept_Click(object sender, EventArgs e)
{
string username = Environment.UserName;
StreamWriter f2 = new StreamWriter("C:\\Users\\" + username + "\\AppData\\accept.txt");
f2.WriteLine("accepted");
f2.Close();
Close();
}
}
}
|
c#
| 17 | 0.556196 | 99 | 22.931034 | 29 |
starcoderdata
|
def construct2dlayout(trks, dims, rots, cam_calib, pose, cam_near_clip=0.15):
depths = []
boxs = []
points = []
corners_camera = worldtocamera(trks, pose)
for corners, dim, rot in zip(corners_camera, dims, rots):
# in camera coordinates
points3d = computeboxes(rot, dim, corners)
depths.append(corners[2])
projpoints = get_3d_bbox_vertex(cam_calib, pose, points3d, cam_near_clip)
points.append(projpoints)
if projpoints == []:
box = np.array([-1000, -1000, -1000, -1000])
boxs.append(box)
depths[-1] = -10
continue
projpoints = np.vstack(projpoints)[:, :2]
projpoints = projpoints.reshape(-1, 2)
minx = projpoints[:, 0].min()
maxx = projpoints[:, 0].max()
miny = projpoints[:, 1].min()
maxy = projpoints[:, 1].max()
box = np.array([minx, miny, maxx, maxy])
boxs.append(box)
return boxs, depths, points
|
python
| 13 | 0.567513 | 81 | 38.44 | 25 |
inline
|
//-----------------------------------------------------------------------------
// boost mpl/aux_/preprocessor/enum.hpp header file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2000-02
//
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appears in all copies and
// that both the copyright notice and this permission notice appear in
// supporting documentation. No representations are made about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
#ifndef BOOST_MPL_AUX_PREPROCESSOR_ENUM_HPP_INCLUDED
#define BOOST_MPL_AUX_PREPROCESSOR_ENUM_HPP_INCLUDED
#include "boost/mpl/aux_/config/preprocessor.hpp"
// BOOST_MPL_PP_ENUM(0,int):
// BOOST_MPL_PP_ENUM(1,int): int
// BOOST_MPL_PP_ENUM(2,int): int, int
// BOOST_MPL_PP_ENUM(n,int): int, int, .., int
#if !defined(BOOST_MPL_NO_OWN_PP_PRIMITIVES)
# include "boost/preprocessor/cat.hpp"
# define BOOST_MPL_PP_ENUM(n, param) \
BOOST_PP_CAT(BOOST_MPL_PP_ENUM_,n)(param) \
/**/
# define BOOST_MPL_PP_ENUM_0(p)
# define BOOST_MPL_PP_ENUM_1(p) p
# define BOOST_MPL_PP_ENUM_2(p) p,p
# define BOOST_MPL_PP_ENUM_3(p) p,p,p
# define BOOST_MPL_PP_ENUM_4(p) p,p,p,p
# define BOOST_MPL_PP_ENUM_5(p) p,p,p,p,p
# define BOOST_MPL_PP_ENUM_6(p) p,p,p,p,p,p
# define BOOST_MPL_PP_ENUM_7(p) p,p,p,p,p,p,p
# define BOOST_MPL_PP_ENUM_8(p) p,p,p,p,p,p,p,p
# define BOOST_MPL_PP_ENUM_9(p) p,p,p,p,p,p,p,p,p
#else
# include "boost/preprocessor/comma_if.hpp"
# include "boost/preprocessor/repeat.hpp"
# define BOOST_MPL_PP_AUX_ENUM_FUNC(unused, i, param) \
BOOST_PP_COMMA_IF(i) param \
/**/
# define BOOST_MPL_PP_ENUM(n, param) \
BOOST_PP_REPEAT_1( \
n \
, BOOST_MPL_PP_AUX_ENUM_FUNC \
, param \
) \
/**/
#endif // BOOST_MPL_NO_OWN_PP_PRIMITIVES
#endif // BOOST_MPL_AUX_PREPROCESSOR_ENUM_HPP_INCLUDED
|
c++
| 6 | 0.62135 | 79 | 32.723077 | 65 |
starcoderdata
|
def scan(index):
# comenzamos a navegar
pinfo("* Crawling...")
chk_url(index)
# ejecutamos plugins
pinfo("* Ejecutando plugins...")
for k in sorted(PLUGINS):
if CFG['plugins'][k]:
PLUGINS[k].check()
PLUGINS[k].fuzz()
|
python
| 11 | 0.638298 | 33 | 17.153846 | 13 |
inline
|
package com.vmware.identity.ssoconfig;
import java.io.File;
import java.util.Scanner;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.args4j.Option;
import com.vmware.directory.rest.client.VmdirClient;
import com.vmware.directory.rest.common.data.GroupDTO;
import com.vmware.directory.rest.common.data.GroupDetailsDTO;
import com.vmware.identity.diagnostics.DiagnosticsLoggerFactory;
import com.vmware.identity.diagnostics.IDiagnosticsLogger;
import com.vmware.identity.rest.idm.client.IdmClient;
import com.vmware.identity.rest.idm.data.BrandPolicyDTO;
import com.vmware.identity.rest.idm.data.ProviderPolicyDTO;
import com.vmware.identity.rest.idm.data.TenantConfigurationDTO;
public class TenantConfigurationCommand extends SSOConfigCommand {
private static final IDiagnosticsLogger logger = DiagnosticsLoggerFactory.getLogger(TenantConfigurationCommand.class);
@Option(name = "--default-provider", metaVar = "[Provider name]", usage = "Set default provider for the tenant.")
private String defaultProvider;
@Option(name = "--default-provider-alias", metaVar = "[Provider alias]", usage = "Set default provider alias for the tenant.")
private String defaultProviderAlias;
@Option(name = "--enable-idp-selection", metaVar = "[True | False]", usage = "Set provider selection flag for the tenant.")
private String idpSelection;
@Option(name = "--enable-logon-banner", metaVar = "[True | False]", usage = "Set logon banner flag for the tenant.")
private String logonBanner;
@Option(name = "--logon-banner-checkbox", metaVar = "[True | False]", usage = "Set logon banner checkbox flag for the tenant.")
private String logonBannerCheckbox;
@Option(name = "--logon-banner-title", metaVar = "[True | False]", usage = "Set logon banner title for the tenant.")
private String logonBannerTitle;
@Option(name = "--logon-banner-file", metaVar = "[Logon banner content file]", usage = "Logon banner content file location.")
private String logonBannerFile;
@Option(name = "--add-group", metaVar = "[Group name]", usage = "Add group to the tenant and domain.")
private String groupName;
@Option(name = "--domain", metaVar = "[Domain name]", usage = "Domain name in the tenant.")
private String domain;
@Option(name = "--group-details", metaVar = "[Group description]", usage = "Description of the group to be added. Optional.")
private String groupDetails;
@Override
public String getShortDescription() {
return String.format("Commands for tenant configurations. Use %s %s for details.", this.getCommandName(), HELP_CMD);
}
@Override
protected void execute() throws Exception {
if (isProviderPolicyUpdated()) {
setProviderPolicy();
} else if (isLogonBannerUpdated()) {
setLogonBanner();
} else if (StringUtils.isNotEmpty(groupName) && StringUtils.isNotEmpty(domain)) {
addGroup();
}
}
private void addGroup() throws Exception {
VmdirClient client = SSOConfigurationUtils.getVmdirClient();
GroupDTO group = new GroupDTO.Builder()
.withName(groupName)
.withDomain(domain)
.withDetails(new GroupDetailsDTO.Builder().withDescription(groupDetails).build())
.build();
client.group().create(tenant, group);
logger.info(String.format("Added group %s to domain %s in tenant %s.", groupName, domain, tenant));
}
private boolean isLogonBannerUpdated() {
return StringUtils.isNotEmpty(logonBanner)
|| StringUtils.isNotEmpty(logonBannerCheckbox)
|| StringUtils.isNotEmpty(logonBannerTitle)
|| StringUtils.isNotEmpty(logonBannerFile);
}
private boolean isProviderPolicyUpdated() {
return StringUtils.isNotEmpty(defaultProvider)
|| StringUtils.isNotEmpty(idpSelection)
|| StringUtils.isNotEmpty(defaultProviderAlias);
}
private void setProviderPolicy() throws Exception {
IdmClient client = SSOConfigurationUtils.getIdmClient();
ProviderPolicyDTO currentProviderPolicy = client.tenant().getConfig(tenant).getProviderPolicy();
ProviderPolicyDTO updatedProviderPolicy = new ProviderPolicyDTO.Builder()
.withDefaultProvider(SSOConfigurationUtils.checkString(defaultProvider, currentProviderPolicy.getDefaultProvider()))
.withDefaultProviderAlias(SSOConfigurationUtils.checkString(defaultProviderAlias, currentProviderPolicy.getDefaultProviderAlias()))
.withProviderSelectionEnabled(SSOConfigurationUtils.checkBoolean(idpSelection, currentProviderPolicy.isProviderSelectionEnabled()))
.build();
TenantConfigurationDTO tenantConfig = new TenantConfigurationDTO.Builder().withProviderPolicy(updatedProviderPolicy).build();
client.tenant().updateConfig(tenant, tenantConfig);
logger.info("Successfully updated provider policy for tenant " + tenant);
}
private void setLogonBanner() throws Exception {
IdmClient client = SSOConfigurationUtils.getIdmClient();
BrandPolicyDTO currentBrandPolicy = client.tenant().getConfig(tenant).getBrandPolicy();
BrandPolicyDTO.Builder builder = new BrandPolicyDTO.Builder();
boolean logonBannerDisabled = !SSOConfigurationUtils.checkBoolean(logonBanner, !currentBrandPolicy.isLogonBannerDisabled());
builder.withLogonBannerDisabled(logonBannerDisabled);
boolean logonBannerCheckboxEnabled = SSOConfigurationUtils.checkBoolean(logonBannerCheckbox, currentBrandPolicy.isLogonBannerCheckboxEnabled());
builder.withLogonBannerCheckboxEnabled(logonBannerCheckboxEnabled);
builder.withLogonBannerTitle(SSOConfigurationUtils.checkString(logonBannerTitle, currentBrandPolicy.getLogonBannerTitle()));
Scanner scanner = new Scanner(new File(logonBannerFile));
String logonBannerContent = scanner.useDelimiter("\\Z").next();
scanner.close();
builder.withLogonBannerContent(SSOConfigurationUtils.checkString(logonBannerContent, currentBrandPolicy.getLogonBannerContent()));
TenantConfigurationDTO tenantConfig = new TenantConfigurationDTO.Builder().withBrandPolicy(builder.build()).build();
client.tenant().updateConfig(tenant, tenantConfig);
logger.info("Successfully updated logon banner for tenant " + tenant);
}
}
|
java
| 16 | 0.724526 | 152 | 51.739837 | 123 |
starcoderdata
|
void rotateDr4bDownTo(float distance){//rotates double reverse fourbar down to *distance* height
SensorValue[rdr4bEnc]=0;
SensorValue[ldr4bEnc]=0;
int encVal = abs(distance*C_dr4bconstant);
while(SensorValue[ldr4bEnc]<encVal && SensorValue[rdr4bEnc]>-encVal){
motor[ldr4b] = -C_motorPower;
motor[rdr4b] = C_motorPower;
encVal = abs(distance*C_dr4bconstant);
}
motor[ldr4b] = motor[rdr4b] = 0;
}
|
c
| 10 | 0.723558 | 96 | 36 | 11 |
inline
|
import React from 'react';
import { gql } from 'react-apollo';
import { getSlotFragmentSpreads } from 'coral-framework/utils';
import PropTypes from 'prop-types';
import DraftArea from '../components/DraftArea';
import withFragments from 'coral-framework/hocs/withFragments';
const STORAGE_PATH = 'DraftArea';
/**
* An enhanced textarea to make comment drafts.
*/
class DraftAreaContainer extends React.Component {
constructor(props, context) {
super(props, context);
this.initValue();
}
async initValue() {
const input = await this.context.pymSessionStorage.getItem(this.getPath());
if (input && this.props.onInputChange) {
let parsed = '';
// Older version saved a normal string, catch those and ignore them.
try {
parsed = JSON.parse(input);
} catch (_e) {}
if (typeof parsed === 'object') {
this.props.onInputChange(parsed);
}
}
}
getPath = () => {
return `${STORAGE_PATH}_${this.props.id}`;
};
componentWillReceiveProps(nextProps) {
if (this.props.input !== nextProps.input) {
if (nextProps.input) {
this.context.pymSessionStorage.setItem(
this.getPath(),
JSON.stringify(nextProps.input)
);
} else {
this.context.pymSessionStorage.removeItem(this.getPath());
}
}
}
render() {
return (
<DraftArea
root={this.props.root}
comment={this.props.comment}
input={this.props.input}
id={this.props.id}
onInputChange={this.props.onInputChange}
disabled={this.props.disabled}
charCountEnable={this.props.charCountEnable}
maxCharCount={this.props.maxCharCount}
registerHook={this.props.registerHook}
unregisterHook={this.props.unregisterHook}
isReply={this.props.isReply}
isEdit={this.props.isEdit}
/>
);
}
}
DraftAreaContainer.contextTypes = {
// We use pymSessionStorage instead to persist the data directly on the parent page,
// in order to mitigate strict cross domain security settings.
pymSessionStorage: PropTypes.object,
};
DraftAreaContainer.propTypes = {
charCountEnable: PropTypes.bool,
maxCharCount: PropTypes.number,
id: PropTypes.string.isRequired,
input: PropTypes.object.isRequired,
onInputChange: PropTypes.func.isRequired,
disabled: PropTypes.bool,
registerHook: PropTypes.func,
unregisterHook: PropTypes.func,
isReply: PropTypes.bool,
isEdit: PropTypes.bool,
root: PropTypes.object.isRequired,
comment: PropTypes.object,
};
const slots = ['draftArea', 'commentInputArea'];
export default withFragments({
root: gql`
fragment TalkEmbedStream_DraftArea_root on RootQuery {
__typename
${getSlotFragmentSpreads(slots, 'root')}
}
`,
comment: gql`
fragment TalkEmbedStream_DraftArea_comment on Comment {
__typename
${getSlotFragmentSpreads(slots, 'comment')}
}
`,
})(DraftAreaContainer);
|
javascript
| 15 | 0.669926 | 86 | 26.719626 | 107 |
starcoderdata
|
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
delete(message) {
if (confirm('Are you sure you want to delete this message?')) {
this.sendAction('destroyMessage', message);
}
},
destroyAnswer(answer) {
this.sendAction('destroyAnswer',answer)
}
}
});
|
javascript
| 12 | 0.626471 | 69 | 21.666667 | 15 |
starcoderdata
|
import random
class Die:
def _init_(self, sides_count = 6):
self.sides_count = sides_count
def roll(self):
__roll_value = random.randint(1, self.sides_count)
return __roll_value
def get_roll_value(self):
return self.roll()
def _str_(self):
return str("The Rolled Value is {0}".
format(self.get_roll_value()))
def dice_time():
die = Die()
decision = "n"
decision = input("Do you wan to roll the dice? y/n")
while decision.lower() == "y":
die.roll()
print(die)
decision = input("Do you want to roll the dice again? y/n")
while decision.lower() == "n":
print("Thanks for playing!")
quit()
else:
print("Invalid Input. y or no")
dice_time()
|
python
| 10 | 0.547051 | 67 | 23.9375 | 32 |
starcoderdata
|
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
// defines the Users schema
const userSchema = new mongoose.Schema({
firstName: {
type: String,
required: [true, "First name is required"],
},
lastName: {
type: String,
required: [true, "Last name is required"],
},
userName: {
type: String,
required: [true, "User name is required"],
},
emailAddress: {
trim: true,
type: String,
required: [true, "Email address is required"],
unique: true,
},
password: {
type: String,
required: [true, "Password is required"],
minLength: [8, "Password must be at least 8 characters long"],
},
isMember: {
type: Boolean,
required: [true, "Is this user a member?"],
default: false,
},
isBeneficiary: {
type: Boolean,
required: [true, "Is this user a beneficiary?"],
default: false,
},
vouchers: {
type: Number,
required: [false, "Vouchers"],
},
tokens: {
type: [String],
required: [false, "Tokens"],
default: undefined,
}
},{
timestamp:true,//this will check when the user is created and updated
});
// encrypting password with bcrypt so Users password is not visible in db
userSchema.pre('save', async function(next){
if(!this.isModified('password')){
next();
}
const saltRounds = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, saltRounds);
next();
});
// decrypting for the use of checking if the passwords match upon user/admin authorisation
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password)
}
const Users = mongoose.model('Users', userSchema);
module.exports = Users
|
javascript
| 12 | 0.605723 | 90 | 26.362319 | 69 |
starcoderdata
|
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int n;
double dp[3001][3001], headProb[3001];
bool visited[3001][3001];
double solve(int index, int numberOfTails)
{
if(index > n && 2 * numberOfTails >= n)
return 0;
if(index > n)
return 1.0;
if(visited[index][numberOfTails])
return dp[index][numberOfTails];
visited[index][numberOfTails] = true;
double ans = 0;
ans += solve(index + 1, numberOfTails) * headProb[index];
ans += solve(index + 1, numberOfTails + 1) * (1 - headProb[index]);
return dp[index][numberOfTails] = ans;
}
int main()
{
IO;
cin >> n;
for(int i = 1; i <= n; i++)
cin >> headProb[i];
memset(visited, false, sizeof visited);
cout << fixed << setprecision(10) << solve(1,0);
return 0;
}
|
c++
| 10 | 0.600234 | 71 | 25.65625 | 32 |
codenet
|
import os
from MesaHandler.support import *
from MesaHandler.MesaFileHandler.MesaFileInterface import IMesaInterface
class MesaEnvironmentHandler(IMesaInterface):
def __init__(self):
IMesaInterface.__init__(self)
self.mesaDir,self.defaultsDir = self.readMesaDirs(mesa_env)
for section,file in defaultsFileDict.items():
fileContent = self.readFile(self.defaultsDir+file)
self.dataDict[section] = self.getParameters(fileContent)
def readMesaDirs(self,envVar):
try:
mesaDir = os.environ[envVar]
except KeyError:
raise EnvironmentError("MESA_DIR is not set in your enviroment. Be sure to set it properly!!")
defaultsDir = mesaDir + defaultsPath
if not os.path.exists(mesaDir):
raise FileNotFoundError("Mesa dir "+mesaDir+" does not exist. Be sure that it exists on your machine")
if not os.path.exists(defaultsDir):
raise FileNotFoundError("Defaults directory "+defaultsDir+" does not exist.")
return mesaDir,defaultsDir
def checkParameter(self,parameter,value=None):
for section,paramDict in self.dataDict.items():
if parameter in paramDict.keys():
if value is None or type(value) == type(paramDict[parameter]):
return section, paramDict[parameter]
else:
raise TypeError(
"Type of value for parameter " + parameter + " is wrong, expected type " + str(type(value)))
return "",value
|
python
| 20 | 0.643267 | 116 | 38.2 | 40 |
starcoderdata
|
bool MCP79412RTC::read(tmElements_t &tm)
{
i2cBeginTransmission(RTC_ADDR);
i2cWrite((uint8_t)TIME_REG);
if (i2cEndTransmission() != 0) {
return false;
}
else {
// request 7 bytes (secs, min, hr, dow, date, mth, yr)
i2cRequestFrom(RTC_ADDR, tmNbrFields);
tm.Second = bcd2dec(i2cRead() & ~_BV(ST));
tm.Minute = bcd2dec(i2cRead());
tm.Hour = bcd2dec(i2cRead() & ~_BV(HR1224)); // assumes 24hr clock
tm.Wday = i2cRead() & ~(_BV(OSCON) | _BV(VBAT) | _BV(VBATEN)); // mask off OSCON, VBAT, VBATEN bits
tm.Day = bcd2dec(i2cRead());
tm.Month = bcd2dec(i2cRead() & ~_BV(LP)); // mask off the leap year bit
tm.Year = y2kYearToTm(bcd2dec(i2cRead()));
return true;
}
}
|
c++
| 15 | 0.564103 | 110 | 38.05 | 20 |
inline
|
package com.old.time.activitys;
import android.view.View;
import android.widget.TextView;
import com.old.time.R;
import com.old.time.adapters.UserDressAdapter;
import com.old.time.utils.DataUtils;
import com.old.time.utils.RecyclerItemDecoration;
public class UserDressCActivity extends BaseCActivity {
private UserDressAdapter mAdapter;
@Override
protected void initView() {
super.initView();
setTitleText("地址管理");
linear_layout_more.setVisibility(View.VISIBLE);
mAdapter = new UserDressAdapter(DataUtils.getDateStrings(20));
mRecyclerView.addItemDecoration(new RecyclerItemDecoration(mContext, RecyclerItemDecoration.VERTICAL_LIST, 10));
mRecyclerView.setAdapter(mAdapter);
View view = View.inflate(this, R.layout.bottom_layout_view, null);
view.findViewById(R.id.relative_layout_creat).setBackgroundResource(R.drawable.shape_radius0_stroke_line_bgfff);
TextView tv_crest_address = view.findViewById(R.id.tv_crest_address);
tv_crest_address.setText("添加地址");
tv_crest_address.setTextColor(getResources().getColor(R.color.color_ff4444));
linear_layout_more.removeAllViews();
linear_layout_more.addView(view);
}
@Override
protected void initEvent() {
super.initEvent();
linear_layout_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CreateDressActivity.startCreateDressActivity(mContext);
}
});
}
@Override
public void getDataFromNet(boolean isRefresh) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
|
java
| 15 | 0.69911 | 120 | 32.7 | 50 |
starcoderdata
|
/* Copyright 2010.
* All rights reserved worldwide.
*
* This software is provided "as is" without express or implied
* warranties. You may freely copy and compile this source into
* applications you distribute provided that the copyright text
* below is included in the resulting source code, for example:
* "Portions Copyright 2010"
*/
#pragma once
#include "singleton.h"
#include "DXUT\DXUTmisc.h"
class Time : public Singleton
{
public:
Time( void );
~Time( void ) {}
void MarkTimeThisTick( void );
inline float GetElapsedTime( void ) { return( m_timeLastTick ); }
inline float GetCurTime( void ) { return( m_currentTime ); }
inline double GetAbsoluteTime( void ) { return( m_timer.GetAbsoluteTime() ); }
inline double GetHighestResolutionTime( void ) { LARGE_INTEGER qwTime; QueryPerformanceCounter( &qwTime ); return((double)qwTime.QuadPart); }
private:
unsigned int m_startTime;
float m_currentTime;
float m_timeLastTick;
CDXUTTimer m_timer;
};
|
c
| 8 | 0.703053 | 142 | 25.74359 | 39 |
starcoderdata
|
/**
*/
package de.dc.spring.bootstrap.blog.model;
/**
* <!-- begin-user-doc -->
* A representation of the model object ' Section
* <!-- end-user-doc -->
*
*
* @see de.dc.spring.bootstrap.blog.model.ModelPackage#getStorySection()
* @model
* @generated
*/
public interface StorySection extends Section {
} // StorySection
|
java
| 4 | 0.679134 | 137 | 27.941176 | 17 |
starcoderdata
|
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using BenchmarkDotNet.Attributes;
using System.Numerics;
namespace NodaTime.Benchmarks.NodaTimeTests
{
public class DurationBenchmarks
{
private static readonly TimeSpan SampleTimeSpan = new TimeSpan(1, 2, 3);
[Benchmark]
public Duration FromDays() =>
#if !V1
Duration.FromDays(100);
#else
Duration.FromStandardDays(100);
#endif
[Benchmark]
public Duration FromHours() => Duration.FromHours(100);
[Benchmark]
public Duration FromMinutes() => Duration.FromMinutes(100);
[Benchmark]
public Duration FromSeconds() => Duration.FromSeconds(100);
[Benchmark]
public Duration FromMilliseconds() => Duration.FromMilliseconds(100);
[Benchmark]
public Duration FromTicks() => Duration.FromTicks(100);
#if !V1
[Benchmark]
public Duration FromInt64Nanoseconds() => Duration.FromNanoseconds(int.MaxValue + 1L);
[Benchmark]
public Duration FromBigIntegerNanoseconds() => Duration.FromNanoseconds(long.MaxValue + (BigInteger)100);
#endif
[Benchmark]
public Duration FromTimeSpan() => Duration.FromTimeSpan(SampleTimeSpan);
}
}
|
c#
| 12 | 0.671459 | 113 | 27.387755 | 49 |
starcoderdata
|
const grpc = require('grpc');
class BackendCommunication {
constructor() {
};
sayHello() {
console.log("Hello 2+2 is 4!");
const demoProto = grpc.load('./protos/demo.proto').demo;
var client = new demoProto.Greeter('localhost:50051', grpc.credentials.createInsecure());
client.sayHello({
name: "Philly"
});
}
}
export default BackendCommunication;
|
javascript
| 12 | 0.630739 | 97 | 24.1 | 20 |
starcoderdata
|
@Test //Verify if user clicks cancel button, new task will not be created
public void Test4_createAndCancel() throws Exception {
//clear list
beforeClass();
int countA = RecyclerViewCount();
//add a new task
onView(withId(R.id.new_todo))
.perform(click());
//click to cancel action
onView(withId(R.id.cancel))
.check(matches(isDisplayed()))
.perform(click());
//check if number of list is not changed
int countB = RecyclerViewCount();
if (countA != countB) {
fail();
}
}
|
java
| 12 | 0.547049 | 73 | 32.052632 | 19 |
inline
|
@Test
public void checkContextMenuInterceptor()
{
System.out.println(" **** Context Menu Interceptor *** ");
try
{
// intialize the test document
xDrawDoc = DrawTools.createDrawDoc(xMSF);
SOfficeFactory SOF = SOfficeFactory.getFactory(xMSF);
XShape oShape = SOF.createShape(xDrawDoc, 5000, 5000, 1500, 1000, "GraphicObject");
DrawTools.getShapes(DrawTools.getDrawPage(xDrawDoc, 0)).add(oShape);
com.sun.star.frame.XModel xModel =
UnoRuntime.queryInterface(com.sun.star.frame.XModel.class, xDrawDoc);
// get the frame for later usage
xFrame = xModel.getCurrentController().getFrame();
// ensure that the document content is optimal visible
DesktopTools.zoomToEntirePage(xDrawDoc);
XBitmap xBitmap = null;
// adding graphic as ObjRelation for GraphicObjectShape
XPropertySet oShapeProps = UnoRuntime.queryInterface(XPropertySet.class, oShape);
System.out.println("Inserting a shape into the document");
try
{
String sFile = OfficeFileUrl.getAbsolute(new File("space-metal.jpg"));
// String sFile = util.utils.getFullTestURL("space-metal.jpg");
oShapeProps.setPropertyValue("GraphicURL", sFile);
Object oProp = oShapeProps.getPropertyValue("GraphicObjectFillBitmap");
xBitmap = (XBitmap) AnyConverter.toObject(new Type(XBitmap.class), oProp);
}
catch (com.sun.star.lang.WrappedTargetException e)
{
}
catch (com.sun.star.lang.IllegalArgumentException e)
{
}
catch (com.sun.star.beans.PropertyVetoException e)
{
}
catch (com.sun.star.beans.UnknownPropertyException e)
{
}
// reuse the frame
com.sun.star.frame.XController xController = xFrame.getController();
XContextMenuInterception xContextMenuInterception = null;
XContextMenuInterceptor xContextMenuInterceptor = null;
if (xController != null)
{
System.out.println("Creating context menu interceptor");
// add our context menu interceptor
xContextMenuInterception =
UnoRuntime.queryInterface(XContextMenuInterception.class, xController);
if (xContextMenuInterception != null)
{
ContextMenuInterceptor aContextMenuInterceptor = new ContextMenuInterceptor(xBitmap);
xContextMenuInterceptor =
UnoRuntime.queryInterface(XContextMenuInterceptor.class, aContextMenuInterceptor);
System.out.println("Register context menu interceptor");
xContextMenuInterception.registerContextMenuInterceptor(xContextMenuInterceptor);
}
}
// utils.shortWait(10000);
openContextMenu(UnoRuntime.queryInterface(XModel.class, xDrawDoc));
checkHelpEntry();
// remove our context menu interceptor
if (xContextMenuInterception != null
&& xContextMenuInterceptor != null)
{
System.out.println("Release context menu interceptor");
xContextMenuInterception.releaseContextMenuInterceptor(
xContextMenuInterceptor);
}
}
catch (com.sun.star.uno.RuntimeException ex)
{
// ex.printStackTrace();
fail("Runtime exception caught!" + ex.getMessage());
}
catch (java.lang.Exception ex)
{
// ex.printStackTrace();
fail("Java lang exception caught!" + ex.getMessage());
}
}
|
java
| 15 | 0.582048 | 110 | 38.56 | 100 |
inline
|
package shuaicj.hobby.great.free.will.protocol;
/**
* Message interface.
*
* @author shuaicj 2017/09/28
*/
public interface Message {
int length();
}
|
java
| 5 | 0.72766 | 75 | 20.363636 | 11 |
starcoderdata
|
import numpy as np
N=int(input())
la=list(map(int,input().split()))
lan=np.array(la)
count=0
while(1):
if(np.any(lan%2==1)):
lan=lan[~(lan%2==1)]
if(np.any(lan%2==0)):
lan=lan/2
count=count+len(lan)
else:
break;
print(count)
|
python
| 12 | 0.548507 | 33 | 18.214286 | 14 |
codenet
|
def get_frame_stats(self):
"""
preparing the stats before analyze
:return: stats: pd.Dataframe
"""
# add the last day stats which is not saved in the directory
current_stats = pd.DataFrame(self.frame_stats)
current_stats.set_index('period_close', drop=False, inplace=True)
# get the location of the directory
algo_folder = get_algo_folder(self.algo_namespace)
folder = join(algo_folder, 'frame_stats')
if exists(folder):
files = [f for f in listdir(folder) if isfile(join(folder, f))]
period_stats_list = []
for item in files:
filename = join(folder, item)
with open(filename, 'rb') as handle:
perf_period = pickle.load(handle)
period_stats_list.extend(perf_period)
stats = pd.DataFrame(period_stats_list)
stats.set_index('period_close', drop=False, inplace=True)
return pd.concat([stats, current_stats])
else:
return current_stats
|
python
| 14 | 0.573921 | 75 | 35.333333 | 30 |
inline
|
package com.example.denaun.aoc2021.day07;
import static com.example.denaun.aoc2021.parsers.AocParsers.COMMA;
import static com.example.denaun.aoc2021.parsers.AocParsers.LINE_ENDING;
import static com.example.denaun.aoc2021.parsers.AocParsers.NUMBER;
import com.google.common.collect.HashMultiset;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.IntFunction;
import java.util.stream.IntStream;
import org.jparsec.Parser;
class Day07 {
private Day07() {}
private static final Parser PARSER = NUMBER.sepBy(COMMA).followedBy(LINE_ENDING);
static final IntFunction SIMPLE_COST = i -> i;
static final IntFunction INCREASING_COST = i -> (i * (i + 1)) / 2;
static int part1(String input) {
var positions = PARSER.parse(input);
var destination = nearestPosition(positions, SIMPLE_COST);
return destination.getValue();
}
static int part2(String input) {
var positions = PARSER.parse(input);
var destination = nearestPosition(positions, INCREASING_COST);
return destination.getValue();
}
static final Map.Entry<Integer, Integer> nearestPosition(
List positions,
IntFunction cost) {
var counts = HashMultiset.create(positions);
var start = Collections.min(positions);
var end = Collections.max(positions);
return IntStream.range(start, end)
.mapToObj(destination -> Map.entry(
destination,
counts.entrySet().stream()
.mapToInt(entry -> entry.getCount()
* cost.apply(Math.abs(entry.getElement() - destination)))
.sum()))
.min(Comparator.comparingInt(Map.Entry::getValue))
.orElseThrow();
}
}
|
java
| 23 | 0.643539 | 100 | 37.25 | 52 |
starcoderdata
|
import liionpack as lp
import matplotlib.pyplot as plt
import numpy as np
import pybamm
import unittest
class plotsTest(unittest.TestCase):
@classmethod
def setUpClass(self):
R_bus = 1e-4
R_series = 1e-2
R_int = 5e-2
I_app = 80.0
ref_voltage = 3.2
# Load the netlist
netlist = lp.read_netlist(
"AMMBa", Ri=R_int, Rc=R_series, Rb=R_bus, Rl=R_bus, I=I_app, V=ref_voltage
)
Nspm = np.sum(netlist["desc"].str.find("V") > -1)
# Heat transfer coefficients
htc = np.ones(Nspm) * 10
# Cycling experiment
experiment = pybamm.Experiment(
[
"Charge at 50 A for 300 seconds",
"Rest for 150 seconds",
"Discharge at 50 A for 300 seconds",
"Rest for 300 seconds",
],
period="10 seconds",
)
# PyBaMM parameters
chemistry = pybamm.parameter_sets.Chen2020
parameter_values = pybamm.ParameterValues(chemistry=chemistry)
# Solve pack
output = lp.solve(
netlist=netlist,
parameter_values=parameter_values,
experiment=experiment,
output_variables=None,
htc=htc,
)
self.output = output
def test_draw_circuit(self):
net = lp.setup_circuit(Np=3, Ns=1, Rb=1e-4, Rc=1e-2, Ri=5e-2, V=3.2, I=80.0)
lp.draw_circuit(net)
plt.close("all")
def test_cell_scatter_plot(self):
X_pos = [
0.080052414,
0.057192637,
0.080052401,
0.057192662,
0.080052171,
0.057192208,
0.080052285,
0.057192264,
-0.034260006,
-0.011396764,
-0.034259762,
-0.011396799,
-0.034259656,
-0.011397055,
-0.034259716,
-0.01139668,
0.034329391,
0.01146636,
0.034329389,
0.011466487,
0.034329301,
0.011466305,
0.034329448,
0.011465906,
-0.079983086,
-0.057122698,
-0.079983176,
-0.057123076,
-0.079982958,
-0.057122401,
-0.079982995,
-0.057122961,
]
Y_pos = [
-0.046199913,
-0.033000108,
-0.019799939,
-0.0066001454,
0.0066000483,
0.019799888,
0.033000056,
0.046200369,
0.046200056,
0.033000127,
0.019800097,
0.0065999294,
-0.0065998979,
-0.019800061,
-0.032999967,
-0.046200222,
-0.04620005,
-0.032999882,
-0.019800016,
-0.0065999624,
0.0065997543,
0.019799885,
0.033000077,
0.046199929,
0.0462001,
0.033000148,
0.019800099,
0.0066000627,
-0.0065999586,
-0.019800142,
-0.032999927,
-0.046199973,
]
fig, ax = plt.subplots()
data = self.output["Terminal voltage [V]"][-1, :]
lp.cell_scatter_plot(ax, X_pos, Y_pos, c=data)
plt.close("all")
def test_plot_pack(self):
lp.plot_pack(self.output)
plt.close("all")
def test_plot_cells(self):
lp.plot_cells(self.output)
plt.close("all")
def test_plot_output(self):
lp.plot_output(self.output)
plt.close("all")
if __name__ == "__main__":
unittest.main()
|
python
| 16 | 0.475467 | 86 | 25.041667 | 144 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.