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 |
---|---|---|---|---|---|---|---|
# Copyright (c) 2020.
import logging
import maya.api.OpenMaya as om2
import maya.cmds as cmds
import pluginUtils.skinCluster as mPlugUtils_skin
import pluginUtils.plugs as mPlugUtils_plugs
logging.basicConfig()
logger = logging.getLogger(__name__)
def iterForSkinCluster(node):
"""
:param node: MObject for the source connection
:return: MObject
"""
if node.apiType() == om2.MFn.kSkinClusterFilter:
return om2.MObjectHandle(node)
iterDg = om2.MItDependencyGraph(
node, om2.MItDependencyGraph.kDownstream, om2.MItDependencyGraph.kPlugLevel
)
while not iterDg.isDone():
currentItem = iterDg.currentNode()
if currentItem.hasFn(om2.MFn.kSkinClusterFilter):
return om2.MObjectHandle(currentItem)
iterDg.next()
def findSkinCluster(mesh):
"""
Find a skinCluster attached to the kMesh or kNurbsCurve
@:param mesh: `MObjectHandle`. Not the shape! Use the transform!
:return: `MObjectHandle`
"""
if not mesh.isValid():
logger.warning("Destination mesh MObject is no longer valid!")
return
dagPath = om2.MDagPath()
geo = dagPath.getAPathTo(mesh.object())
## Does it have a valid number of shapes?
if geo.numberOfShapesDirectlyBelow() != 0:
## Fetch the shape of the geo now.
shapeMobj = geo.extendToShape().node()
mFn_shape = om2.MFnDependencyNode(shapeMobj)
apiType = shapeMobj.apiType()
if apiType == om2.MFn.kMesh:
## Look at the inMesh attr for the source
inMesh_attr = mFn_shape.attribute("inMesh")
elif apiType == om2.MFn.kNurbsCurve:
inMesh_attr = mFn_shape.attribute("create")
else:
logger.warning(
"This type of om2.MFn node is not supported! int: {}".format(apiType)
)
return
inMesh_plug = om2.MPlug(shapeMobj, inMesh_attr)
getSource = inMesh_plug.source().node()
## Now use the iterForSkinCluster() function to find the skinCluster in the connected network.
skinClusterNode_MObjH = iterForSkinCluster(getSource)
if skinClusterNode_MObjH is not None:
return skinClusterNode_MObjH
def findInfluences(skinClusterMobjH=None):
"""
returns all the valid influences from the .matrix attribute on the skinCluster node.
:param mesh: MObjectHandle for the skinCluster. Using the handles here may be playing it a little too safe. But meh.
:return: MObject
"""
if not skinClusterMobjH.isValid():
logger.warning("Skincluster is no longer valid! Did it get deleted?")
return
skClsMFnDep = om2.MFnDependencyNode(skinClusterMobjH.object())
mtxAttr = skClsMFnDep.attribute("matrix")
matrixPlug = om2.MPlug(skinClusterMobjH.object(), mtxAttr)
## Get a list of all the valid connected indices in the matrix array now.
indices = matrixPlug.getExistingArrayAttributeIndices()
influences = []
for idx in indices:
name = om2.MFnDependencyNode(
matrixPlug.elementByLogicalIndex(idx).source().node()
).absoluteName()
influences.append(str(om2.MNamespace.stripNamespaceFromName(name)))
return influences
def fetchSkinWeights(geo=None, skipZeroWeights=True):
"""
If you send in a list of geo, we'll use that. Else we assume we're working off selected.
:param geoList: MSelectionList of geo to itr
:param skipZeroWeights: if you want to avoid saving all 0.0 weight data
:return: dict
"""
weightData = {}
for x in range(geo.length()):
geoMObjH = om2.MObjectHandle(geo.getDependNode(x))
geoName = om2.MNamespace.stripNamespaceFromName(
om2.MFnDependencyNode(geoMObjH.object()).name()
)
skinClusterMObjH = findSkinCluster(geoMObjH)
if skinClusterMObjH is None:
logger.warning("Skipping {} has no skinCluster!".format(geoName))
continue
skName = str(
om2.MNamespace.stripNamespaceFromName(
om2.MFnDependencyNode(skinClusterMObjH.object()).name()
)
)
influences = findInfluences(skinClusterMObjH)
## Add the data to the dict
weightData[geoName] = {}
weightData[geoName][skName] = {}
weightData[geoName][skName]["influences"] = influences
weightData[geoName][skName]["maxInf"] = cmds.skinCluster(
skName, q=True, maximumInfluences=True
)
weightData[geoName][skName]["weights"] = {}
## Fetch the weights now
weightPlug = mPlugUtils_plugs.findPlugOnNode(skinClusterMObjH, "weightList")
matrixPlug = mPlugUtils_plugs.findPlugOnNode(skinClusterMObjH, "matrix")
if weightPlug.isNull or matrixPlug.isNull:
logger.warning(".weightList or .matrix plug not found on skinCluster!")
return
weightCount = weightPlug.getExistingArrayAttributeIndices()
for x in range(len(weightCount)):
# .weightList[x]
p = weightPlug.elementByLogicalIndex(weightCount[x])
# .weights
c = p.child(0)
## Now fetch the list of idx numbers that should relate to the inf [23, 66, 99]
w = c.getExistingArrayAttributeIndices()
## For each idx we're going to build a tuple (idx, infName, weightVal)
weightList = list()
for i in range(len(w)):
childPlug = c.elementByLogicalIndex(w[i])
weightValue = mPlugUtils_plugs.getMPlugValue(childPlug)
infName = om2.MNamespace.stripNamespaceFromName(
om2.MFnDagNode(
matrixPlug.elementByLogicalIndex(w[i]).source().node()
).name()
)
if skipZeroWeights and weightValue == 0.0:
continue
idx = w[i]
weightList.append((idx, weightValue, infName))
weightData[geoName][skName]["weights"][str(x)] = weightList
return weightData
|
python
| 24 | 0.637629 | 120 | 34.505814 | 172 |
starcoderdata
|
/*
* 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.ing.ranger.s3.client;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.ObjectListing;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
import org.apache.ranger.plugin.client.BaseClient;
import org.apache.ranger.plugin.util.PasswordUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class S3Client {
private String endpoint;
private String accessKey;
private String secretKey;
private String awsRegion;
private static final Log LOG = LogFactory.getLog(S3Client.class);
private static void logError(String errorMessage) throws Exception {
LOG.error(errorMessage);
throw new Exception(errorMessage);
}
public S3Client(Map<String, String> configs) throws Exception {
this.endpoint = configs.get("endpoint");
this.accessKey = configs.get("accesskey");
this.secretKey = PasswordUtils.decryptPassword(configs.get("password"));
this.awsRegion = RangerConfiguration.getInstance().get("airlock.s3.aws.region", "us-east-1");
if (this.endpoint == null || this.endpoint.isEmpty() || !this.endpoint.startsWith("http")) {
logError("Incorrect value found for configuration `endpoint`. Please provide url in format http://host:port");
}
if (this.accessKey == null || this.secretKey == null) {
logError("Required value not found. Please provide accessKey, secretKey");
}
}
private AmazonS3 getAWSClient() {
AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
// singer type only required util akka http allows Raw User-Agent header
// airlock changes User-Agent and causes signature mismatch
ClientConfiguration conf = new ClientConfiguration();
conf.setSignerOverride("S3SignerType");
AmazonS3ClientBuilder client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withClientConfiguration(conf)
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, awsRegion));
client.setPathStyleAccessEnabled(true);
return client.build();
}
public Map<String, Object> connectionTest() {
Map<String, Object> responseData = new HashMap<String, Object>();
List buckets = getAWSClient().listBuckets();
if (buckets.get(0).getName().isEmpty()) {
final String errMessage = "Failed, cannot retrieve Buckets list from S3";
BaseClient.generateResponseDataMap(false, errMessage, errMessage,
null, null, responseData);
} else {
final String successMessage = "Connection test successful";
BaseClient.generateResponseDataMap(true, successMessage, successMessage,
null, null, responseData);
}
return responseData;
}
private String removeLeadingSlash(final String userInput) {
String withoutLeadingSlash;
if (userInput.startsWith("/")) {
withoutLeadingSlash = userInput.substring(1);
} else {
withoutLeadingSlash = userInput;
}
return withoutLeadingSlash;
}
public List getBucketPaths(final String userInput) {
Supplier buckets = () -> getAWSClient().listBuckets().stream();
String[] userInputSplit = removeLeadingSlash(userInput).split("/");
String bucketFilter = userInputSplit[0];
String subdirFilter;
if (userInputSplit.length >= 2) {
subdirFilter = userInput.substring(removeLeadingSlash(userInput).indexOf("/") + 2);
} else {
subdirFilter = "";
}
List bucketsPaths = buckets
.get()
.filter(b -> b.getName().startsWith(bucketFilter))
.flatMap(b -> {
if (subdirFilter.length() > 0 || userInput.endsWith("/")) {
return getBucketsPseudoDirs(b.getName(), subdirFilter).stream();
} else {
return buckets.get()
.filter(sb -> sb.getName().startsWith(bucketFilter))
.map(sb -> String.format("/%s", sb.getName()));
}
})
.distinct()
.sorted()
.limit(50)
.collect(Collectors.toList());
return bucketsPaths;
}
public List getBucketsPseudoDirs(final String bucket, final String subdirFilter) {
ObjectListing bucketObjects = getAWSClient().listObjects(bucket);
List pseduDirsFiltered = bucketObjects
.getObjectSummaries()
.stream()
.filter(p -> {
if (subdirFilter.length() > 0) {
return p.getKey().startsWith(subdirFilter);
} else {
return true;
}
})
.map(p -> {
if (p.getSize() == 0) {
return String.format("/%s/%s", bucket, p.getKey());
} else {
Integer endIndex = p.getKey().contains("/") ? p.getKey().lastIndexOf("/") : 0;
if (endIndex > 0) {
return String.format("/%s/%s/", bucket, p.getKey().substring(0, endIndex));
} else {
return String.format("/%s/", bucket);
}
}
})
.collect(Collectors.toList());
return pseduDirsFiltered;
}
}
|
java
| 25 | 0.620589 | 122 | 39.666667 | 177 |
starcoderdata
|
TEST(net_fetcher_tests, test_post_message_to_url)
{
std::string url("http://durbatuluk-server.appspot.com/post");
std::stringstream ss;
ss << time(nullptr);
std::string time_str(ss.str());
// stringstream giving strange results, so use inefficient string handling
std::string message("<durbatuluk>joelwashere");
message += time_str;
message += "/+=</durbatuluk>";
// post
ASSERT_TRUE(NetFetcher::PostMessageToURL(url, message));
// check log that post went through
std::string contents;
ASSERT_TRUE(NetFetcher::FetchURL("http://durbatuluk-server.appspot.com/fetch",
&contents));
EXPECT_TRUE(contents.find(time_str) != contents.npos)
<< "This can possibly fail if the server is too slow...";
}
|
c++
| 10 | 0.698087 | 80 | 30.869565 | 23 |
inline
|
#pragma once
#define I2C_ADDRESS 0x20
#define I2C_WRITE_BIT 0x00
#define I2C_READ_BIT 0x01
#define REG_DATA 0x00
#define REG_DIR 0x01
#define REG_PULLUP 0x02
#define REG_PULLDOWN 0x03
// reserved
#define REG_INTR_MASK 0x05
#define REG_SENSE_HIGH 0x06
#define REG_SENSE_LOW 0x07
#define REG_INTR_SRC 0x08
#define REG_EVENT_STAT 0x09
#define REG_PLD_MODE 0x10
#define REG_PLD_TABLE0 0x11
#define REG_PLD_TABLE1 0x12
#define REG_PLD_TABLE2 0x13
#define REG_PLD_TABLE3 0x14
#define REG_PLD_TABLE4 0x15
#define REG_ADVANCED 0xAB
|
c
| 8 | 0.729042 | 90 | 26.875 | 24 |
starcoderdata
|
export default [
{
id: 1048,
name: '
price: 5.0,
stripe_price: 'price_1Gzi24CzjdOYYybLCABpt0VD',
category: 'pencil',
image: 'https://cdn.shopify.com/s/files/1/1338/0845/collections/lippie-pencil_grande.jpg?v=1512588769'
},
{
id: 1047,
name: '
price: 5.5,
stripe_price: 'price_1GzkutCzjdOYYybLyK7lfMuu',
category: 'lipstick',
image: 'https://cdn.shopify.com/s/files/1/1338/0845/products/brain-freeze_a_800x1200.jpg?v=1502255076'
},
{
id: 1046,
name: '
price: 5.5,
stripe_price: 'price_1Gzkw5CzjdOYYybLf2kVGs7a',
category: 'lipstick',
image: 'https://cdn.shopify.com/s/files/1/1338/0845/collections/blottedlip-lippie-stix_grande.jpg?v=1512588803'
},
];
|
javascript
| 6 | 0.648221 | 115 | 28.192308 | 26 |
starcoderdata
|
using BlazorComponent;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Masa.Blazor
{
public class MECharts : BECharts, IDisposable
{
[Parameter]
public StringNumber Width { get; set; } = 600;
[Parameter]
public StringNumber Height { get; set; } = 400;
[Parameter]
public StringNumber MinWidth { get; set; }
[Parameter]
public StringNumber MinHeight { get; set; }
[Parameter]
public StringNumber MaxWidth { get; set; }
[Parameter]
public StringNumber MaxHeight { get; set; }
[Parameter]
public object Option { get; set; } = new { };
protected override void SetComponentClass()
{
CssProvider
.Apply(styleAction: styleBuilder =>
{
styleBuilder
.AddWidth(Width)
.AddHeight(Height)
.AddMinWidth(MinWidth)
.AddMinHeight(MinHeight)
.AddMaxHeight(MaxHeight)
.AddMaxWidth(MaxWidth);
});
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (IsDisposed)
{
return;
}
var echarts = await Js.InvokeAsync "./_content/Masa.Blazor/js/echarts-helper.js");
await echarts.InvokeVoidAsync("init", Ref, Option);
}
}
}
|
c#
| 27 | 0.560726 | 124 | 27.419355 | 62 |
starcoderdata
|
DPT_RTN_T dptHBA_C::calibrateBattery(dptBuffer_S *toEng_P)
{
DPT_RTN_T retVal = MSG_RTN_IGNORED;
if (isBatteryUnit()) {
uCHAR calibrationType = 0;
// Get the calibration type (initial calibration == 0, maintenance calibration == 1)
if (!toEng_P->extract(calibrationType))
retVal = MSG_RTN_DATA_UNDERFLOW;
else
retVal = sendMFC(MFC_CALIBRATE_BATTERY, calibrationType);
}
return (retVal);
}
|
c++
| 11 | 0.703163 | 86 | 21.888889 | 18 |
inline
|
//File Requirements
const mongoose = require('mongoose');
const Review = require('./review');
const Schema = mongoose.Schema;
//Local variables
const sensiblePeriods = ['Movimento', 'Linguagem', 'Detalhes', 'Ordem', 'Desenvolvimento dos Sentidos', 'Refinamento dos Sentidos', 'Graça e Cortesia', 'Música e Ritmo', 'Escrita', 'Leitura', 'Matemática']
//Activity Schema
const ActivitySchema = new Schema({
title: {
type: String,
required: true
},
ages: {
type: String,
required: true
},
sensiblePeriod: {
type: String,
//enum limits the options to those inside the array
enum: sensiblePeriods,
required: true
},
category: {
type: String,
},
theme: {
type: String,
},
description: {
type: String,
required: true,
trim: true
},
owned: {
type: String,
required: true,
default: 'Não'
},
picture: {
url: {
type: String,
default: 'public/img/fatherhood.svg'
},
fileName: {
type: String
}
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
date: {
type: Date,
default: Date.now()
//required: true
},
reviews: [
{
type: Schema.Types.ObjectId,
ref: 'Review'
}
]
})
ActivitySchema.post('findOneAndDelete', async function (doc) {
if (doc) {
await Review.deleteMany({
_id: {
$in: doc.reviews
}
})
}
})
//"Compile" Schema
const Activity = mongoose.model('Activity', ActivitySchema);
//Export module to be used elsewhere
module.exports = Activity;
|
javascript
| 17 | 0.563779 | 205 | 19.280488 | 82 |
starcoderdata
|
#!/usr/bin/python
#bridge between lldb and python for non-trivial scripting
#this python script can be loaded in lldb by invoking 'lldb -s'
# and passing a text file with the following command
# command script import /path/to/this/file
import lldb
#define a custom lldb command.
def find_aslr(debugger, command, result, internal_dict):
print >> result, "Hello, World!"
#anything here will execute as soon as this python module is imported
def __lldb_init_module(debugger, internal_dict):
#passes this command to lldb without return object
debugger.HandleCommand("command script add -f find_aslr_offset.find_aslr find_aslr")
print "The 'find_aslr command has been installed."
#set up command interpreter so that we can get results of commands
ci = debugger.GetCommandInterpreter()
#set up a return object to handle resuls of commands
ro = lldb.SBCommandReturnObject()
#figure out the name of the module we want to dump to find aslr offset
ci.HandleCommand("image list", ro)
image_list_lines = ro.GetOutput().strip().split("\n")
target_line = image_list_lines[0]
target_module = target_line.strip().split(" ")[-2]
print target_module
#find the relevant fields in the module's section dump
# to calculate the aslr offset
ci.HandleCommand("image dump sections "+target_module, ro)
section_dump_lines = ro.GetOutput().strip().split("\n")
for line in section_dump_lines:
print line
zero_page_line = section_dump_lines[3]
zero_end_address = zero_page_line.split("-")[1].split(")")[0]
print "zero: "+zero_end_address
text_section_line = section_dump_lines[4]
text_start_address = text_section_line.split("[")[1].split("-")[0]
print "text: "+text_start_address
aslr_shift = int(text_start_address,0) - int(zero_end_address,0)
print "aslr: "+str(hex(aslr_shift))
#TODO Set up a breakpoint using the aslr shift and some constant value.
#Set a condition on the breakpoint such that a record is logged to a file.
#Continue with execution automatically after logging the event.
|
python
| 12 | 0.731048 | 86 | 39.607843 | 51 |
starcoderdata
|
package com.demo.client;
import com.demo.pojo.User;
import org.springframework.stereotype.Component;
@Component
public class UserClientFallback implements UserClient {
@Override
public User findUserByUserName(String userName) {
User user = new User();
user.setName( "服务器繁忙,请稍后再试!" );
return user;
}
}
|
java
| 10 | 0.697778 | 88 | 21.736842 | 19 |
starcoderdata
|
<?php
Route::get('/', function () {
return view('principal');
});
Route::get('/ejemplo', function () {
return view('proyectos/ejemplo');
});
///EJEMPLOS
Route::post('/hola-mundo', function () {
return "Hola soy
});
Route::match(['get','post'],'contacto', function(){
return view("contacto"); // crear archivo blade....
});
Route::get('contacto/{nombre?}/{edad?}',function($nombre ='adrian',$edad = 25){
return view('/cursolaravel/contacto')
->with('nombre' , $nombre)
->with('edad' , $edad)
->with('fruta', array(
'pera','manzana','kwi'
));
})->where([
'nombre' => '[A-Za-z]+',
'edad' => '[0-9]+'
]);
use App\Video;
//APLICACION YOUTUBE
//Route::get('/youtube','youtubeController@index');
Route::get('/youtube',function(){
$videos = Video::all();
foreach($videos as $video){
echo "Este es el video: ".$video->title."
}
die();
return $videos;
});
///////////////////////
//IMPRESION
///////////////////////
Route::get('/impresion',"Impresion@index");
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/VueEx',"vueExController@index");
Route::get('/form', function () {
return view('cursoVue.form');
});
|
php
| 16 | 0.542835 | 79 | 20.274194 | 62 |
starcoderdata
|
# -*- encoding:utf-8 -*-
import json
import os
import datetime
import time
import sys
import analyze
import search
reload(sys)
sys.setdefaultencoding('utf8')
"""
主要思路:
1. 答题时使用adb截图并将图片pull到本机
2. 通过ocr图片识别题目
3. 百度题目
4. 百度后结果与选项做匹配,匹配度最高的即为推荐答案
注: 部分题目由于识别或题目本身无法问题,可能搜索不到答案或推荐有误差,需自己根据题目情况进行抉择
"""
# 检查adb是否安装
def check_os():
size_str = os.popen('adb shell wm size').read()
if not size_str:
print('请安装ADB调试工具')
sys.exit()
# 获取配置文件
def get_config():
config_file = 'config.json'
if os.path.exists(config_file):
with open(config_file, 'r') as f:
return json.load(f)
else:
print('请检查根目录下是否存在配置文件 config.json')
exit(-1)
def main():
pro_start = datetime.datetime.now()
check_os()
config = get_config()
is_auto = config['auto']
while True:
while True:
img = analyze.tell_and_get_image()
if img is not None:
break
if is_auto:
print('没有发现题目页面')
exit(-1)
time.sleep(1) # 不是题目页面,休眠1秒后继续判断
# 获取题目及选项
start = datetime.datetime.now() # 开始时间
question,option_arr = analyze.image_to_str(img) # 图片转文字
question, is_negative = analyze.get_question(question) # 得到题目、选项及题目正反
result_list = search.search(question) # 搜索结果
print question
best_result = analyze.get_result(result_list, option_arr, question, is_negative) # 分析结果
if best_result is None:
print('\n没有答案')
else:
print('最佳答案是: \033[1;31m{}\033[0m'.format(best_result))
run_time = (datetime.datetime.now() - start).seconds
print('本次运行时间为:{}秒'.format(run_time))
if is_auto:
time.sleep(10) # 每一道题结束,休息10秒
else:
break
total_time = (datetime.datetime.now() - pro_start).seconds
print('脚本运行共运行{}秒'.format(total_time))
if __name__ == '__main__':
main()
|
python
| 15 | 0.5838 | 96 | 23.5375 | 80 |
starcoderdata
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
use HasFactory;
// la realiza un usuario
public function user()
{
return $this->belongsTo(User::class);
}
// tiene un estado
public function state()
{
return $this->belong(State::class);
}
// tiene un producto
public function product()
{
return $this->hasOne(Product::class);
}
// tiene una review
public function review()
{
return $this->hasOne(Review::class);
}
// recibe varios reportes
public function accusations()
{
return $this->morphMany(Report::class, 'reportable');
}
}
|
php
| 10 | 0.618135 | 61 | 16.795455 | 44 |
starcoderdata
|
from pyvirtualdisplay import Display
from selenium import webdriver
import pandas as pd
import datetime
display = Display(visible=0, size=(800, 600))
display.start()
url_1 = "https://www.melon.com/chart/day/index.htm"
url_2 = "https://www.melon.com/chart/day/index.htm#params%5Bidx%5D=51"
def melon_daily_100():
melon_day = pd.DataFrame(columns = ["Ranking", "Song", "Artist", "Album"])
driver = webdriver.Chrome()
driver.get(url_1)
table_50 = driver.find_elements_by_css_selector("#tb_list tbody #lst50")
for table in table_50:
rank = table.find_element_by_css_selector(".rank").text
song = table.find_element_by_css_selector(".wrap_song_info .ellipsis.rank01 a").text
artist = table.find_element_by_css_selector(".wrap_song_info .ellipsis.rank02 a").text
album = table.find_element_by_css_selector(".wrap_song_info .ellipsis.rank03 a").text
data = {"Ranking" : rank,
"Song" : song,
"Artist" : artist,
"Album" : album, }
melon_day.loc[len(melon_day)] = data
driver.get(url_2)
table_100 = driver.find_elements_by_css_selector("#tb_list tbody .lst100")
for table in table_100:
rank = table.find_element_by_css_selector(".rank").text
song = table.find_element_by_css_selector(".wrap_song_info .ellipsis.rank01 a").text
artist = table.find_element_by_css_selector(".wrap_song_info .ellipsis.rank02 a").text
album = table.find_element_by_css_selector(".wrap_song_info .ellipsis.rank03 a").text
data = {"Ranking" : rank,
"Song" : song,
"Artist" : artist,
"Album" : album, }
melon_day.loc[len(melon_day)] = data
melon_day = melon_day.set_index('Ranking')
now = datetime.datetime.now()
current_time = now.strftime("%Y-%m-%d")
melon_day.to_csv('melon_daily_100_(' + str(current_time) + ').csv', encoding='utf-8' )
driver.close()
melon_daily_100()
|
python
| 11 | 0.602317 | 94 | 29.925373 | 67 |
starcoderdata
|
package server
import (
"context"
"elasticgpu.io/elastic-gpu-scheduler/pkg/scheduler"
v1 "k8s.io/api/core/v1"
log "k8s.io/klog/v2"
extender "k8s.io/kube-scheduler/extender/v1"
)
type Prioritize struct {
Name string
Func func(pod *v1.Pod, nodeNames []string) (*extender.HostPriorityList, error)
Config scheduler.ElasticSchedulerConfig
}
func (p Prioritize) Handler(args extender.ExtenderArgs) (*extender.HostPriorityList, error) {
pod := args.Pod
nodeNames := *args.NodeNames
return p.Func(pod, nodeNames)
}
func NewElasticGPUPrioritize(ctx context.Context, config scheduler.ElasticSchedulerConfig) *Prioritize {
return &Prioritize{
Name: "ElasticGPUPrioritize",
Func: func(pod *v1.Pod, nodeNames []string) (*extender.HostPriorityList, error) {
priorityList := make(extender.HostPriorityList, len(nodeNames))
sch, err := scheduler.GetResourceScheduler(pod, config.RegisteredSchedulers)
if err != nil {
return nil, err
}
scores := sch.Score(nodeNames, pod)
for i, score := range scores {
priorityList[i] = extender.HostPriority{
Host: nodeNames[i],
Score: int64(score),
}
}
log.Infof("node scores: %v", priorityList)
return &priorityList, nil
},
Config: config,
}
}
|
go
| 22 | 0.718872 | 104 | 26.76087 | 46 |
starcoderdata
|
<?php
namespace TarfinLabs\Parasut\Models;
class Contact extends BaseModel
{
public $fillable = [
'created_at',
'updated_at',
'contact_type',
'name',
'email',
'short_name',
'balance',
'trl_balance',
'usd_balance',
'eur_balance',
'gbp_balance',
'tax_number',
'tax_office',
'archived',
'account_type',
'city',
'district',
'address',
'phone',
'fax',
'is_abroad',
'term_days',
//'invoicing_preference,
'sharings_count',
//'iban,
'exchange_rate_type',
'iban',
'sharing_preview_url',
'sharing_preview_path',
'payment_reminder_preview_url',
];
protected $schema = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'contact_type' => 'string',
'name' => 'string',
'email' => 'string',
'short_name' => 'string',
'balance' => 'float',
'trl_balance' => 'float',
'usd_balance' => 'float',
'eur_balance' => 'float',
'gbp_balance' => 'float',
'tax_number' => 'string',
'tax_office' => 'string',
'archived' => 'boolean',
'account_type' => 'string',
'city' => 'string',
'district' => 'string',
'address' => 'string',
'phone' => 'string',
'fax' => 'string',
'is_abroad' => 'boolean',
'term_days' => 'integer',
//'invoicing_preferences' => 'array',
'sharings_count' => 'integer',
//'ibans' => 'array',
'exchange_rate_type' => 'string',
'iban' => 'string',
'sharing_preview_url' => 'string',
'sharing_preview_path' => 'string',
'payment_reminder_preview_url' => 'string',
];
}
|
php
| 9 | 0.472596 | 69 | 25.493151 | 73 |
starcoderdata
|
package br.com.zupacademy.jpcsik.proposta.proposta;
import java.net.URI;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.UriComponentsBuilder;
import br.com.zupacademy.jpcsik.proposta.proposta.analise.ApiAnaliseSolicitacao;
import br.com.zupacademy.jpcsik.proposta.proposta.analise.ResultadoAnaliseDto;
import br.com.zupacademy.jpcsik.proposta.proposta.analise.SolicitacaoAnaliseDto;
import br.com.zupacademy.jpcsik.proposta.validacao.DocumentoValidator;
import feign.FeignException;
import feign.FeignException.FeignClientException;
@RestController
public class NovaPropostaController {
@Autowired
private PropostaRepository propostaRepository;
@Autowired
private ApiAnaliseSolicitacao apiAnaliseSolicitacao;
@Value("${encryptor.password}")
private String password;
@Value("${encryptor.salt}")
private String salt;
//Valida se o documento que vêm na requisição já existe
@Autowired
private DocumentoValidator documentoValidator;
@InitBinder
public void init(WebDataBinder binder) {
binder.addValidators(documentoValidator);
}
@PostMapping("/proposta/cadastrar")
@Transactional
public ResponseEntity cadastrar(@RequestBody @Valid NovaPropostaRequest novaProposta, UriComponentsBuilder uriBuilder) {
//Classe responsável por criptografar o documento
TextEncryptor encryptor = Encryptors.text(password, salt);
Proposta proposta = novaProposta.toProposta(encryptor);
//Salva a proposta no banco gerando um Id
propostaRepository.save(proposta);
//Trata as possíveis exceções que o serviço de analise pode jogar
try {
ResultadoAnaliseDto propostaAnalisada = apiAnaliseSolicitacao.analise(new SolicitacaoAnaliseDto(proposta, encryptor));
proposta.definirStatus(propostaAnalisada.getResultadoSolicitacao().normaliza());
} catch (FeignClientException e) {
if(e.status() == 422) {
proposta.definirStatus(StatusProposta.NAO_ELEGIVEL);
}
} catch(FeignException e) {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Serviço indisponivel!");
}
//Atualiza a proposta com o novo status
propostaRepository.save(proposta);
//Cria a url da nova proposta
URI uri = uriBuilder.path("/proposta/{id}").buildAndExpand(proposta.getId()).toUri();
return ResponseEntity.created(uri).build();
}
}
|
java
| 14 | 0.810188 | 124 | 34.837209 | 86 |
starcoderdata
|
/* eslint-disable camelcase */
const knex = require('../../config/db');
const Error = require('../lib/utils/http-error');
// get all notifications
// get unread notifications
const getNotifications = async (req) => {
try {
const { has_been_read, sort } = req.query;
let notifications = knex('notifications')
.select(
'notifications.id AS id',
'notifications.fk_user_id AS userId',
'message',
`has_been_read AS isUnread`,
'notifications.created_at AS createdAt',
)
.innerJoin('users', 'users.id', '=', 'notifications.fk_user_id');
if (has_been_read === 'false') {
notifications = notifications.where('has_been_read', '=', false);
}
if (sort) {
notifications = notifications.orderBy('notifications.created_at', sort);
}
if (notifications.length === 0) {
throw new Error(`incorrect entry notifications`, 404);
}
return await notifications
.groupBy('notifications.id')
.orderBy('notifications.created_at', 'desc');
} catch (error) {
return error.message;
}
};
const getNotificationsById = async (id) => {
try {
const notificationById = await knex('notifications')
.select(
'notifications.id AS id',
'notifications.fk_user_id AS userId',
'message',
'has_been_read AS isUnread',
'notifications.created_at AS createdAt',
)
.innerJoin('users', 'users.id', '=', 'notifications.fk_user_id')
.where('notifications.id', '=', id);
if (notificationById.length === 0) {
throw new Error(
`incorrect entry notifications with the id of ${id}`,
404,
);
}
return notificationById[0];
} catch (error) {
return error.message;
}
};
const createNotification = async (body) => {
const newNotification = {
title: body.title,
};
// will return the total number of notifications after inserting a new notification
const insertedNotifications = await knex('notifications').insert(
newNotification,
);
return {
successful: true,
// id for the newly created notification will be same as total number of notifications inserted
id: insertedNotifications[0],
};
};
// users delete by id
const deleteNotification = async (notificationId) => {
return knex('notifications')
.where({ id: notificationId })
.del();
};
module.exports = {
createNotification,
deleteNotification,
getNotifications,
getNotificationsById,
};
|
javascript
| 19 | 0.632318 | 100 | 27.022472 | 89 |
starcoderdata
|
void tee_mmu_final(struct user_ta_ctx *utc)
{
uint32_t asid = 1 << ((utc->context - 1) & 0xff);
/* return ASID */
g_asid |= asid;
/* clear MMU entries to avoid clash when asid is reused */
tlbi_asid(utc->context & 0xff);
utc->context = 0;
free(utc->mmu);
utc->mmu = NULL;
}
|
c
| 11 | 0.616197 | 59 | 19.357143 | 14 |
inline
|
#include "Graphics.hpp"
#include "Device.hpp"
#include "SDL.h"
#include
#include "GL/gl.h"
//----------------------------------------------------------------------------//
// Graphics
//----------------------------------------------------------------------------//
//----------------------------------------------------------------------------//
Graphics::Graphics(void)
{
}
//----------------------------------------------------------------------------//
Graphics::~Graphics(void)
{
}
//----------------------------------------------------------------------------//
bool Graphics::OnEvent(int _type, void* _data)
{
switch (_type)
{
case SystemEvent::PreloadEngineSettings:
_PreloadEngineSettings(*reinterpret_cast
break;
case SystemEvent::SaveEngineSettings:
_SaveEngineSettings(*reinterpret_cast
break;
case SystemEvent::LoadUserSettings:
_LoadUserSettings(*reinterpret_cast
break;
case SystemEvent::SaveUserSettings:
_SaveUserSettings(*reinterpret_cast
break;
case SystemEvent::Startup:
if (!_Startup())
{
*reinterpret_cast = false;
return true;
}
break;
case SystemEvent::Shutdown:
_Shutdown();
break;
case SystemEvent::BeginFrame:
_BeginFrame();
break;
case SystemEvent::EndFrame:
_EndFrame();
break;
}
return false;
}
//----------------------------------------------------------------------------//
void Graphics::_PreloadEngineSettings(Json& _cfg)
{
m_settings = _cfg.Get("Graphics");
}
//----------------------------------------------------------------------------//
void Graphics::_SaveEngineSettings(Json& _cfg)
{
//
m_settings["CoreProfile"] = true;
m_settings["ForwardCompatible"] = false;
m_settings["DebugContext"] = false;
_cfg["Graphics"] = m_settings;
}
//----------------------------------------------------------------------------//
void Graphics::_LoadUserSettings(Json& _cfg)
{
const Json& _src = _cfg.Get("Graphics");
m_vsync = _src["VSync"];
}
//----------------------------------------------------------------------------//
void Graphics::_SaveUserSettings(Json& _cfg)
{
Json& _dst = _cfg["Graphics"];
_dst["VSync"] = m_vsync;
}
//----------------------------------------------------------------------------//
bool Graphics::_Startup(void)
{
LOG("Graphics::Startup");
int _ctx_flags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG | SDL_GL_CONTEXT_DEBUG_FLAG;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, _ctx_flags);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
m_context = SDL_GL_CreateContext(gDevice->WindowHandle());
if (!m_context)
{
LOG("Unable to create of OpenGL context: %s", SDL_GetError());
return false;
}
LOG("%s on %s, %s", glGetString(GL_VERSION), glGetString(GL_RENDERER), glGetString(GL_VENDOR)); // temp
return true;
}
//----------------------------------------------------------------------------//
void Graphics::_Shutdown(void)
{
LOG("Graphics::Shutdown");
if (m_context)
{
SDL_GL_DeleteContext(m_context);
m_context = nullptr;
}
}
//----------------------------------------------------------------------------//
void Graphics::_BeginFrame(void)
{
//_ResetState
}
//----------------------------------------------------------------------------//
void Graphics::_EndFrame(void)
{
SDL_GL_SetSwapInterval(m_vsync ? 1 : 0);
SDL_GL_SwapWindow(gDevice->WindowHandle());
}
//----------------------------------------------------------------------------//
//----------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------//
|
c++
| 16 | 0.438672 | 104 | 25.795775 | 142 |
starcoderdata
|
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace OnlineLMS
{
public partial class membermanagementpage
{
///
/// MembersID control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MembersID;
///
/// BtnMemberGO control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.LinkButton BtnMemberGO;
///
/// MembersName control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MembersName;
///
/// MemberStatus control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberStatus;
///
/// BtnActive control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.LinkButton BtnActive;
///
/// BtnPending control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.LinkButton BtnPending;
///
/// BtnInActive control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.LinkButton BtnInActive;
///
/// MemberDateBirth control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberDateBirth;
///
/// MemberPhoneNumber control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberPhoneNumber;
///
/// MemberEmail control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberEmail;
///
/// MemberState control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberState;
///
/// MemberCity control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberCity;
///
/// MemberZipCode control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberZipCode;
///
/// MemberPostAddress control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.TextBox MemberPostAddress;
///
/// BtnDeleteMemberPermanent control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.Button BtnDeleteMemberPermanent;
///
/// SqlDataSourceMemberManagement control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.SqlDataSource SqlDataSourceMemberManagement;
///
/// GridMemberManagement control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.GridView GridMemberManagement;
}
}
|
c#
| 11 | 0.551629 | 96 | 34.081871 | 171 |
starcoderdata
|
import DayList from "../src/component/DayList";
import DayFull from "../src/component/DayFull";
export default function Class_map() {
return (
<>
<DayList />
<DayFull />
);
}
|
javascript
| 8 | 0.621005 | 47 | 15.923077 | 13 |
starcoderdata
|
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace Uno.UI.Xaml
{
[Flags]
public enum RoutedEventFlag : ulong
{
None = 0,
// Pointers
PointerPressed = 1 << 0,
PointerReleased = 1 << 1,
PointerEntered = 1 << 2,
PointerExited = 1 << 3,
PointerMoved = 1 << 4,
PointerCanceled = 1 << 5,
PointerCaptureLost = 1 << 6,
// Gestures
Tapped = 1 << 7,
DoubleTapped = 1 << 8,
// Key
KeyDown = 1 << 9,
KeyUp = 1 << 10,
// Focus
GotFocus = 1 << 11,
LostFocus = 1 << 12,
}
internal static class RoutedEventFlagExtensions
{
private const RoutedEventFlag _isPointer = // 0b0000_0000_0111_1111
RoutedEventFlag.PointerPressed
| RoutedEventFlag.PointerReleased
| RoutedEventFlag.PointerEntered
| RoutedEventFlag.PointerExited
| RoutedEventFlag.PointerMoved
| RoutedEventFlag.PointerCanceled
| RoutedEventFlag.PointerCaptureLost;
private const RoutedEventFlag _isGesture = // 0b0000_0001_1000_0000
RoutedEventFlag.Tapped
| RoutedEventFlag.DoubleTapped;
private const RoutedEventFlag _isKey = // 0b0000_0110_0000_0000
RoutedEventFlag.KeyDown
| RoutedEventFlag.KeyUp;
private const RoutedEventFlag _isFocus = // 0b0001_1000_0000_0000
RoutedEventFlag.GotFocus
| RoutedEventFlag.LostFocus;
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPointerEvent(this RoutedEventFlag flag) => (flag & _isPointer) != 0;
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsGestureEvent(this RoutedEventFlag flag) => (flag & _isGesture) != 0;
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsKeyEvent(this RoutedEventFlag flag) => (flag & _isKey) != 0;
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFocusEvent(this RoutedEventFlag flag) => (flag & _isFocus) != 0;
}
}
|
c#
| 16 | 0.716356 | 91 | 25.465753 | 73 |
starcoderdata
|
/**
* 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.ls.infrastructure.core.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.ls.infrastructure.core.exception.PlatformApiDataValidationException;
import org.springframework.stereotype.Component;
@Component
public class PaginationParametersDataValidator {
public static Set sortOrderValues = new HashSet<>(Arrays.asList("ASC", "DESC"));
public void validateParameterValues(PaginationParameters parameters, final Set supportedOrdeByValues, final String resourceName) {
final List dataValidationErrors = new ArrayList<>();
if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())) {
final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy()
+ "' is not supported. The supported orderBy values are " + supportedOrdeByValues.toString();
final ApiParameterError error = ApiParameterError.parameterError("validation.msg." + resourceName
+ ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy", parameters.getOrderBy(),
supportedOrdeByValues.toString());
dataValidationErrors.add(error);
}
if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) {
final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder()
+ "' is not supported. The supported sortOrder values are " + sortOrderValues.toString();
final ApiParameterError error = ApiParameterError.parameterError("validation.msg." + resourceName
+ ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder", parameters.getSortOrder(),
sortOrderValues.toString());
dataValidationErrors.add(error);
}
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) {
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
}
|
java
| 14 | 0.727273 | 142 | 48.253968 | 63 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Identity;
namespace SimpleSocial.Data.Models
{
// Add profile data for application users by adding properties to the SimpleSocialUser class
public class SimpleSocialUser : IdentityUser
{
public SimpleSocialUser()
{
Posts = new HashSet
Comments = new HashSet
UserPages = new HashSet
Likes = new HashSet
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string ProfilePictureURL { get; set; }
public DateTime? BirthDay { get; set; }
public Gender? Gender { get; set; }
public string Description { get; set; }
public string City { get; set; }
public string Country { get; set; }
public DateTime CreatedOn { get; set; } = DateTime.UtcNow;
public ICollection Posts { get; set; }
public ICollection Comments { get; set; }
public ICollection UserPages { get; set; }
public ICollection Likes { get; set; }
}
}
|
c#
| 12 | 0.621815 | 96 | 26.911111 | 45 |
starcoderdata
|
var router = require('express').Router();
var Settings = require('../../models/Settings');
var utils = require('../../utils');
router.post('/pos', function (req, res) {
var validator = {
requestType: /^(save|remove)$/,
name: /^.{3,100}$/,
tin: /^\d{8}$/,
vat: /^[A-Z]{2}\d{8,10}$/,
street: /^.{5,100}$/,
city: /^.{2,75}$/,
zip: /^\w{3,10}$/,
country: /^.{3,75}$/,
phone: /^\+?(\d{3})?\d{9}$/,
currency: /^\{"code":"(CZK)","symbol":"(Kč)"\}$/
};
if (!utils.isValidRequest(validator, req.body)) {
res.json({success: false, msg: 'Invalid request. Request format is not accepted'});
} else {
var query = {userId: req.user._id};
Settings.findOne(query).exec().then(function (settings) {
//console.log(settings);
settings.name = req.body.name;
settings.tin = req.body.tin;
settings.vat = req.body.vat;
settings.address.street = req.body.street ;
settings.address.city = req.body.city ;
settings.address.zip = req.body.zip ;
settings.address.country = req.body.country;
settings.phone = req.body.phone;
settings.currency = JSON.parse(req.body.currency);
return settings.save();
}).then(function (settings) {
var ret = {
name: settings.name,
tin: settings.tin,
vat: settings.vat,
address: settings.address,
phone: settings.phone,
currency: settings.currency,
tax_rates: settings.tax_rates,
receipt: settings.receipt,
staff: settings.staff,
customer_display: settings.customer_display
};
res.json({success: true, msg: ret});
}).catch(function (err) {
res.json({success: false, msg: err});
});
}
});
module.exports = router;
|
javascript
| 18 | 0.467931 | 91 | 36.859649 | 57 |
starcoderdata
|
document.addEventListener('DOMContentLoaded', function () {
const selectCollection = document.querySelector('.visualisation-3d.bottom .select-collection');
const selectColor = document.querySelector('.visualisation-3d.bottom .select-color');
const selectProduct = document.querySelector('.visualisation-3d.bottom .select-product');
const img3d = document.querySelector('.visualisation-3d .wrapper-3d img');
const prodLink = document.querySelector('.visualisation-3d .to-product');
function run(newCard) {
if (!newCard) return true;
setActiveCard(newCard);
window.resetSelectColor();
setSelectColor(newCard);
window.resetSelectCollection();
window.resetSelectProduct();
}
function setActiveCard(newCard) {
const oldCard = newCard.closest('.cards').querySelector('.card.active');
if (oldCard) oldCard.classList.remove('active');
newCard.classList.add('active');
img3d.src = newCard.dataset.srcLarge;
prodLink.href = newCard.dataset.productLink;
}
function setSelectColor(newCard) {
const interiorType = newCard.dataset.interiorType;
selectColor.querySelector(`.colors[data-interior-type="${interiorType}"]`).classList.remove('hidden');
}
window.resetSelectColor = function () {
selectColor.querySelector('.select-placeholder').classList.remove('hidden');
selectColor.querySelector('.select-title').classList.add('hidden');
const activeColor = selectColor.querySelector('.color.active');
if (activeColor) activeColor.classList.remove('active');
const activeColors = selectColor.querySelector('.colors:not(.hidden)');
if (activeColors) activeColors.classList.add('hidden');
};
window.resetSelectCollection = function () {
selectCollection.querySelector('.summary').classList.add('disabled');
selectCollection.querySelector('.select-placeholder').classList.remove('hidden');
selectCollection.querySelector('.select-title').classList.add('hidden');
const activeCollection = selectCollection.querySelector('.collection.active');
if (activeCollection) activeCollection.classList.remove('active');
};
window.resetSelectProduct = function () {
selectProduct.querySelector('.summary').classList.add('disabled');
selectProduct.querySelector('.select-placeholder').classList.remove('hidden');
selectProduct.querySelector('.select-title').classList.add('hidden');
selectProduct.querySelector('.products').innerHTML = '';
};
run(document.querySelector('.visualisation-3d.top .card'));
document.addEventListener('click', function (e) {
const newCard = e.target.closest('.visualisation-3d.top .card:not(.active)');
run(newCard);
});
});
|
javascript
| 17 | 0.732196 | 106 | 38.086957 | 69 |
starcoderdata
|
#ifndef HTTP_AUTH_H
#define HTTP_AUTH_H
#include "array-decl.h"
struct http_auth_param;
struct http_auth_challenge;
struct http_auth_credentials;
ARRAY_DEFINE_TYPE(http_auth_param, struct http_auth_param);
ARRAY_DEFINE_TYPE(http_auth_challenge, struct http_auth_challenge);
struct http_auth_param {
const char *name;
const char *value;
};
struct http_auth_challenge {
const char *scheme;
const char *data;
ARRAY_TYPE(http_auth_param) params;
};
struct http_auth_credentials {
const char *scheme;
const char *data;
ARRAY_TYPE(http_auth_param) params;
};
/*
* Parsing
*/
int http_auth_parse_challenges(const unsigned char *data, size_t size,
ARRAY_TYPE(http_auth_challenge) *chlngs);
int http_auth_parse_credentials(const unsigned char *data, size_t size,
struct http_auth_credentials *crdts);
/*
* Construction
*/
void http_auth_create_challenge(string_t *out,
const struct http_auth_challenge *chlng);
void http_auth_create_challenges(string_t *out,
const ARRAY_TYPE(http_auth_challenge) *chlngs);
void http_auth_create_credentials(string_t *out,
const struct http_auth_credentials *crdts);
/*
* Manipulation
*/
void http_auth_challenge_copy(pool_t pool,
struct http_auth_challenge *dst,
const struct http_auth_challenge *src);
struct http_auth_challenge *
http_auth_challenge_clone(pool_t pool,
const struct http_auth_challenge *src);
void http_auth_credentials_copy(pool_t pool,
struct http_auth_credentials *dst,
const struct http_auth_credentials *src);
struct http_auth_credentials *
http_auth_credentials_clone(pool_t pool,
const struct http_auth_credentials *src);
/*
* Simple schemes
*/
void http_auth_basic_challenge_init(struct http_auth_challenge *chlng,
const char *realm);
void http_auth_basic_credentials_init(struct http_auth_credentials *crdts,
const char *username, const char *password);
#endif
|
c
| 8 | 0.751046 | 74 | 22.9 | 80 |
starcoderdata
|
@NotNull
private static String createStackTraceElementLine(@NotNull String fileName, @NotNull String className, int lineNumber) {
// Method name doesn't matter
String methodName = "foo";
// File's last name appears in stack trace
String fileLastName = new File(fileName).getName();
StackTraceElement element = new StackTraceElement(className, methodName, fileLastName, lineNumber);
return "\tat " + element + "\n";
}
|
java
| 8 | 0.683544 | 124 | 42.181818 | 11 |
inline
|
var drawing = document.getElementById("drawing")
var context = drawing.getContext("2d")
// 线性渐变
function drawLinearGradient() {
var gradient = context.createLinearGradient(30, 30, 70, 70)
gradient.addColorStop(0, "white")
gradient.addColorStop(1, "black")
//绘制红色矩形
context.fillStyle = "#ff0000"
context.fillRect(10, 10, 50, 50)
//绘制渐变矩形
context.fillStyle = gradient
context.fillRect(30, 30, 50, 50)
}
function createRectLinearGradient(context, x, y, width, height) {
return context.createLinearGradient(x, y, x + width, y + width)
}
// drawLinearGradient()
// 径向渐变
function drawRadialGradient() {
var gradient = context.createRadialGradient(55, 55, 10, 55, 55, 30)
gradient.addColorStop(0, "white")
gradient.addColorStop(1, "black")
//绘制红色矩形
context.fillStyle = "#ff0000"
context.fillRect(10, 10, 50, 50)
// 绘制渐变矩形
context.fillStyle = gradient
context.fillRect(30, 30, 50, 50)
}
// drawRadialGradient()
// 同心圆渐变
function drawCircleGradient() {
var gradient = context.createRadialGradient(100,100,30,100,100,100)
gradient.addColorStop(0,"deepskyblue")
gradient.addColorStop(1,"black")
//绘制圆形
context.beginPath()
context.fillStyle = gradient
context.arc(100,100, 100, 0, 2*Math.PI, false)
context.fill()
}
drawCircleGradient()
|
javascript
| 14 | 0.682609 | 71 | 20.230769 | 65 |
starcoderdata
|
import Vue from "vue";
import pathUtil from "web/common/utils/pathUtil";
export default {
createPhoneCode(info){ //info对象包括手机号码和短信类型REGISTER-注册,LOGIN-登录,RESET-找回密码,WITHDRAWALS-提现
return Vue.http.post(pathUtil.getBasePath()+'/registerUser/createPhoneCode',info);
}
}
|
javascript
| 8 | 0.755352 | 92 | 28.818182 | 11 |
starcoderdata
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
#define INF 1010001000
#define loop(i, n) for (int i = 0; i < n; i++)
#define mp make_pair
typedef pair<int, int> i_i;
bool dfs(vector<vector<int> > &g);
int sx, sy, gx, gy;
int w, h;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int main()
{
while (cin >> w >> h, (w|h) ) {
w++;
h++;
vector<vector<int> > graph(w, vector<int>(h, 0));
cin >> sx >> sy >> gx >> gy;
int blocks;
cin >> blocks;
loop(i, blocks){
int c, d, x, y;
cin >> c >> d >> x >> y;
if (d) {
for (int j = x; j < x+2; j++) {
for (int k = y; k < y+4; k++) {
graph[j][k] = c;
}
}
} else {
for (int j = x; j < x+4; j++) {
for (int k = y; k < y+2; k++) {
graph[j][k] = c;
}
}
}
}
cout << ((dfs(graph))?"OK":"NG") << endl;
}
return 0;
}
bool dfs(vector<vector<int> > &g)
{
int cl = g[sx][sy];
vector<vector<bool> > check(w, vector<bool>(h, false));
queue<i_i > q;
q.push(mp(sx,sy));
while(!q.empty()){
int x = q.front().first, y = q.front().second;
q.pop();
if(x == gx && y == gy){
return true;
}
if(check[x][y]){
continue;
} else {
check[x][y] = true;
}
loop(i, 4) {
int nx = x + dx[i], ny = y + dy[i];
if (0 < nx && nx < w && 0 < ny && ny < h){
if (g[nx][ny] == cl){
q.push(mp(nx,ny));
}
}
}
}
return false;
}
|
c++
| 19 | 0.361505 | 59 | 22.227848 | 79 |
codenet
|
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = loadFXML("Home");
primaryStage.setScene(new Scene(root));
//set stage borderless
primaryStage.initStyle(StageStyle.UNDECORATED);
//window resize and drag and drop
ResizeHelper.addResizeListener(primaryStage, 4);
primaryStage.show();
}
|
java
| 8 | 0.63728 | 60 | 32.166667 | 12 |
inline
|
import React from 'react'
import PropTypes from 'prop-types'
import pluginManager from '../plugin/PluginManager'
import { dashifyString } from '../util'
export default function View(props) {
const {
site,
route,
model,
} = props,
view = route.view,
layout = route.layout,
Plugin = pluginManager.getView(view),
className = 'view ' + dashifyString(view) + ' ' + dashifyString(layout)
return (
<div className={className}>
<Plugin site={site} layout={layout} model={model} />
)
}
View.propTypes = {
site: PropTypes.object.isRequired,
route: PropTypes.object.isRequired,
model: PropTypes.object.isRequired,
}
|
javascript
| 11 | 0.660767 | 75 | 23.214286 | 28 |
starcoderdata
|
using System.Reflection;
namespace AutoUml
{
public interface IAssemblyVisitor
{
void Visit(Assembly assembly, UmlDiagram diagram);
}
}
|
c#
| 8 | 0.666667 | 66 | 17.444444 | 9 |
starcoderdata
|
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace NSW.EliteDangerous.INARA
{
public class InaraCommandFixture : IDisposable
{
internal EliteDangerousINARA INARA { get; }
public InaraCommandFixture()
{
INARA = (EliteDangerousINARA)new ServiceCollection()
.AddLogging(cfg => cfg.AddDebug())
.Configure => cfg.MinLevel = LogLevel.Warning)
.AddEliteDangerousINARA(o =>
{
o.ApiKey = "your_apikey_from_inara";
o.ApplicationName = "your_application_name";
o.ApplicationVersion = "1.2.3";
o.Commander = "Your Commander";
o.FrontierId = "F1234567";
o.IsDevelopment = true;
})
.AddSingleton<ISystemClock, TestSystemClock>()
.BuildServiceProvider()
.GetService
}
public void Dispose()
{
}
}
}
|
c#
| 26 | 0.54947 | 87 | 31.371429 | 35 |
starcoderdata
|
public boolean isConnectionValid(Object connectionType, Object fromElement,
Object toElement, boolean checkWFR) {
if (Model.getModelManagementHelper().isReadOnly(fromElement)) {
// Don't allow connections to be created from a read only
// model element to any other
// TODO: This should be considered a workaround. It only works
// because, by default, we place newly created relationships in
// the namespace of the fromElement. The correct behavior in
// the presence of read-only elements really depends on the type of
// connection as well as the writeability of both ends.
return false;
}
// Get the list of valid model item pairs for the given connection type
List<Class<?>[]> validItems = validConnectionMap.get(connectionType);
if (validItems == null) {
return false;
}
// See if there's a pair in this list that match the given
// model elements
for (Class<?>[] modeElementPair : validItems) {
if (modeElementPair[0].isInstance(fromElement)
&& modeElementPair[1].isInstance(toElement)) {
if (checkWFR) {
return isConnectionWellformed(
(Class<?>) connectionType,
(ModelElement) fromElement,
(ModelElement) toElement);
} else {
return true;
}
}
}
return false;
}
|
java
| 16 | 0.559099 | 79 | 46.058824 | 34 |
inline
|
package com.sshtools.icongenerator.tools;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.sshtools.icongenerator.AwesomeIcon;
import com.sshtools.icongenerator.Colors;
import com.sshtools.icongenerator.IconBuilder;
import com.sshtools.icongenerator.IconBuilder.IconShape;
/**
* Very simple icon test. Just shows a grid of random icons. Remove the zero
* seed from {@link Java2DIcons#r} if you want truly random every time.
*/
@SuppressWarnings("serial")
public class Java2DIcons extends JPanel {
private Random r = new Random(0);
Java2DIcons() {
setLayout(new GridLayout(10, 10, 2, 2));
for (int i = 0; i < 100; i++) {
IconBuilder ib = new IconBuilder();
ib.theme(Colors.MATERIAL);
ib.autoColor();
if (r.nextFloat() > 0.5)
ib.bold(true);
if (r.nextFloat() > 0.5)
ib.border((int) (r.nextFloat() * 4f));
ib.shape(IconShape.values()[(int) (IconShape.values().length * r.nextFloat())]);
ib.width(48);
if(r.nextFloat() > 0.5) {
ib.border((int)( 1 + ( r.nextFloat() * 3 ) ));
if(r.nextFloat() > 0.5) {
ib.backgroundOpacity(0);
ib.textColor(0);
}
}
ib.height(48);
if (r.nextFloat() > 0.5) {
ib.icon(AwesomeIcon.values()[(int) (AwesomeIcon.values().length * r.nextFloat())]);
if (r.nextFloat() > 0.5)
ib.text(randWord());
} else
ib.text(randWord());
ib.fontName("Sans");
add(new JLabel(ib.build(Icon.class)));
}
}
String randWord() {
StringBuilder b = new StringBuilder();
for (int i = 0; i < 1 + (int) (r.nextFloat() * 3); i++) {
if (r.nextFloat() > 0.5)
b.append((char) ('a' + (int) (r.nextFloat() * 26f)));
else
b.append((char) ('A' + (int) (r.nextFloat() * 26f)));
}
return b.toString();
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().setLayout(new BorderLayout());
Java2DIcons icons = new Java2DIcons();
f.getContentPane().add(icons);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
|
java
| 19 | 0.656679 | 94 | 26.62069 | 87 |
starcoderdata
|
using Assets.XnaLegacy;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Transforms;
namespace Assets.SpCrsVrPrototypes.Systems
{
public class SphereSyncSystem : JobComponentSystem
{
struct Data
{
[ReadOnly] public ComponentDataArray Positions;
public ComponentDataArray Spheres;
public readonly int Length;
}
[Inject] private Data _data;
struct SyncJob : IJobParallelFor
{
[ReadOnly] public ComponentDataArray Positions;
public NativeArray Spheres;
public void Execute(int index)
{
var sphere = Spheres[index];
sphere.Position = Positions[index].Value + sphere.Offset;
Spheres[index] = sphere;
}
}
private JobHandle _handle;
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
inputDeps.Complete();
var spheres = _data.Spheres.ToNativeArray(Allocator.TempJob);
_handle = new SyncJob
{
Positions = _data.Positions,
Spheres = spheres
}.Schedule(_data.Length, 64, inputDeps);
_handle.Complete();
spheres.CopyToAndDispose(_data.Spheres);
return _handle;
}
}
}
|
c#
| 16 | 0.598559 | 86 | 24.466667 | 60 |
starcoderdata
|
package com.mingyuans.smoke.android;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import com.mingyuans.smoke.Processes;
import com.mingyuans.smoke.SubSmoke;
import com.mingyuans.smoke.android.file.AndroidFilePrinter;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
/**
* Created by yanxq on 2017/2/23.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SmokeJniTest {
@Test
public void testAppenderOpen() {
Processes processes = AndroidProcesses.androidDefault();
processes.addLast(new AndroidFilePrinter());
SubSmoke subSmoke = new SubSmoke("Smoke",processes);
subSmoke.open();
try {
Thread.sleep(3 *1000);
} catch (InterruptedException e) {
subSmoke.error(e);
}
subSmoke.info("hello,Smoke!");
subSmoke.debug("hello,Smoke!");
}
}
|
java
| 9 | 0.693712 | 64 | 23.04878 | 41 |
starcoderdata
|
#!/usr/bin/python3
# http://deeplearning.net/software/theano/tutorial/gradients.html
import numpy as np
import theano as tn
x = tn.tensor.dscalar('x')
y = x**2
gy = tn.tensor.grad(y, x)
print ('dump gradient function')
print (tn.pp (gy))
print ('--> fill((x ** 2), 1.0) means ones(size(x**2))')
f = tn.function([x], gy)
print (tn.pp (f.maker.fgraph.outputs[0]))
print (f(4))
print (np.allclose(f(94.2), 188.4))
'''
derivative of logistic?
'''
x = tn.tensor.dscalar('x')
s = 1 / (1+tn.tensor.exp(-x))
gs = tn.tensor.grad(s, x)
ds = tn.function([x], gs)
print (tn.pp(ds.maker.fgraph.outputs[0]))
'''
my test
'''
x = tn.tensor.dscalar('x')
y = 4*x**3 + 2*x +1
gy = tn.tensor.grad(y, x)
dy = tn.function([x], gy)
print (tn.pp(dy.maker.fgraph.outputs[0]))
|
python
| 10 | 0.628307 | 65 | 20.6 | 35 |
starcoderdata
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package secondassignement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* @author roberto
*/
public class Settings {
public static final String BASE_URL = "http://localhost:8000/sdelab/";
public static String convDate(String date) {
long d = Long.parseLong(date);
String date_s = "";
try{
date_s = new SimpleDateFormat("dd-MM-yyyy").format(d);
} catch(Exception e){
e.printStackTrace();
}
return date_s;
}
public static String convDateHour(String date) {
long d = Long.parseLong(date);
String date_s = "";
try{
date_s = new SimpleDateFormat("dd-MM-yyyyHH:mm:ss").format(d);
}catch(Exception e) {
e.printStackTrace();
}
return date_s;
}
public static String convertFromDateToTimestamp(String date){
Date result = null;
try{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.ITALIAN);
result = df.parse(date);
} catch(Exception e) {
e.printStackTrace();
}
return result.getTime() + "";
}
}
|
java
| 11 | 0.56909 | 79 | 25.321429 | 56 |
starcoderdata
|
package externalapi
import (
"github.com/firemiles/gstats/pkg/annotation"
)
const (
// TypeExternalAPI : ...
TypeExternalAPI = "ExternalAPI"
ParamServer = "server"
ParamURL = "url"
ParamMethod = "method"
ParamStatusCode = "code"
ParamReturnBody = "body"
)
// Get : ...
func Get() []annotation.AnnotationDescriptor {
return []annotation.AnnotationDescriptor{
{
Name: TypeExternalAPI,
ParamNames: []string{ParamURL, ParamMethod, ParamStatusCode, ParamReturnBody},
Validator: validateExternalAPIAnnotation,
},
}
}
func validateExternalAPIAnnotation(anno annotation.Annotation) bool {
return true
}
|
go
| 14 | 0.711628 | 81 | 20.5 | 30 |
starcoderdata
|
public void UpdateLink(LinksBean linkObj,LinkUpdateBean linkUpdateObj) throws Exception
{
//find link by id
Filter IDEqualFilter = new FilterPredicate(
LinksBean.id_property,
FilterOperator.EQUAL, linkObj.getID());
Query q = new Query(LinksBean.LINKS_ENTITY_KIND)
.setFilter(IDEqualFilter);
PreparedQuery pq = datastore.prepare(q);
Entity linkEntity = pq.asSingleEntity();
if(linkEntity!=null){
linkEntity.setProperty(LinksBean.CategoryID_property, linkObj.getCategoryID());
linkEntity.setProperty(LinksBean.note_property, linkObj.getNote());
linkEntity.setProperty(LinksBean.updatedOn_property, new Date());
//datastore.put(linkEntity);
}
//find linkupdate by link id
IDEqualFilter = new FilterPredicate(
LinkUpdateBean.LinkID_property,
FilterOperator.EQUAL, linkUpdateObj.getLinkID());
q = new Query(LinkUpdateBean.LINKUPDATE_ENTITY_KIND)
.setFilter(IDEqualFilter);
pq = datastore.prepare(q);
Entity linkUpdateEntity = pq.asSingleEntity();
//get sequence for linkUpdate
CloudSequenceBean linkUpdateSeqObj = null;
Entity linkUpdateSeqEntity = GetCurrentSequenceForEntityKind(LinkUpdateBean.LINKUPDATE_ENTITY_KIND);
if(linkUpdateSeqEntity==null)
{
linkUpdateSeqObj = new CloudSequenceBean();
linkUpdateSeqObj.setSeq(1);
linkUpdateSeqObj.setKind(LinkUpdateBean.LINKUPDATE_ENTITY_KIND);
linkUpdateSeqEntity = linkUpdateSeqObj.createEntity();
}else
{
linkUpdateSeqObj = new CloudSequenceBean(linkUpdateSeqEntity);
linkUpdateSeqObj.setSeq(linkUpdateSeqObj.getSeq()+1);
linkUpdateSeqObj.setUpdatedOn(new Date());
linkUpdateSeqEntity.setProperty(CloudSequenceBean.sequence_property, linkUpdateSeqObj.getSeq());
linkUpdateSeqEntity.setProperty(CloudSequenceBean.updatedOn_property, linkUpdateSeqObj.getUpdatedOn());
}
//update id for linkUpdateObj
linkUpdateObj.setID(linkUpdateSeqObj.getSeq());
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction txn = datastore.beginTransaction(options);
try {
//update link entity
if(linkEntity!=null){
datastore.put(linkEntity);
}
//delete old linkupdate entity
if(linkUpdateEntity!=null){
datastore.delete(linkUpdateEntity.getKey());
}
//update sequence entity for linkupdate kind
datastore.put(txn, linkUpdateSeqEntity);
//add new linkupdate entity
datastore.put(txn, linkUpdateObj.createEntity());
txn.commit();
} catch (Exception e) {
throw e;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
|
java
| 12 | 0.737995 | 106 | 33.263158 | 76 |
inline
|
var runner_timeout = 10000;
var runner_polling_interval = 512;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchJson(url,data){
return await $.ajax({
crossDomain: true,
url: url,
type: "POST",
data: data,
});
}
async function runner_api_test(){
var a = await runnerGetDetails("db_QO3lJlolQ8TQ2SzL1ng")
console.log(a)
}
function runnerCreate(scriptLang, scriptContents, scriptInput){
var params = {
source_code: scriptContents,
language: scriptLang,
input: scriptInput
};
return fetchJson('/api/runner/create',params);
}
function runnerGetStatus(paramid){
var params = {
id:paramid
};
return fetchJson('/api/runner/get_status',params);
}
function runnerGetDetails(paramid){
var params = {
id:paramid
};
return fetchJson('/api/runner/get_details',params);
}
async function runScript(scriptLang, scriptContents, scriptInput){
var runner_session = await runnerCreate(scriptLang,scriptContents,scriptInput);
var status = runner_session.status;
var timeout_left = runner_timeout;
while(status!='completed' && timeout_left>0){
await sleep(runner_polling_interval);
timeout_left -= runner_polling_interval;
var result = await runnerGetStatus(runner_session.id);
status = result.status;
};
if(status!='completed')
return {
result:'failure',
status:'completed',
stderr:'timeout'
}
else
return await runnerGetDetails(runner_session.id);
}
|
javascript
| 15 | 0.643594 | 83 | 25.142857 | 63 |
starcoderdata
|
<div hidden id="mapview">
<!-- Breadcromb Area Start -->
<section class="jobguru-breadcromb-area">
<div class="breadcromb-bottom">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="breadcromb-box-pagin">
href="/">home
<li class="active-breadcromb"><a href="">Sign up company
<!-- Breadcromb Area End -->
<!-- Login Area Start -->
<section class="jobguru-submit-resume-area section_70">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="submit-resume-box">
<?php echo form_open_multipart('employers/signup', 'id="form"') ?>
<div class="single-resume-feild resume-avatar">
<div class="resume-image">
<img class="file-upload-image" src="<?php echo base_url(); ?>assets/img/resume-avatar.jpg" alt="resume avatar"/>
<div class="file-upload">
<div class="image-upload-wrap">
<input class="file-upload-input" type='file' onchange="readURL(this);" accept="image/*" name="image"/>
<div class="drag-text">
<h3 style="border: none;">Drag and drop a file or select your image
<div class="file-upload-content">
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span class="image-title">Uploaded Image
<?php echo form_error('image', '<small class="text-danger mx-1">', ' ?>
<div class="resume-box">
Information
<div class="single-resume-feild feild-flex-2">
<div class="single-input">
<label for="title">Title*
<input name="title" type="text" placeholder="Company's title" id="title" value="<?php echo set_value('title'); ?>" required>
<?php echo form_error('title', '<small class="text-danger mx-1">', ' ?>
<div class="single-input">
<label for="category">Category*
<select name="category" id="category" required>
<option disabled <?php if (!set_value('category')) echo 'selected'; ?>>- Select Category -
<?php foreach($categories as $category): ?>
<option <?php if(set_value('category') == $category) echo 'selected'; ?> value="<?php echo $category ?>"><?php echo $category ?>
<?php endforeach; ?>
<?php echo form_error('category', '<small class="text-danger mx-1">', ' ?>
<div class="single-resume-feild feild-flex-2">
<div class="single-input">
<label for="email">Email*
<input name="email" type="email" placeholder="Company's Email" id="email" value="<?php echo set_value('email'); ?>" required>
<?php echo form_error('email', '<small class="text-danger mx-1">', ' ?>
<div class="single-input">
<label for="phone">Phone
<input name="phone" type="tel" placeholder="Phone Number" id="phone" value="<?php echo set_value('phone'); ?>">
<?php echo form_error('phone', '<small class="text-danger mx-1">', ' ?>
<div class="single-resume-feild feild-flex-2">
<div class="single-input">
<label for="address">Address*
<input autocomplete="off" name="address" type="text" id="searchInput" placeholder="Street Address" id="address" value="<?php echo set_value('address'); ?>" required>
<?php echo form_error('address', '<small class="text-danger mx-1">', ' ?>
<div class="hiddeninputs">
<input type="hidden" name="" id="location" value="">
<input type="hidden" name="" id="route" value="">
<input type="hidden" name="" id="street_number" value="">
<input type="hidden" name="" id="postal_code" value="">
<input type="hidden" name="" id="locality" value="">
<input type="hidden" name="lat" id="lat1" value="">
<input type="hidden" name="lng" id="lng1" value="">
<div class="single-input">
<label for="start">Start year*
<input name="start" type="number" placeholder="Start year" id="start" min="1870" max="<?php echo date("Y"); ?>" value="<?php echo set_value('start'); ?>" required>
<?php echo form_error('start', '<small class="text-danger mx-1">', ' ?>
<div class="single-resume-feild ">
<div class="single-input">
<label for="description">Description
<textarea name="description" id="description" class="tinymce" placeholder="Write a summary of company ..."><?php echo set_value('description'); ?>
<?php echo form_error('description', '<small class="text-danger mx-1">', ' ?>
<div class="resume-box">
Links
<div class="single-resume-feild feild-flex-2">
<div class="single-input">
<label for="facebook"><i class="fa fa-facebook facebook">
<input name="facebook" type="text" placeholder="Facebook URL" id="facebook" value="<?php echo set_value('facebook'); ?>">
<?php echo form_error('facebook', '<small class="text-danger mx-1">', ' ?>
<div class="single-input">
<label for="linkedin"><i class="fa fa-linkedin linkedin">
<input name="linkedin" type="text" placeholder="LinkedIn URL" id="linkedin" value="<?php echo set_value('linkedin'); ?>">
<?php echo form_error('linkedin', '<small class="text-danger mx-1">', ' ?>
<div class="single-resume-feild ">
<div class="single-input">
<label for="website">Website
<input name="website" type="text" placeholder="Company's website" id="website" value="<?php echo set_value('website'); ?>">
<?php echo form_error('website', '<small class="text-danger mx-1">', ' ?>
<div class="resume-box">
info
<div class="single-resume-feild feild-flex-2">
<div class="single-input">
<label for="username">Full Name*
<input name="username" type="text" placeholder="Enter your name and surname" id="username" value="<?php echo set_value('username'); ?>" required>
<?php echo form_error('username', '<small class="text-danger mx-1">', ' ?>
<div class="single-input">
<label for="employer_email">Email*
<input name="employer_email" type="email" placeholder="Enter your email" id="employer_email" value="<?php echo set_value('employer_email'); ?>" required>
<?php echo form_error('employer_email', '<small class="text-danger mx-1">', ' ?>
<div class="single-resume-feild feild-flex-2">
<div class="single-input">
<label for="password">Password*
<input name="password" type="password" pattern=".{4,}" title="Four or more characters" placeholder="Enter your password" id="password" required>
<?php echo form_error('password', '<small class="text-danger mx-1">', ' ?>
<div class="single-input">
<label for="password_confirm">Confirm Password*
<input name="password_confirm" type="password" pattern=".{4,}" title="Four or more characters" placeholder="Enter your password again" id="password_confirm" required>
<?php echo form_error('password_confirm', '<small class="text-danger mx-1">', ' ?>
<div class="submit-resume">
<button id="form-btn" type="submit"> Create Company <i class='fa fa-spinner fa-spin' style="display:none;">
<!-- Submit Resume Area End -->
<!-- Login Area End -->
|
php
| 10 | 0.405224 | 202 | 63.22043 | 186 |
starcoderdata
|
/*
* Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* Key Management Service
*
* AWS Key Management Service (AWS KMS) is an encryption and key management web
* service. This guide describes the AWS KMS operations that you can call
* programmatically. For general information about AWS KMS, see the <a
* href="http://docs.aws.amazon.com/kms/latest/developerguide/">AWS Key
* Management Service Developer Guide
*
*
*
* AWS provides SDKs that consist of libraries and sample code for various
* programming languages and platforms (Java, Ruby, .Net, iOS, Android, etc.).
* The SDKs provide a convenient way to create programmatic access to AWS KMS
* and other AWS services. For example, the SDKs take care of tasks such as
* signing requests (see below), managing errors, and retrying requests
* automatically. For more information about the AWS SDKs, including how to
* download and install them, see <a href="http://aws.amazon.com/tools/">Tools
* for Amazon Web Services
*
*
*
* We recommend that you use the AWS SDKs to make programmatic API calls to AWS
* KMS.
*
*
* Clients must support TLS (Transport Layer Security) 1.0. We recommend TLS
* 1.2. Clients must also support cipher suites with Perfect Forward Secrecy
* (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral
* Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support
* these modes.
*
*
* Requests
*
*
* Requests must be signed by using an access key ID and a secret access key. We
* strongly recommend that you not use your AWS account (root) access
* key ID and secret key for everyday work with AWS KMS. Instead, use the access
* key ID and secret access key for an IAM user, or you can use the AWS Security
* Token Service to generate temporary security credentials that you can use to
* sign requests.
*
*
* All AWS KMS operations require <a href=
* "http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html"
* >Signature Version 4
*
*
* API Requests
*
*
* AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and
* related events for your AWS account and delivers them to an Amazon S3 bucket
* that you specify. By using the information collected by CloudTrail, you can
* determine what requests were made to AWS KMS, who made the request, when it
* was made, and so on. To learn more about CloudTrail, including how to turn it
* on and find your log files, see the <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/">AWS
* CloudTrail User Guide
*
*
* Resources
*
*
* For more information about credentials and request signing, see the
* following:
*
*
*
*
* <a href=
* "http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html"
* >AWS Security Credentials - This topic provides general information about
* the types of credentials used for accessing AWS.
*
*
*
*
* <a href=
* "http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html"
* >Temporary Security Credentials - This section of the User
* Guide describes how to create and use temporary security credentials.
*
*
*
*
* <a href=
* "http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html"
* >Signature Version 4 Signing Process - This set of topics walks you
* through the process of signing a request using an access key ID and a secret
* access key.
*
*
*
*
* Used APIs
*
*
* Of the APIs discussed in this guide, the following will prove the most useful
* for most applications. You will likely perform actions other than these, such
* as creating keys and assigning policies, by using the console.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.amazonaws.services.kms;
|
java
| 5 | 0.688145 | 80 | 32.86014 | 143 |
starcoderdata
|
public void AccountsGroups_Load(object sender, EventArgs e)
{
_view = (AccountsGroupsForm)sender;
// fill the tree with main categories
int i = 0;
foreach (var category in systemModel.AccountCategories)
{
_view.addCategoryNode(category.ID.ToString(), category.name);
foreach (var group in systemModel.Groups)
{
if (group.parent == null)
{
if (group.AccountCategory.ID == category.ID)
{
_view.addSubGroupNode(_view.Tree().Nodes[i], group.ID.ToString(), group.name);
}
}
}
i++;
}
// fill the tree with main groups and sub groups
foreach (var group in systemModel.Groups)
{
if (!(group.parent == null))
{
TreeNode[] _nodes = _view.Tree().Nodes.Find((group.parent.ID).ToString(), true);
_view.addSubGroupNode(_nodes[_nodes.Length - 1], group.ID.ToString(), group.name);
}
}
}
|
c#
| 21 | 0.448666 | 106 | 37.6875 | 32 |
inline
|
<?php
namespace App\Http\Controllers;
use App\Mail\AccountCreatedMail;
use App\Mail\PasswordChangedMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class UserController extends Controller
{
private function sendAccountCreatedEmail(User $user, String $password)
{
Mail::to($user)->send(new AccountCreatedMail($user->name, $user->email, $password));
}
private function sendPasswordChangedEmail(User $user, String $password)
{
Mail::to($user)->send(new PasswordChangedMail($user->name, $user->email, $password));
}
public function index()
{
return view('users.index');
}
public function registrations()
{
return view('users.registrations', [
'users' => User::where('type', 0)->get()
]);
}
public function list()
{
return view('users.list', [
'users' => User::where('type', '!=', 0)->get(),
]);
}
public function accept_reject(User $user, Request $request)
{
$this->validate($request, [
'action' => 'required'
]);
if ($request->input('action') == 'accept') {
$user->type = 2;
$user->save();
} else if ($request->input('action') == 'reject') {
$user->delete();
}
return redirect()->back();
}
public function create()
{
return view('users.edit', [
'edit' => false,
'user' => null
]);
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3|max:255',
'email' => 'required|email|unique:users,email|max:255',
'phone' => 'required|unique:users,phone',
'id_number' => 'required|unique:users,id_number|max:30',
'position' => 'required|max:255',
'type' => 'required'
]);
$password =
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'phone' => $request->input('phone'),
'id_number' => $request->input('id_number'),
'position' => $request->input('position'),
'password' =>
'type' => $request->input('type')
]);
$this->sendAccountCreatedEmail($user, $password);
return redirect()->route('users-list');
}
public function edit(User $user)
{
return view('users.edit', [
'edit' => true,
'user' => $user
]);
}
public function update(User $user, Request $request)
{
$this->validate($request, [
'name' => 'required|min:3|max:255',
'email' => 'required|email|unique:users,email,' . $user->id . '|max:255',
'phone' => 'required|unique:users,phone,' . $user->id,
'id_number' => 'required|unique:users,id_number,' . $user->id . '|max:30',
'position' => 'required|max:255',
'type' => 'required'
]);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phone = $request->input('phone');
$user->id_number = $request->input('id_number');
$user->position = $request->input('position');
$user->type = $request->input('type');
// if ($request->input('password')) {
// $user->password = Hash::make($request->input('password'));
// }
$user->save();
return redirect()->route('users-list');
}
public function ChangePassword(User $user)
{
$password =
$user->password =
$user->save();
$this->sendPasswordChangedEmail($user, $password);
return redirect()->route('users-list');
}
public function get(string $id)
{
return User::where('id_number', $id)->first();
}
public function get_import()
{
return view('users.import');
}
public function activate(User $user, Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users,email,' . $user->id . '|confirmed|max:255'
]);
$password =
$user->email = $request->email;
$user->password =
$user->type = 2;
$user->save();
$this->sendAccountCreatedEmail($user, $password);
return redirect()->route('users-list');
}
public function import(Request $request)
{
$this->validate($request, [
'users_excel' => 'required|mimes:xlsx,xls'
]);
$date = now();
$extension = $request->users_excel->extension();
$filename = date_format($date, 'Y-m-d-H-i-s') . '.' . $extension;
$request->users_excel->storeAs('users', $filename);
$reader = null;
if ($extension == 'xls') {
$reader = new Xls();
} else if ($extension == 'xlsx') {
$reader = new Xlsx();
}
$spreadsheet = $reader->load(storage_path('app/users/' . $filename));
$imported_users = $spreadsheet->getSheet(0)->toArray();
for ($i = 1; $i < count($imported_users); $i++) {
// create user is it not in the database
$user = User::firstOrCreate(
['id_number' => $imported_users[$i][1]],
[
'name' => $imported_users[$i][0],
'position' => 'طالب',
'type' => 4, // unregistered user
'phone' => $imported_users[$i][11],
'barcode' => $imported_users[$i][81]
]
);
$changed = false;
// Update user details if changed
if ($user->name != $imported_users[$i][0]) {
$changed = true;
$user->name = $imported_users[$i][0];
}
if ($user->barcode != $imported_users[$i][81]) {
$changed = true;
$user->barcode = $imported_users[$i][81];
}
if ($changed) {
$user->save();
}
}
return redirect()->route('users-list');
}
}
|
php
| 17 | 0.571007 | 89 | 24.829596 | 223 |
starcoderdata
|
import {
SHOW_ERROR_MODAL,
HIDE_ERROR_MODAL,
} from '../constant/ActionTypes';
const initState = {
show: 'failed',
message: '',
};
const error = (state = initState, action) => {
switch (action.type) {
// case LOGIN:
// return {
// loginStatus: 'loading',
// message: '',
// }
case SHOW_ERROR_MODAL:
return {
show: 'true',
message: action.message,
}
case HIDE_ERROR_MODAL:
return {
show: 'failed',
message: '',
}
default:
return state
}
}
export default error;
|
javascript
| 12 | 0.596457 | 46 | 14.424242 | 33 |
starcoderdata
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* physics_loop.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kguibout +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/09 13:39:28 by kguibout #+# #+# */
/* Updated: 2020/03/11 15:07:30 by kguibout ### ########.fr */
/* */
/* ************************************************************************** */
#include "physics.h"
#include "mysdl2.h"
void ph_add_update_func(t_ph_context *ph_context,
bool (*update)(void *, float), void *param)
{
ph_context->update = update;
ph_context->param = param;
}
void init_ph_context(t_ph_context *ph_context)
{
ph_context->t = 0.0;
ph_context->dt = DELTATIME;
clock_restart(&ph_context->physics_clock);
ph_context->current_time = clock_get_seconds(
&ph_context->physics_clock);
ph_context->accumulator = 0.0;
}
bool ph_loop(t_ph_context *ph_context)
{
double new_time;
new_time = clock_get_seconds(&ph_context->physics_clock);
ph_context->frame_time = new_time
- ph_context->current_time;
ph_context->current_time = new_time;
ph_context->accumulator += ph_context->frame_time;
while (ph_context->accumulator >= ph_context->dt)
{
if (!ph_context->update(ph_context->param, ph_context->dt))
return (false);
ph_context->accumulator -= ph_context->dt;
ph_context->t += ph_context->dt;
}
return (true);
}
|
c
| 11 | 0.407267 | 80 | 35.88 | 50 |
starcoderdata
|
private boolean isTargetIncludedOrExcludedInSegment(List<String> segmentList, Target target) {
for (String segmentIdentifier : segmentList) {
final Optional<Segment> optionalSegment = query.getSegment(segmentIdentifier);
if (optionalSegment.isPresent()) {
final Segment segment = optionalSegment.get();
// Should Target be excluded - if in excluded list we return false
if (isTargetInList(target, segment.getExcluded())) {
log.debug(
"Target {} excluded from segment {} via exclude list",
target.getName(),
segment.getName());
return false;
}
// Should Target be included - if in included list we return true
if (isTargetInList(target, segment.getIncluded())) {
log.debug(
"Target {} included in segment {} via include list",
target.getName(),
segment.getName());
return true;
}
// Should Target be included via segment rules
List<Clause> rules = segment.getRules();
if ((rules != null) && !rules.isEmpty() && evaluateClauses(rules, target)) {
log.debug(
"Target {} included in segment {} via rules", target.getName(), segment.getName());
return true;
}
}
}
return false;
}
|
java
| 14 | 0.590842 | 97 | 37.714286 | 35 |
inline
|
def create_rule_file(file_path: Path, rule_name: str) -> None:
"""Create a new rule file."""
rule_name = is_valid_name(rule_name)
context = _LICENCE + _IMPORTS + _TO_DOS + _RULE_CLASS
updated_context = invoke_formatter(
get_lint_config().formatter, context.format(class_name=rule_name)
)
with open(file_path, "w") as f:
f.write(updated_context)
print(f"Successfully created {file_path.name} rule file at {file_path.parent}")
|
python
| 10 | 0.651064 | 83 | 38.25 | 12 |
inline
|
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Certificate;
use App\Models\Content;
use App\Models\Image;
use App\Models\Operation;
use App\Models\Research;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\App;
class MainController extends Controller
{
public function main()
{
$researches = Research::latest()->take(5)->get();
$operations = Operation::latest()->take(4)->get();
$images = Image::loadImages();
$data = [
'researches' => $researches,
'operations' => $operations,
'images' => $images
];
return view('main.home', $data);
}
/**
* shows biography page
*
* @return View
*/
public function biography(): View
{
$images = Image::loadImages();
$certificates = Certificate::all();
$data = array(
'images' => $images,
'certificates' => $certificates
);
return view('main.biography', $data);
}
/**
* Show Contact Us Page
*
* @return View
*/
public function contact(): View
{
$images = Image::loadImages();
$data = array(
'images' => $images,
);
return view('main.contact', $data);
}
}
|
php
| 11 | 0.561028 | 58 | 20.227273 | 66 |
starcoderdata
|
package com.smartcar.sdk.data;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.smartcar.sdk.SmartcarException;
import com.smartcar.sdk.Utils;
import java.util.HashMap;
import java.util.Map;
/** Smartcar BatchResponse Object */
public class BatchResponse extends ApiData {
private String requestId;
private Map<String, JsonObject> responseData = new HashMap<>();
private static GsonBuilder gson =
new GsonBuilder().setFieldNamingStrategy((field) -> Utils.toCamelCase(field.getName()));
/**
* Initializes a new BatchResponse.
*
* @param responses the array of Json response objects
*/
public BatchResponse(JsonArray responses) {
for (JsonElement response : responses) {
JsonObject res = response.getAsJsonObject();
String path = res.get("path").getAsString();
this.responseData.put(path, res);
}
}
private <T extends ApiData> T get(String path, Class dataType)
throws SmartcarException {
JsonObject res = this.responseData.get(path);
if (res == null) {
throw new SmartcarException.Builder()
.type("DATA_NOT_FOUND")
.description("The data you requested was not returned")
.build();
}
int statusCode = res.get("code").getAsInt();
JsonObject body = res.get("body").getAsJsonObject();
JsonObject headers = res.get("headers").getAsJsonObject();
headers.addProperty("sc-request-id", this.requestId);
if (statusCode != 200) {
throw SmartcarException.Factory(statusCode, headers, body);
}
String bodyString = body.toString();
T data = gson.create().fromJson(bodyString, dataType);
Meta meta = gson.create().fromJson(res.get("headers").getAsJsonObject().toString(), Meta.class);
data.setMeta(meta);
return data;
}
/**
* Return the Smartcar request id from the response headers
*
* @return the request id
*/
public String getRequestId() {
return this.requestId;
}
/**
* Sets the Smartcar request id from the response headers
*
* @param requestId the request id
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* Get response from the /battery endpoint
*
* @return the battery status of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleBattery battery()
throws SmartcarException {
return get("/battery", VehicleBattery.class);
}
/**
* Get response from the /battery/capacity endpoint
*
* @return the battery capacity of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleBatteryCapacity batteryCapacity()
throws SmartcarException {
return get("/battery/capacity", VehicleBatteryCapacity.class);
}
/**
* Get response from the /charge endpoint
*
* @return the charge status of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleCharge charge()
throws SmartcarException {
return get("/charge", VehicleCharge.class);
}
/**
* Get response from the /fuel endpoint
*
* @return the fuel status of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleFuel fuel()
throws SmartcarException {
return get("/fuel", VehicleFuel.class);
}
/**
* Get response from the / endpoint
*
* @return VehicleAttributes object
* @throws SmartcarException if the request for this endpoint +returned an HTTP error code
*/
public VehicleAttributes attributes() throws SmartcarException {
return get("/", VehicleAttributes.class);
}
/**
* Get response from the /location endpoint
*
* @return the location of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleLocation location()
throws SmartcarException {
return get("/location", VehicleLocation.class);
}
/**
* Get response from the /odometer endpoint
*
* @return the odometer of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleOdometer odometer()
throws SmartcarException {
return get("/odometer", VehicleOdometer.class);
}
/**
* Get response from the /engine/oil endpoint
*
* @return the engine oil status of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleEngineOil engineOil()
throws SmartcarException {
return get("/engine/oil", VehicleEngineOil.class);
}
/**
* Get response from the /vin endpoint
*
* @return the vin of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleVin vin() throws SmartcarException {
return get("/vin", VehicleVin.class);
}
/**
* Get response from the /tires/pressure endpoint
*
* @return the tire pressure status of the vehicle
* @throws SmartcarException if the request for this endpoint returned an HTTP error code
*/
public VehicleTirePressure tirePressure()
throws SmartcarException {
return get("/tires/pressure", VehicleTirePressure.class);
}
/** @return a stringified representation of BatchResponse */
@Override
public String toString() {
return responseData.toString();
}
}
|
java
| 12 | 0.694687 | 100 | 28.958115 | 191 |
starcoderdata
|
#ej 9 profe
def leer_entero_validado():
"""
nada --> int
OBJ: Solicita un entero al usuario y lo valida y lo retorna si solo si
"""
esValido = False
while (not esValido):
try:
entero= int (input('introduce un entero'))
esValido=True
except ValueError:
print ('El entero no es válido')
return entero
#main
if __name__ == '__main__':
entero= leer_entero_validado()
print ('el entero es: ', entero)
|
python
| 14 | 0.566735 | 75 | 23.35 | 20 |
starcoderdata
|
#include "clar_libgit2.h"
#include "repository.h"
#include "backend_helpers.h"
#include "git2/sys/mempack.h"
static git_odb *_odb;
static git_oid _oid;
static git_odb_object *_obj;
static git_repository *_repo;
void test_odb_backend_mempack__initialize(void)
{
git_odb_backend *backend;
cl_git_pass(git_mempack_new(&backend));
cl_git_pass(git_odb_new(&_odb));
cl_git_pass(git_odb_add_backend(_odb, backend, 10));
cl_git_pass(git_repository_wrap_odb(&_repo, _odb));
}
void test_odb_backend_mempack__cleanup(void)
{
git_odb_object_free(_obj);
git_odb_free(_odb);
git_repository_free(_repo);
}
void test_odb_backend_mempack__write_succeeds(void)
{
const char *data = "data";
cl_git_pass(git_odb_write(&_oid, _odb, data, strlen(data) + 1, GIT_OBJECT_BLOB));
cl_git_pass(git_odb_read(&_obj, _odb, &_oid));
}
void test_odb_backend_mempack__read_of_missing_object_fails(void)
{
cl_git_pass(git_oid_fromstr(&_oid, "f6ea0495187600e7b2288c8ac19c5886383a4633"));
cl_git_fail_with(GIT_ENOTFOUND, git_odb_read(&_obj, _odb, &_oid));
}
void test_odb_backend_mempack__exists_of_missing_object_fails(void)
{
cl_git_pass(git_oid_fromstr(&_oid, "f6ea0495187600e7b2288c8ac19c5886383a4633"));
cl_assert(git_odb_exists(_odb, &_oid) == 0);
}
void test_odb_backend_mempack__exists_with_existing_objects_succeeds(void)
{
const char *data = "data";
cl_git_pass(git_odb_write(&_oid, _odb, data, strlen(data) + 1, GIT_OBJECT_BLOB));
cl_assert(git_odb_exists(_odb, &_oid) == 1);
}
void test_odb_backend_mempack__blob_create_from_buffer_succeeds(void)
{
const char *data = "data";
cl_git_pass(git_blob_create_from_buffer(&_oid, _repo, data, strlen(data) + 1));
cl_assert(git_odb_exists(_odb, &_oid) == 1);
}
|
c
| 11 | 0.696899 | 82 | 27.483333 | 60 |
research_code
|
package com.poianitibaldizhou.trackme.grouprequestservice.message.publisher;
import com.poianitibaldizhou.trackme.grouprequestservice.util.GroupRequestWrapper;
public interface GroupRequestPublisher {
/**
* Send the group request wrapper to the message broker (rabbit-mq)
*
* @param groupRequestWrapper the group request wrapper containing also the list of filter statements
*/
void publishGroupRequest(GroupRequestWrapper groupRequestWrapper);
}
|
java
| 7 | 0.789144 | 105 | 33.214286 | 14 |
starcoderdata
|
$('.spotify-embed-close').on('click', function() {
if($('.spotify-embed-block').is(':hidden') && $(window).width() > 768){
$('.spotify-embed-close').animate({
bottom: 250
}, 400);
var top_text = 'Hide <i class="fa fa-angle-down">'
$('.close-text').empty().append(top_text);
} else if($('.spotify-embed-block').is(':hidden') && $(window).width() <= 768){
$('.spotify-embed-close').animate({
bottom: 80
}, 400);
var top_text = 'Hide <i class="fa fa-angle-down">'
$('.close-text').empty().append(top_text);
}
else {
$('.spotify-embed-close').animate({
bottom: 0
}, 400);
var bottom_text = '<i class="fa fa-music">'
$('.close-text').empty().append(bottom_text);
}
$('.spotify-embed-block').slideToggle();
});
|
javascript
| 19 | 0.581989 | 80 | 31.347826 | 23 |
starcoderdata
|
#include
#include
#include
#include
#define PROGRAM_NAME "unit_test-gravity_simulation"
char run;
void close_win(void);
int main(int argc, char *argv[])
{
printf("starting unit test %s\n", PROGRAM_NAME);
if(argc){}
if(argv){}
NUS_mass test_mass = nus_mass_build();
nus_mass_print(test_mass);
nus_movement_set_mass(test_mass.movement, 1);
nus_movement_set_gravity(test_mass.movement, nus_vector_build(0.0, -1.0, 0.0));
nus_mass_batch_update(&test_mass, 0, 0, 1, 2.0);
nus_mass_print(test_mass);
nus_mass_free(&test_mass);
printf("unit test %s completed\n", PROGRAM_NAME);
return 0;
}
|
c
| 8 | 0.665698 | 81 | 19.848485 | 33 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using jr.common.Jira.Models;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace jr.common.Jira
{
public interface IJiraApi
{
JiraIssue GetJiraIssue(long issueId);
JiraIssue GetJiraIssue(string issueKey);
JiraProject GetJiraProject(string projectId);
IEnumerable GetJiraIssuesFromProject(string project);
IEnumerable GetTempoWorkItems(string dateFrom, string dateTo, string accountKey);
}
public class JiraApi : IJiraApi
{
//TODO: use repository pattern / dependency injection?
private readonly string _pwd;
private readonly string _url;
private readonly string _user;
private readonly string _tempoUrl;
private readonly string _tempoApiToken;
[ExcludeFromCodeCoverage]
public JiraApi(string url, string user, string pwd, string tempoUrl, string tempoApiToken)
{
_pwd =
_user = user;
_url = url;
_tempoUrl = tempoUrl;
_tempoApiToken = tempoApiToken;
}
//TODO: consolidate GetJiraIssue methods, shouldn't have two almost exact methods between issueId and issueKey
[ExcludeFromCodeCoverage]
public JiraIssue GetJiraIssue(long issueId)
{
var client = new RestClient(_url + "/rest/api/2")
{
Authenticator = new HttpBasicAuthenticator(_user, _pwd)
};
var request = new RestRequest("issue/{issueId}", Method.GET);
request.AddUrlSegment("issueId", issueId);
var response = client.Execute(request);
Debug.WriteLine($"QUERY: Get issue: Issue:{issueId}");
if (response.IsSuccessful)
{
try
{
var issue = JsonConvert.DeserializeObject
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
}
);
return issue;
}
catch (Exception e)
{
throw new Exception($"Issue ID={issueId}, Json={response.Content}, Exception={e.Message}{e.StackTrace}");
}
}
else
{
throw new Exception($"Issue ID={issueId}, Response Status={response.StatusDescription}");
}
}
[ExcludeFromCodeCoverage]
public JiraIssue GetJiraIssue(string issueKey)
{
var client = new RestClient(_url + "/rest/api/2")
{
Authenticator = new HttpBasicAuthenticator(_user, _pwd)
};
var request = new RestRequest("issue/{issueKey}", Method.GET);
request.AddUrlSegment("issueKey", issueKey);
var response = client.Execute(request);
Debug.WriteLine($"QUERY: Get issue: Issue:{issueKey}");
if (response.IsSuccessful)
{
try
{
var issue = JsonConvert.DeserializeObject
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
}
);
return issue;
}
catch (Exception e)
{
throw new Exception($"Issue ID={issueKey}, Json={response.Content}, Exception={e.Message}{e.StackTrace}");
}
}
else
{
throw new Exception($"Issue ID={issueKey}, Response Status={response.StatusDescription}");
}
}
[ExcludeFromCodeCoverage]
public JiraProject GetJiraProject(string projectId)
{
var client = new RestClient(_url + "/rest/api/2/")
{
Authenticator = new HttpBasicAuthenticator(_user, _pwd)
};
var request = new RestRequest("project/{projectIdOrKey}", Method.GET);
request.AddUrlSegment("projectIdOrKey", projectId);
var response = client.Execute(request);
Debug.WriteLine($"QUERY: Get project: Project:{projectId}");
if (response.IsSuccessful)
{
return JsonConvert.DeserializeObject
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None
}
);
}
else
{
throw new Exception(response.StatusDescription);
}
}
[ExcludeFromCodeCoverage]
public IEnumerable GetJiraIssuesFromProject(string project)
{
var resultsCollection = new List
string jql = $"project={project}";
JiraIssueResults firstResult = GetIssueSearchResultsPaginated(jql, 0, 0);
int maxResults = firstResult.MaxResults;
var startAtPages = JiraServices.GetPagingStartPageNumbers(firstResult.Total, maxResults);
resultsCollection.Add(firstResult);
foreach (var item in startAtPages)
{
var result = GetIssueSearchResultsPaginated(jql, item, maxResults);
resultsCollection.Add(result);
}
return resultsCollection;
}
[ExcludeFromCodeCoverage]
private JiraIssueResults GetIssueSearchResultsPaginated(string jql, int startAt, int maxResults)
{
var client = new RestClient(_url + "/rest/api/2") {Authenticator = new HttpBasicAuthenticator(_user, _pwd)};
var request = new RestRequest("search", Method.GET);
request.AddParameter("jql", jql);
request.AddParameter("fields",
"id,key,summary,issuetype,priority,created,fixVersions,status,customfield_10008,customfield_11600,customfield_10004");
request.AddParameter("startAt", startAt);
if (maxResults > 0) request.AddParameter("maxResults", maxResults);
var response = client.Execute(request);
Debug.WriteLine($"QUERY: Get Issues:{jql}, offset:{startAt}, maxResults:{maxResults}");
if (response.IsSuccessful)
{
var tp = JsonConvert.DeserializeObject
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None
}
);
return tp;
}
else
{
throw new Exception(response.StatusDescription);
}
}
[ExcludeFromCodeCoverage]
public IEnumerable GetTempoWorkItems(string dateFrom, string dateTo, string accountKey)
{
var resultsCollection = new List
string next = string.Empty;
TempoWorkItemResults firstResult = GetTempoSearchResultsPaginated(accountKey, dateFrom, dateTo, 0, 0);
resultsCollection.Add(firstResult);
if (!string.IsNullOrEmpty(firstResult.Metadata.Next))
{
next = firstResult.Metadata.Next;
while (!string.IsNullOrEmpty(next))
{
TempoWorkItemResults results = GetTempoSearchResultsPaginated(next);
resultsCollection.Add(results);
next = results.Metadata.Next;
}
}
return resultsCollection;
}
private TempoWorkItemResults GetTempoSearchResultsPaginated(string url)
{
var client = new RestClient(url)
{
Authenticator = new JwtAuthenticator(_tempoApiToken)
};
var request = new RestRequest(Method.GET);
var response = client.Execute(request);
Debug.WriteLine($"QUERY: Get worklogs: URL:{url}");
if (response.IsSuccessful)
{
var tp = JsonConvert.DeserializeObject
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None
}
);
return tp;
}
else
{
throw new Exception(response.StatusDescription);
}
}
private TempoWorkItemResults GetTempoSearchResultsPaginated(string accountKey, string dateFrom, string dateTo, int startAt, int maxResults)
{
var client = new RestClient(_tempoUrl + "/core/3/")
{
Authenticator = new JwtAuthenticator(_tempoApiToken)
};
var request = new RestRequest("worklogs/account/{accountKey}", Method.GET);
request.AddUrlSegment("accountKey",accountKey);
request.AddQueryParameter("from", dateFrom);
request.AddQueryParameter("to", dateTo);
request.AddParameter("offset", startAt);
if (maxResults > 0) request.AddParameter("limit", maxResults);
var response = client.Execute(request);
Debug.WriteLine($"QUERY: Get worklogs: Account:{accountKey},F:{dateFrom},T:{dateTo},offset:{startAt},limit:{maxResults}");
if (response.IsSuccessful)
{
var tp = JsonConvert.DeserializeObject
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None
}
);
return tp;
}
else
{
throw new Exception(response.StatusDescription);
}
}
}
}
|
c#
| 22 | 0.551073 | 147 | 37.10473 | 296 |
starcoderdata
|
<?php
class KilpailijaController extends BaseController{
public static function index(){
$kilpailijat = Kilpailija::all();
View::make('kilpailija/index.html', array('kilpailijat' => $kilpailijat));
}
public static function store(){
self::check_logged_in();
$params = $_POST;
$attributes = array(
'etunimi' => $params['etunimi'],
'sukunimi' => $params['sukunimi'],
'kayttajatunnus' => $params['kayttajatunnus'],
'salasana' => $params['salasana'],
'usergroup' => $params['usergroup']
);
$kilpailija = new Kilpailija($attributes);
$errors = $kilpailija->errors();
if (count($errors) == 0){
$kilpailija->save();
Redirect::to('/kilpailija', array('message' => 'Kilpailija on lisätty listaukseen!'));
}else{
View::make('kilpailija/add.html', array('errors' => $errors, 'attributes' => $attributes));
}
}
public static function add(){
self::check_logged_in();
View::make('kilpailija/add.html');
}
public static function show($kilpailija_id){
$kilpailija = Kilpailija::find($kilpailija_id);
$osallistumiset = Osallistuminen::haeOsallistumiset($kilpailija_id);
View::make('kilpailija/show.html', array('kilpailija' => $kilpailija, 'osallistumiset' => $osallistumiset));
}
public static function edit($id){
self::check_logged_in();
$kilpailija = Kilpailija::find($id);
View::make('kilpailija/edit.html', array('attributes' => $kilpailija));
}
public static function update($id){
self::check_logged_in();
$params = $_POST;
$attributes = array(
'kilpailija_id' => $id,
'etunimi' => $params['etunimi'],
'sukunimi' => $params['sukunimi'],
'kayttajatunnus' => $params['kayttajatunnus'],
'salasana' => $params['salasana']
);
$kilpailija = new Kilpailija($attributes);
$errors = $kilpailija->errors();
if(count($errors) == 0){
$kilpailija->update($id);
Redirect::to('/kilpailija/' . $kilpailija->kilpailija_id, array('message' => 'Kilpailijan tiedot on päivitetty!'));
}else{
View::make('kilpailija/edit.html', array('errors' => $errors, 'attributes' => $attributes));
}
}
public static function delete($id){
self::check_logged_in();
$kilpailija = new Kilpailija(array('kilpailija_id' => $id));
$kilpailija->delete();
Redirect::to('/kilpailija', array('message' => 'Kilpailija on poistettu!'));
}
}
|
php
| 15 | 0.653018 | 118 | 25.043956 | 91 |
starcoderdata
|
/*
* @method setStorage
* @param { key: String, required } { data: Any, required } { hours: Number }
* @return { Boolean }
*/
export function setStorage (key, data, hours) {
let expires;
if (!key || !data) {
console.error('[localStorage Error]: Key and Data is a must parameter');
return false;
}
expires = hours ? new Date().getTime() + 1000 * 60 * 60 * hours : new Date(0).getTime();
localStorage.setItem(key, JSON.stringify({ data, expires }));
return true;
}
/*
* @method getStorage
* @param { key: String, required }
* @return { Boolean | null }
*/
export function getStorage (key) {
let data, nowTime = new Date().getTime();
if (!key) console.error('[localStorage Error]: Key is a must parameter');
try {
data = JSON.parse(localStorage.getItem(key));
} catch (error) {
return localStorage.getItem(key);
}
if (!data) return null;
if (!data.expires || data.expires >= nowTime) {
return data.data;
} else {
localStorage.removeItem(key);
return null;
}
}
/*
* @method clearStorage
* @param { key: String, required }
* @return null
*/
export function clearStorage (key) {
if (key) {
localStorage.removeItem(key);
} else {
localStorage.clear();
}
}
|
javascript
| 13 | 0.637217 | 90 | 21.068966 | 58 |
starcoderdata
|
void quakelib::ModelWorld::write_stress_drop_factor_hdf5(const hid_t &data_file) const {
double tmp[2];
hid_t values_set;
hid_t pair_val_dataspace;
hsize_t dimsf[2];
herr_t status, res;
// Create dataspace for a single value
dimsf[0] = 1;
pair_val_dataspace = H5Screate_simple(1, dimsf, NULL);
// Create entries for the simulation start/stop years and base longitude/latitude
values_set = H5Dcreate2(data_file, "stress_drop_factor", H5T_NATIVE_DOUBLE, pair_val_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (values_set < 0) exit(-1);
// Record the simulation start/end years
tmp[0] = stressDropFactor();
tmp[1] = stressDropFactor();
status = H5Dwrite(values_set, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &tmp);
// Close the handles we've used
res = H5Dclose(values_set);
}
|
c++
| 8 | 0.670507 | 139 | 35.208333 | 24 |
inline
|
//
using System;
using System.IO;
using System.Threading;
class Test
{
static void Main()
{
Search search = new Search();
search.FindFile("SomeFile.dat");
}
}
class Search
{
// Maintain state information to pass to FindCallback.
class State
{
public AutoResetEvent autoEvent;
public string fileName;
public State(AutoResetEvent autoEvent, string fileName)
{
this.autoEvent = autoEvent;
this.fileName = fileName;
}
}
AutoResetEvent[] autoEvents;
String[] diskLetters;
public Search()
{
// Retrieve an array of disk letters.
diskLetters = Environment.GetLogicalDrives();
autoEvents = new AutoResetEvent[diskLetters.Length];
for(int i = 0; i < diskLetters.Length; i++)
{
autoEvents[i] = new AutoResetEvent(false);
}
}
// Search for fileName in the root directory of all disks.
public void FindFile(string fileName)
{
for(int i = 0; i < diskLetters.Length; i++)
{
Console.WriteLine("Searching for {0} on {1}.",
fileName, diskLetters[i]);
ThreadPool.QueueUserWorkItem(
new WaitCallback(FindCallback),
new State(autoEvents[i], diskLetters[i] + fileName));
}
// Wait for the first instance of the file to be found.
int index = WaitHandle.WaitAny(autoEvents, 3000, false);
if(index == WaitHandle.WaitTimeout)
{
Console.WriteLine("\n{0} not found.", fileName);
}
else
{
Console.WriteLine("\n{0} found on {1}.", fileName,
diskLetters[index]);
}
}
// Search for stateInfo.fileName.
void FindCallback(object state)
{
State stateInfo = (State)state;
// Signal if the file is found.
if(File.Exists(stateInfo.fileName))
{
stateInfo.autoEvent.Set();
}
}
}
//
|
c#
| 18 | 0.559593 | 69 | 24.182927 | 82 |
starcoderdata
|
const express = require('express');
const bodyParser = require('body-parser');
const sigUtil = require('eth-sig-util');
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/log-payment', (req, res) => {
console.log(req.body.address, req.body.msj, req.body.signed);
const params = {
data: req.body.msg,
sig: req.body.signed
};
const recovered = sigUtil.recoverPersonalSignature(params);
if (!recovered || recovered !== req.body.address) {
const err = {
message: 'Invalid credentials'
};
res.status(400).send();
}
res.status(200).send();
});
app.listen(8080, () => {
console.log('app listening on port 8080!');
});
|
javascript
| 14 | 0.652646 | 63 | 23.566667 | 30 |
starcoderdata
|
namespace PCSC.Monitoring
{
/// PC/SC error occurred during device monitoring.
/// <param name="sender">The <see cref="T:PCSC.SCardMonitor" /> sender object.
/// <param name="args">Argument that contains the exception.
public delegate void DeviceMonitorExceptionEvent(object sender, DeviceMonitorExceptionEventArgs args);
}
|
c#
| 4 | 0.730769 | 106 | 50.125 | 8 |
starcoderdata
|
<?php
/**
* Crie uma classe Car
* Instancie três objetos com esta classe
*/
class Car {
}
$peugeot = new Car;
$ford = new Car;
$bmw = new Car;
|
php
| 4 | 0.481675 | 46 | 13.769231 | 13 |
starcoderdata
|
package io.deephaven.csv.benchmark.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;
import java.util.function.IntFunction;
public final class TableMaker {
private final String[] headers;
private final byte[] bytes;
private final TARRAY[] expected;
public TableMaker(final Random rng, final int rows, final int cols, final IntFunction innerArrayFactory,
final IntFunction outerArrayFactory, final Generator generator,
final CellRenderer cellRenderer) {
headers = new String[cols];
for (int c = 0; c < cols; ++c) {
headers[c] = "Col" + (c + 1);
}
expected = outerArrayFactory.apply(cols);
for (int c = 0; c < cols; ++c) {
final TARRAY col = innerArrayFactory.apply(rows);
generator.apply(rng, col, 0, rows);
expected[c] = col;
}
final StringBuilder sb = new StringBuilder();
sb.append(String.join(",", headers)).append('\n');
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (c != 0) {
sb.append(',');
}
cellRenderer.apply(sb, expected[c], r);
}
sb.append('\n');
}
bytes = sb.toString().getBytes(StandardCharsets.UTF_8);
}
public void check(final TARRAY[] actual) {
if (!equalsActual(actual)) {
throw new RuntimeException("expected != actual");
}
}
private boolean equalsActual(final TARRAY[] actual) {
return Arrays.deepEquals(expected, actual);
}
public TARRAY[] expected() {
return expected;
}
public InputStream makeStream() {
return new ByteArrayInputStream(bytes);
}
public String[] headers() {
return headers;
}
public interface Generator {
void apply(Random rng, TARRAY column, int begin, int end);
}
public interface CellRenderer {
void apply(StringBuilder sb, TARRAY col, int rowNum);
}
}
|
java
| 14 | 0.588446 | 116 | 28.773333 | 75 |
starcoderdata
|
using EasyLOB.Data;
namespace EasyLOB.AuditTrail.Data
{
public partial class AuditTrailConfiguration
{
#region Methods
public static void OnSetupProfile(IZProfile profile)
{
profile.Lookup = "Entity";
profile.LINQOrderBy = "Entity";
}
#endregion Methods
}
}
|
c#
| 10 | 0.552561 | 60 | 19.823529 | 17 |
starcoderdata
|
<?php
namespace Prest\Exception;
/**
* Prest\Exception\DomainException
*
* @package Prest\Exception
*/
class DomainException extends \DomainException implements ExceptionInterface
{
use ExceptionInfoAwareTrait;
}
|
php
| 5 | 0.786517 | 76 | 18.071429 | 14 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BmsSurvey.Persistence.Infrastructure
{
using BmsSurvey.Application.Interfaces;
using BmsSurvey.Persistence.Interfaces;
using Microsoft.Extensions.DependencyInjection;
public static class PersistenceConfig
{
public static IServiceCollection AddPersistence(this IServiceCollection services)
{
services.AddScoped<IAuditableDbContext, BmsSurveyDbContext>();
services.AddScoped<IBmsSurveyDbContext, BmsSurveyDbContext>();
return services;
}
}
}
|
c#
| 12 | 0.740854 | 89 | 30.238095 | 21 |
starcoderdata
|
import React, { useEffect, useState } from 'react';
import { ScrollView, StyleSheet, View } from 'react-native';
import PropTypes from 'prop-types';
import axios from '../common/axios';
import { Badge, Button, ListItem, Overlay, Text } from 'react-native-elements';
import { Toast } from 'native-base';
import { connect } from 'react-redux';
import { THEMES } from '../common/themeUtils';
const LicensesListView = ({ selectedTheme }) => {
const [licensesList, setLicensesList] = useState([]);
const [isModalVisible, setIsModalVisible] = useState(false);
const [licenseToShow, setLicenseToShow] = useState({});
useEffect(() => {
getLicensesList();
}, []);
const getLicensesList = () => {
axios
.get('/api/licenses/list')
.then(({ data }) => {
setLicensesList(data);
})
.catch((error) =>
Toast.show({
text: `Error, ${error.message || error}`,
textStyle: { fontFamily: 'System' },
buttonText: 'Dismiss',
type: 'danger',
})
);
};
const openLicenseDetailsModal = (licenseToShow) => {
setLicenseToShow(licenseToShow);
setIsModalVisible(true);
};
const closeLicenseDetailsModal = () => {
setLicenseToShow({});
setIsModalVisible(false);
};
const renderLicenseDetails = () => {
const {
name,
generationDate,
expirationDate,
usedTemplate: { name: templateName },
isActive,
} = licenseToShow;
return (
<Overlay
overlayStyle={
selectedTheme === THEMES.dark ? style.overlayDark : style.overlayLight
}
isVisible
onBackdropPress={closeLicenseDetailsModal}
>
<View style={style.view}>
<Badge
value={isActive ? 'Active' : 'Disabled'}
status={isActive ? 'success' : 'error'}
badgeStyle={style.badge}
/>
<Text style={style.mainText}>License: {name}
<Text style={style.text}>Generation Date: {generationDate}
<Text style={style.text}>Expiration Date: {expirationDate}
<Text style={{ ...style.text, marginBottom: 30 }}>
Used Template: {templateName}
<Button title="Close" onPress={closeLicenseDetailsModal} />
);
};
const licenseDetailsModal = isModalVisible ? renderLicenseDetails() : null;
return (
{licenseDetailsModal}
{licensesList.map((license, index) => (
<ListItem
key={index}
bottomDivider
topDivider
onPress={() => openLicenseDetailsModal(license)}
>
<Badge
value={license.isExpired ? 'EXPIRED' : 'VALID'}
status={license.isExpired ? 'error' : 'success'}
/>
<ListItem.Subtitle
style={{
color: selectedTheme === THEMES.dark ? '#CCCBC8' : '#5E5D5B',
}}
>
{license.customer.name}
))}
);
};
const style = StyleSheet.create({
overlayLight: {
minHeight: '40%',
maxHeight: '80%',
backgroundColor: '#FFFFFF',
},
overlayDark: {
minHeight: '40%',
maxHeight: '80%',
backgroundColor: '#000000',
},
view: {
padding: 10,
},
badge: {
alignSelf: 'flex-start',
},
mainText: {
fontSize: 20,
fontWeight: 'bold',
},
text: {
fontSize: 18,
marginTop: 10,
},
});
LicensesListView.propTypes = {
selectedTheme: PropTypes.string.isRequired,
};
const mapStateToProps = ({ app }) => ({
selectedTheme: app.selectedTheme,
});
export default connect(mapStateToProps)(LicensesListView);
|
javascript
| 20 | 0.577157 | 80 | 25.442953 | 149 |
starcoderdata
|
/*
* *******************************************************************************************
* @author: (Kyri123)
* @copyright Copyright (c) 2019-2020,
* @license MIT License (LICENSE or https://github.com/Kyri123/KAdmin-ArkLIN2/blob/master/LICENSE)
* Github: https://github.com/Kyri123/KAdmin-ArkLIN2
* *******************************************************************************************
*/
"use strict"
// PanelControler
const VUE_panelControler = new Vue({
el : "#panelControler",
data : {
is_update : globalvars.isUpdate,
is_updating : globalvars.isUpdating
}
})
setInterval(() => {
VUE_panelControler.is_update = globalvars.isUpdate
VUE_panelControler.is_updating = globalvars.isUpdating
},2000)
const VUE_panelControlerModals = new Vue({
el : "#panelControlerModals",
data : {
isAdmin : hasPermissions(globalvars.perm, "all/is_admin"),
logArray : []
}
})
setInterval(() => {
if($('#panelControlerLogs').hasClass('show')) $.get(`/nodejs_logs/current.log`)
.done(function(data) {
let array = []
let counter = 0
for(let item of data.split('\n').reverse()) {
let obj = {}
obj.text = item
obj.class = item.includes('[DEBUG_FAILED]')
? "text-danger"
: item.includes('[DEBUG]')
? "text-warning"
: "text-info"
array.push(obj)
counter++
if(counter === 500) break
}
VUE_panelControlerModals.logArray = array
})
},500)
/**
* sendet eine PanelAktion an den Server bzw an das Panel
* @param action
*/
function forceAction(action) {
fireToast(15, "info")
$.post(`/ajax/all`, {
"adminAction": action
}, (datas) => {
try {
let toastData = JSON.parse(datas)
fireToast(toastData.code, toastData.type)
}
catch (e) {
fireToast(33, "error")
}
})
}
|
javascript
| 21 | 0.492544 | 98 | 27.493151 | 73 |
starcoderdata
|
function (receivedMessage, sender, sendResponse) {
var msgdata = receivedMessage.data
if (receivedMessage.title == "pageInfoResponse") {
currentUrl = msgdata.fullUrl;
currentDomain = msgdata.domain;
lastPolicyUpdateDate = msgdata.lastPolicyUpdateDate;
isSupported = msgdata.isSupported;
// if the website supports protocol do the following
if (msgdata.isSupported) {
$("#supportedIcon").removeClass("badge-secondary").addClass("badge-success");
$("#supportedIcon").text("Supported");
$("#updateDate").html(`<p>Last policy change date: ${lastPolicyUpdateDate} <p>`);
}
// if the website does not follow the protocol do the follwing
else {
//change the icon text to not supported and red color
$("#supportedIcon").removeClass("badge-secondary").addClass("badge-danger");
$("#supportedIcon").text("Not Supported");
// add generate receipt button in the UI
$("#generate_receipt_section").html(`<button class="badge badge-pill badge-secondary" id="generateReceiptNonComplaint">Generate Receipt</button>`);
$("#generateReceiptNonComplaint").on('click', function () {
sendMessageToCurrentTab("generateReceipt");
});
//More Information
$("#consentStatusBox").removeClass("alert-secondary").addClass("alert-danger");
$("#consentStatusBox").html("No Receipt Found for this Website");
}
}
if (receivedMessage.title == "UserId_TokenResponse") {
userId = msgdata.userId;
userToken = msgdata.userToken;
}
}
|
javascript
| 18 | 0.698803 | 151 | 37.589744 | 39 |
inline
|
"""
Defining Functions To help with looking at EM Upcoding and Ranking
"""
import sqlalchemy as sa
import sqlalchemy.dialects.postgresql as pg
def get_claims_base_data(claim_lines, codes):
"""
Keyword Args:
claim_lines: Medical Claim Lines table
Returns: sqlalchemy selectable that filters claim lines table to only include last iteration
of paid claims and a certain set of procedure codes.
"""
columns = [
claim_lines.c.personid,
claim_lines.c.servicing_provider_npi,
claim_lines.c.procedure_code,
claim_lines.c.procedure_name,
sa.sql.func.string_to_array(
claim_lines.c.procedure_name, ',').label('procedure_name_array')]
condition = sa.and_(
claim_lines.c.procedure_code is not None,
claim_lines.c.procedure_code.in_(codes))
return sa.select(columns).where(condition)
def add_claims_procedure_stems(claim_lines, codes):
"""
Keyword Args:
claim_lines: Medical Claim Lines table
Returns: sqlalchemy selectable that runs get_claims_base_data and adds the procedure stem
"""
base_without_stems = get_claims_base_data(claim_lines, codes)\
.correlate(None)\
.alias('base_without_stems')
stem = sa.type_coerce(
base_without_stems.c.procedure_name_array,
pg.ARRAY(sa.Text))[1].label('procedure_name_stem')
columns = [
base_without_stems.c.servicing_provider_npi,
base_without_stems.c.procedure_code,
base_without_stems.c.procedure_name,
stem]
return sa.select(columns)
def provider_level_counts(claim_lines, codes):
"""
Keyword Args:
claim_lines: Medical Claim Lines table
Returns: sqlalchemy selectable that takes medical claim lines table and aggregate counts by
servicing_provider_npi and procedure_code level.
"""
claims = add_claims_procedure_stems(claim_lines, codes).correlate(None).alias('claims')
columns = [
claims.c.servicing_provider_npi,
claims.c.procedure_name_stem,
claims.c.procedure_code,
sa.sql.func.count().label('occurrences')]
groups = [
claims.c.servicing_provider_npi,
claims.c.procedure_name_stem,
claims.c.procedure_code]
return sa.select(columns).group_by(*groups)
def provider_all_counts(claim_lines, codes):
"""
Keyword Args:
claim_lines: Medical Claim Lines Table
Returns: sqlalchemy selectable that takes medical claim lines table and runs
provider_level_counts. In addition, adds a total count by provider level
and ranks procedures to flag which ones are "high".
"""
provider_counts = provider_level_counts(claim_lines, codes).correlate(None).alias(
'provider_counts')
columns = [
provider_counts.c.servicing_provider_npi,
provider_counts.c.procedure_name_stem,
provider_counts.c.procedure_code,
provider_counts.c.occurrences,
sa.sql.func.sum(provider_counts.c.occurrences)
.over(partition_by=[provider_counts.c.servicing_provider_npi,
provider_counts.c.procedure_name_stem])
.label('stem_occurrences'),
sa.sql.func.rank().over(
partition_by=[provider_counts.c.procedure_name_stem],
order_by=sa.sql.expression.desc(
provider_counts.c.procedure_code)).label('procedure_rank')]
return sa.select(columns)
def calc_provider_high_encounters(claim_lines, codes):
"""Aggregate Claims Data at the Physician level to get
1. Number of high encounters
2. Percentage of high encounters
Keyword arguments:
claims: A sqlalchemy table object with the relevant claims for a particular procedure group
Returns: A selectable unique at the NPI level with number of high encounters and percentage of
high encounters
"""
aggregated_provider_counts = provider_all_counts(claim_lines, codes).correlate(None).alias(
'aggregated_provider_counts')
encounters = sa.sql.func.sum(aggregated_provider_counts.c.occurrences).label('encounters')
high_encounters = sa.sql.func.sum(sa.case([
(aggregated_provider_counts.c.procedure_rank == 1,
aggregated_provider_counts.c.occurrences)], else_=0)).label('high_encounters')
columns = [
aggregated_provider_counts.c.servicing_provider_npi,
encounters,
high_encounters,
(1.0 * high_encounters / encounters).label('pct_high_encounters')
]
groups = [aggregated_provider_counts.c.servicing_provider_npi]
return sa.select(columns).group_by(*groups)
|
python
| 16 | 0.672923 | 98 | 36.379032 | 124 |
starcoderdata
|
def __init__(self, timeout=5, **kwargs):
super().__init__(**kwargs)
self.timeout = timeout
self.queues = defaultdict(queue.Queue)
self.logger = logging.getLogger(__name__)
# Override default factor & delay
self.factor = 1.5
self.maxDelay = 5.0
|
python
| 8 | 0.57 | 49 | 32.444444 | 9 |
inline
|
/**
* @file Transform ant class attribute
* @author
*/
'use strict';
const classTransformer = require('../base/class');
module.exports = function (attrs, name, tplOpts) {
return classTransformer(attrs, name, tplOpts, true);
};
|
javascript
| 5 | 0.697917 | 56 | 21.153846 | 13 |
starcoderdata
|
// Copyright (C) 2018 Intel Corporation
//
//
// SPDX-License-Identifier: Apache-2.0
//
#include
#include
#include
#include
TEST(FilterRangeTest, Test)
{
using namespace ade::util;
int sum1 = 0;
std::vector v1 = {1,10,100,1000,10000,100000,1000000};
for (auto i: filter(toRange(v1), [&](int /*val*/) { return true; }))
{
sum1 += i;
}
EXPECT_EQ(1111111, sum1);
struct Filter final
{
bool operator()(int /*val*/) const
{
return true;
}
};
sum1 = 0;
for (auto i: filter
{
sum1 += i;
}
EXPECT_EQ(1111111, sum1);
sum1 = 0;
for (auto i: filter(toRange(v1), [&](int /*val*/) { return false; }))
{
sum1 += i;
}
EXPECT_EQ(0, sum1);
sum1 = 0;
for (auto i: filter(toRange(v1), [&](int val)
{
if (1 == val) return true;
return false;
}))
{
sum1 += i;
}
EXPECT_EQ(1, sum1);
sum1 = 0;
for (auto i: filter(toRange(v1), [&](int val)
{
if (1000000 == val) return true;
return false;
}))
{
sum1 += i;
}
EXPECT_EQ(1000000, sum1);
sum1 = 0;
for (auto i: filter(toRange(v1), [&](int val)
{
if (1 == val || 1000000 == val) return true;
return false;
}))
{
sum1 += i;
}
EXPECT_EQ(1000001, sum1);
sum1 = 0;
for (auto i: filter(toRange(v1), [&](int val)
{
if (1000 == val || 10000 == val || 100000 == val) return true;
return false;
}))
{
sum1 += i;
}
EXPECT_EQ(111000, sum1);
}
|
c++
| 13 | 0.424873 | 86 | 20.888889 | 90 |
starcoderdata
|
/*
* 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.
*/
#ifndef _VERIFIER_COMMON_H_
#define _VERIFIER_COMMON_H_
#include "verify_live_heap.h"
#include "verifier_metadata.h"
#include "../common/gc_common.h"
#include "../common/gc_space.h"
#include "../gen/gen.h"
#include "../mark_sweep/gc_ms.h"
#include "../semi_space/sspace.h"
#include "../common/space_tuner.h"
#ifdef USE_32BITS_HASHCODE
#include "../common/hashcode.h"
#endif
#ifdef USE_UNIQUE_MARK_SWEEP_GC
#include "../mark_sweep/wspace_mark_sweep.h"
#endif
#include "../common/gc_concurrent.h"
struct Heap_Verifier;
struct Allocation_Verifier;
struct GC_Verifier;
struct WriteBarrier_Verifier;
struct RootSet_Verifier;
typedef void (*Object_Scanner)(struct Heap_Verifier*);
typedef struct Heap_Verifier{
GC* gc;
GC_Verifier* gc_verifier;
WriteBarrier_Verifier* writebarrier_verifier;
RootSet_Verifier* rootset_verifier;
Allocation_Verifier* allocation_verifier;
Heap_Verifier_Metadata* heap_verifier_metadata;
Boolean is_before_gc;
Boolean gc_is_gen_mode;
Boolean need_verify_gc;
Boolean need_verify_allocation;
Boolean need_verify_rootset;
Boolean need_verify_writebarrier;
Object_Scanner all_obj_scanner;
Object_Scanner live_obj_scanner;
} Heap_Verifier;
typedef Boolean (*Object_Comparator)(POINTER_SIZE_INT*, POINTER_SIZE_INT*);
extern Heap_Verifier* get_heap_verifier();
extern void verifier_metadata_initialize(Heap_Verifier* heap_verifier);
extern void verifier_init_object_scanner(Heap_Verifier* heap_verifier);
extern void verifier_scan_los_objects(Space* space, Heap_Verifier* heap_verifier);
Boolean verifier_copy_rootsets(GC* gc, Heap_Verifier* heap_verifier);
Boolean verifier_compare_objs_pools(Pool* objs_pool_before_gc, Pool* objs_pool_after_gc, Pool* free_pool ,Object_Comparator object_comparator);
Boolean verifier_parse_options(Heap_Verifier* heap_verifier, char* options);
void verifier_log_before_gc(Heap_Verifier* heap_verifier);
void verifier_log_after_gc(Heap_Verifier* heap_verifier);
void verifier_log_start(const char* message);
Boolean verify_rootset_slot(REF* p_ref, Heap_Verifier* heap_verifier);
inline void verifier_set_gen_mode(Heap_Verifier* heap_verifier)
{ heap_verifier->gc_is_gen_mode = gc_is_gen_mode(); }
inline Boolean need_verify_gc_effect(Heap_Verifier* heap_verifier)
{ return heap_verifier->need_verify_gc && !heap_verifier->is_before_gc; }
inline Boolean need_scan_live_objs(Heap_Verifier* heap_verifier)
{
if(heap_verifier->need_verify_gc) return TRUE;
else if(heap_verifier->need_verify_writebarrier && !heap_verifier->is_before_gc) return TRUE;
else return FALSE;
}
inline Boolean need_verify_mutator_effect(Heap_Verifier* heap_verifier)
{
if(!heap_verifier->is_before_gc) return FALSE;
return heap_verifier->need_verify_allocation || heap_verifier->need_verify_rootset
|| heap_verifier->need_verify_writebarrier;
}
inline Boolean need_scan_all_objs(Heap_Verifier* heap_verifier)
{
if(!heap_verifier->is_before_gc) return FALSE;
return heap_verifier->need_verify_allocation || heap_verifier->need_verify_writebarrier;
}
inline void verify_live_object_slot(REF* p_ref, Heap_Verifier* heap_verifier)
{
assert(p_ref);
assert(address_belongs_to_gc_heap(read_slot(p_ref), (GC*)heap_verifier->gc));
Partial_Reveal_Object* UNUSED p_obj = read_slot(p_ref);
assert(p_obj);
assert(decode_vt(obj_get_vt(p_obj)));
assert(!address_belongs_to_gc_heap(decode_vt(obj_get_vt(p_obj)), (GC*)heap_verifier->gc));
#ifdef USE_UNIQUE_MARK_SWEEP_GC
GC_MS* gc = (GC_MS*)heap_verifier->gc;
if(!heap_verifier->is_before_gc){
/*in GC_MS mark sweep algorithm, all live objects should be set their mark bit*/
assert(obj_is_alloc_in_color_table(p_obj));
if(!obj_is_alloc_in_color_table(p_obj))
printf("\nERROR: obj after GC should be set its alloc color!\n");
}else{
if( !in_con_idle(heap_verifier->gc) )
assert(obj_is_mark_black_in_table(p_obj));
}
#endif
}
inline void verify_all_object_slot(REF* p_ref, Heap_Verifier* heap_verifier)
{
assert(p_ref);
assert(address_belongs_to_gc_heap(read_slot(p_ref), (GC*)heap_verifier->gc));
}
inline void verify_object_header(Partial_Reveal_Object* p_obj, Heap_Verifier* heap_verifier)
{
assert(p_obj);
assert(address_belongs_to_gc_heap(p_obj, (GC*)heap_verifier->gc));
assert(obj_get_vt(p_obj));
/*FIXME:: should add more sanity checks, such as vt->gcvt->class... */
assert(!address_belongs_to_gc_heap(decode_vt(obj_get_vt(p_obj)), (GC*)heap_verifier->gc));
}
inline void verifier_clear_rootsets(Heap_Verifier* heap_verifier)
{
Heap_Verifier_Metadata* verifier_metadata = heap_verifier->heap_verifier_metadata;
verifier_clear_pool(verifier_metadata->root_set_pool, verifier_metadata->free_set_pool, FALSE);
}
#define VERIFY_WB_MARK_BIT 0x01
inline void wb_mark_in_slot(REF* p_ref){
REF ref = *p_ref;
*p_ref = (REF)((POINTER_SIZE_INT)ref | VERIFY_WB_MARK_BIT);
}
inline void wb_unmark_in_slot(REF* p_ref){
REF ref = *p_ref;
*p_ref = (REF)((POINTER_SIZE_INT)ref & ~VERIFY_WB_MARK_BIT);
}
inline Boolean wb_is_marked_in_slot(REF* p_ref){
REF ref = *p_ref;
return (Boolean)((POINTER_SIZE_INT)ref & VERIFY_WB_MARK_BIT);
}
inline REF verifier_get_object_slot(REF* p_ref)
{
REF ref = *p_ref;
return (REF)((POINTER_SIZE_INT)ref | VERIFY_WB_MARK_BIT);
}
/*
#define UNREACHABLE_OBJ_MARK_IN_VT 0x02
inline void tag_unreachable_obj(Partial_Reveal_Object* p_obj)
{
VT vt = obj_get_vt_raw(p_obj);
obj_set_vt(p_obj, (VT)((POINTER_SIZE_INT)vt | UNREACHABLE_OBJ_MARK_IN_VT));
}
inline Boolean is_unreachable_obj(Partial_Reveal_Object* p_obj)
{
return (Boolean)((POINTER_SIZE_INT)obj_get_vt_raw(p_obj) & UNREACHABLE_OBJ_MARK_IN_VT);
}*/
#endif
|
c
| 14 | 0.724838 | 143 | 32.153061 | 196 |
starcoderdata
|
static void on_destroy(ANativeActivity* na) {
traceln("pid/tid=%d/%d na=%p", getpid(), gettid(), na);
glue_t* glue = (glue_t*)na->instance;
app_t* a = glue->a;
assert(glue->sensor_event_queue != null);
if (glue->sensor_event_queue != null) {
ASensorManager_destroyEventQueue(glue->sensor_manager, glue->sensor_event_queue);
glue->sensor_event_queue = null;
}
glue->destroy_requested = true;
if (glue->timer_thread != 0) {
synchronized_signal(glue->mutex, glue->cond, glue->timer_next_ns = 0); // wake up timer_thread
pthread_join(glue->timer_thread, null); glue->timer_thread = 0;
}
pthread_mutex_destroy(&glue->mutex);
pthread_cond_destroy(&glue->cond);
close(glue->read_pipe); glue->read_pipe = 0;
close(glue->write_pipe); glue->write_pipe = 0;
AConfiguration_delete(glue->config); glue->config = 0;
glue->sensor_manager = null; // shared instance do not hold on to
glue->accelerometer_sensor = null;
if (a->done != null) { a->done(a); }
assert(glue->display == null);
assert(glue->surface == null);
assert(glue->context == null);
a->focused = null;
glue->na = null;
}
|
c
| 10 | 0.621327 | 102 | 41.571429 | 28 |
inline
|
<?php
declare(strict_types=1);
namespace Tipoff\Checkout\Tests\Unit\View\Components\Order;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\Component;
use Tipoff\Authorization\Models\User;
use Tipoff\Checkout\Models\Order;
use Tipoff\Checkout\Models\OrderItem;
use Tipoff\Checkout\Tests\Support\Models\TestSellable;
use Tipoff\Checkout\Tests\TestCase;
use Tipoff\Support\Objects\DiscountableValue;
class OrderTest extends TestCase
{
use DatabaseTransactions;
public function setUp(): void
{
parent::setUp();
$this->artisan('view:clear')->run();
TestSellable::createTable();
// Dynamic Component has static data, so need to ensure this gets included
$this->resetDynamicComponent();
Blade::component('tipoff-custom-order-item', CustomItem::class);
}
/** @test */
public function order_with_item()
{
$user = User::factory()->create();
$this->actingAs($user);
/** @var TestSellable $sellable */
$sellable = TestSellable::factory()->create();
$order = Order::factory()->create();
$orderItem = OrderItem::factory()->withSellable($sellable)->create([
'quantity' => 2,
'order_id' => $order,
'amount_each' => new DiscountableValue(1000),
]);
$order->refresh();
$view = $this->blade(
'<x-tipoff-order :order="$order" />',
['order' => $order]
);
$view->assertSee($orderItem->description);
$view->assertSee('2');
$view->assertSee('$10.00');
$view->assertSee('$0.00');
$view->assertSee('$20.00');
}
/** @test */
public function order_with_custom_item()
{
CustomSellable::createTable();
$user = User::factory()->create();
$this->actingAs($user);
/** @var CustomSellable $sellable */
$sellable = CustomSellable::factory()->create();
$order = Order::factory()->create();
OrderItem::factory()->withSellable($sellable)->create([
'order_id' => $order,
]);
$order->refresh();
$view = $this->blade(
'<x-tipoff-order :order="$order" />',
['order' => $order]
);
$view->assertSee('I am custom!');
}
}
class CustomSellable extends TestSellable
{
public function getViewComponent($context = null)
{
return implode('-', ['tipoff','custom', $context]);
}
}
class CustomItem extends Component
{
public function render()
{
return ' am custom!
}
}
|
php
| 15 | 0.586104 | 82 | 24.740385 | 104 |
starcoderdata
|
package es.upm.miw.apaw_practice.adapters.mongodb.movie;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.daos.CinemaRepository;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.daos.FilmDirectorRepository;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.daos.MovieRepository;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.entities.CinemaEntity;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.entities.FilmDirectorEntity;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.entities.FilmRoomEntity;
import es.upm.miw.apaw_practice.adapters.mongodb.movie.entities.MovieEntity;
import es.upm.miw.apaw_practice.domain.models.movie.Movie;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
@Service
public class MovieSeederService {
@Autowired
private CinemaRepository cinemaRepository;
@Autowired
private FilmDirectorRepository filmDirectorRepository;
@Autowired
private MovieRepository movieRepository;
public void seedDatabase() {
LogManager.getLogger(this.getClass()).warn("------- Movie Initial Load -----------");
FilmDirectorEntity[] filmDirectories = {
FilmDirectorEntity.builder().name("Jose").fulName("
FilmDirectorEntity.builder().name("Pedro").fulName("
FilmDirectorEntity.builder().name("Marta").fulName("
FilmDirectorEntity.builder().name("Luis").fulName("
FilmDirectorEntity.builder().name("Hector").fulName("
};
this.filmDirectorRepository.saveAll(Arrays.asList(filmDirectories));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
MovieEntity[] movies = {
new MovieEntity(new Movie("Frozen", filmDirectories[4], LocalDateTime.parse("1986-04-08 10:30", formatter), "ppppppp", 10)),
new MovieEntity(new Movie("Kill", filmDirectories[0], LocalDateTime.parse("2000-02-23 20:50", formatter), "dddddddddd", 2)),
new MovieEntity(new Movie("Avengers", filmDirectories[4], LocalDateTime.parse("2010-01-09 14:12", formatter), "tttttttt", 5)),
new MovieEntity(new Movie("Deadpool", filmDirectories[3], LocalDateTime.parse("2020-02-14 18:20", formatter), "ggggggg", 6)),
new MovieEntity(new Movie("Let's Be Cops", filmDirectories[1], LocalDateTime.parse("1986-06-08 13:21", formatter), "lllllll", 3)),
new MovieEntity(new Movie("The dark Knight", filmDirectories[2], LocalDateTime.parse("1986-11-03 23:32", formatter), "wwwwwww", 7)),
new MovieEntity(new Movie("X-Men", filmDirectories[3], LocalDateTime.parse("1986-05-14 11:23", formatter), "yyyyyyyyyy", 9)),
new MovieEntity(new Movie("The Simpsons", filmDirectories[4], LocalDateTime.parse("1986-02-17 20:30", formatter), "qqqqqqq", 1))
};
this.movieRepository.saveAll(Arrays.asList(movies));
FilmRoomEntity[] filmRooms = {
new FilmRoomEntity(150, 12, true),
new FilmRoomEntity(85, 14, false),
new FilmRoomEntity(70, 8, false),
new FilmRoomEntity(67, 15, false),
new FilmRoomEntity(170, 10, true),
new FilmRoomEntity(55, 3, false),
new FilmRoomEntity(55, 7, false),
new FilmRoomEntity(55, 9, false)
};
CinemaEntity[] cinemas = {
new CinemaEntity(List.of(movies[0], movies[1], movies[3]), List.of(filmRooms[0], filmRooms[1]), "YelmoCine", new BigDecimal("10.23"), "Alcorcon"),
new CinemaEntity(List.of(movies[1], movies[1]), List.of(filmRooms[2], filmRooms[3]), "OdeonCine", new BigDecimal("9.24"), "Mostoles"),
new CinemaEntity(List.of(movies[4], movies[5], movies[7]), List.of(filmRooms[4], filmRooms[5]), "Cinepolis", new BigDecimal("8.34"), "Fuenlabrada"),
new CinemaEntity(List.of(movies[2], movies[3], movies[0]), List.of(filmRooms[6], filmRooms[7]), "Cinessa", new BigDecimal("8.45"), "Boadilla")
};
this.cinemaRepository.saveAll(Arrays.asList(cinemas));
}
public void deleteAll() {
this.cinemaRepository.deleteAll();
this.movieRepository.deleteAll();
this.filmDirectorRepository.deleteAll();
}
}
|
java
| 13 | 0.674068 | 164 | 59.43038 | 79 |
starcoderdata
|
class Solution {
public:
//using matrix chain multiplication
int sol(vector nums, int l, int r, vector dp){
if(l==r)
return 0;
if(dp[l][r] != -1)
return dp[l][r];
dp[l][r] = 0;
for(int k = l; k < r; k++){
dp[l][r] = max(dp[l][r], sol(nums, l, k, dp) + sol(nums, k + 1, r, dp) + nums[l-1] * nums[k] * nums[r]);
}
return dp[l][r];
}
int maxCoins(vector nums){
nums.insert(nums.begin() + 0, 1);
nums.push_back(1);
int siz = nums.size();
vector dp(siz, vector -1));
return sol(nums, 1, siz - 1, dp);
}
};
|
c++
| 16 | 0.435239 | 116 | 23.485714 | 35 |
starcoderdata
|
//
// FireToGps.h
// TXYBaiDuNewApp
//
// Created by yunlian on 15/10/22.
// Copyright (c) 2015年 yunlian. All rights reserved.
//
#import
#import
@interface FireToGps : NSObject
+ (instancetype)sharedIntances;
- (CLLocationCoordinate2D)gcj02Decrypt:(double)gjLat gjLon:(double)gjLon;
- (BOOL)outOfChina:(double)lat bdLon:(double)lon;
-(CLLocationCoordinate2D)hhTrans_GCGPS:(CLLocationCoordinate2D)baiduGps;
-(CLLocationCoordinate2D)hhTrans_bdGPS:(CLLocationCoordinate2D)fireGps;
- (CLLocationCoordinate2D)gcj02Encrypt:(double)ggLat bdLon:(double)ggLon;
@end
|
c
| 5 | 0.784711 | 73 | 32.736842 | 19 |
starcoderdata
|
<?php
namespace App\Http\Services\Tier;
class DogHandler extends AbstractHandler
{
public function handle(string $request): ?string
{
if ($request === "MeatBall") {
return "Dog: I'll eat the " . $request . ".\n";
}
return parent::handle($request);
}
}
|
php
| 11 | 0.612536 | 59 | 20.9375 | 16 |
starcoderdata
|
int main(int argc, char** argv)
{
OPTICKS_LOG(argc, argv);
//nconvexpolyhedron* cpol = test_make_trapezoid();
nconvexpolyhedron* cpol = test_make_segment();
dump(cpol);
return 0 ;
}
|
c++
| 7 | 0.626214 | 54 | 17.818182 | 11 |
inline
|
package com.zhihei.jdk8;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
/**
* @author ZKY
* @createTime 2019/7/5 1:08
* @description
*/
public class PersonTest
{
public static void main(String[] args)
{
Person person1 = new Person("zhangsan", 20);
Person person2 = new Person("wangwu", 30);
Person person3 = new Person("lisi", 40);
List personList = Arrays.asList(person1, person2, person3);
PersonTest test = new PersonTest();
// List personResult = test.getPersonByUserName("zhangsan", personList);
// List personResult = test.getPersonByAge(25, personList);
// personResult.forEach(person -> {
// System.out.println(person.toString());
// });
List personResult = test.getPersonByAge2(20, personList, (age, persons) -> {
return personList.stream().filter(person -> person.getAge() > age).collect(Collectors.toList());
});
personResult.forEach(person -> {
System.out.println(person.toString());
});
System.out.println("-------------");
List personResult2 = test.getPersonByAge2(20, personList, (age, persons) -> {
return personList.stream().filter(person -> person.getAge() <= age).collect(Collectors.toList());
});
personResult2.forEach(person -> {
System.out.println(person.toString());
});
}
public List getPersonByUserName(String userName, List personList)
{
return personList.stream().filter(person -> person.getUsername().equals(userName)).collect(Collectors.toList());
}
/**
* 这里大于写死了
*
* @param age
* @param personList
* @return
*/
public List getPersonByAge(int age, List personList)
{
//参数2个,返回值一个 符合Bifunction函数
BiFunction<Integer, List List biFunction = (userAge, persons) -> persons.stream()
.filter(person -> person.getAge() > userAge)
.collect(Collectors.toList());
return biFunction.apply(age, personList);
}
/**
* 动作动态化
*
* @param age
* @param personList
* @param biFunction
* @return
*/
public List getPersonByAge2(int age, List personList, BiFunction<Integer, List List biFunction)
{
return biFunction.apply(age, personList);
}
}
|
java
| 19 | 0.56745 | 142 | 31.151163 | 86 |
starcoderdata
|
<!DOCTYPE HTML>
<html lang="es">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
echo $titulo ?> : BINormalizador
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/datepicker.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css//datepicker3.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/justified-nav.css" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" media="all">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/font-awesome.min.css" >
<!-- <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/barra.css" > -->
<script src="<?php echo base_url(); ?>assets/js/ie-emulation-modes-warning.js">
<script src="<?php echo base_url(); ?>assets/js/bootstrap-datepicker.min.js">
.think{
display: none;
}
.lexHide{
display: none;
}
.sep{
display: none;
}
.bloq1{
display: none;
}
#dateRangeForm .form-control-feedback {
top: 0;
right: -15px;
}
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="col-xs-2">
<img class="img-circle" src="<?php echo base_url(); ?>assets/Imagenes/Sistema/BINormalizador.jpg" alt="Generic placeholder image" width="80" height="80">
<div class="col-xs-4">
<h2 class="text-muted">BINormalizador
<div class="col-md-6">
<div class="col-md-6">
<div class="col-xs-1">
<div class="col-xs-1">
<div class="col-xs-6">
<h6 class="text-right text-muted">Usuario : <?php echo $usuario ?>
<h6 class="text-right text-muted">Nombre : <?php echo $nombre ?>
<h6 class="text-right text-muted">Perfil : <?php echo $perfil ?>
<h6 class="text-right text-muted">Cuenta : <?php echo $cuenta ?>
<div class="col-xs-2">
<img class="img-circle" src="<?php echo base_url(); ?>assets/Imagenes/Usuarios/<?php echo $usuario.'.gif' ?> " alt="Generic placeholder image" width="80" height="80">
<div class="row">
<div class="col-lg-12">
<?php
if ($this->session->userdata('cambia') == 0)
{
echo '<div class="btn-group">';
echo '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">';
echo '<i class="fa fa-safari fa-fw">
echo '
echo '<ul class="dropdown-menu" role="menu">';
echo ' href="'.base_url().'home/"><i class="fa fa-home fa-fw"> Home
echo '
echo '
}
?>
<?php
if($cuenta == 'Adm sitio')
{
if ($this->session->userdata('cambia') == 0)
{
echo '<div class="btn-group">';
echo '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">';
echo '<i class="fa fa-university fa-lg fa-fw">
echo '
echo '<ul class="dropdown-menu" role="menu">';
echo ' href="'.base_url().'Usuarios/"><i class="fa fa-users fa-fw"> Usuarios
echo ' href="'.base_url().'Perfiles/"><i class="fa fa-graduation-cap fa-fw"> Perfiles
echo ' href="'.base_url().'Clientes/"><i class="fa fa-btc fa-fw"> Clientes
echo ' href="'.base_url().'Cuentas/"><i class="fa fa-credit-card fa-fw"> Cuentas
echo ' href="'.base_url().'Tablas/"><i class="fa fa-bookmark-o fa-fw"> Tablas
echo '
echo '
}
}
?>
<?php
if ($this->session->userdata('cambia') == 0)
{
echo '<div class="btn-group">';
echo '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">';
echo '<i class="fa fa-list-ol fa-lg fa-fw">
echo '
echo '<ul class="dropdown-menu" role="menu">';
echo ' href="'.base_url().'Procesos/"><i class="fa fa-level-up fa-fw"> Procesar
echo ' href="'.base_url().'Registros/"><i class="fa fa-sort-amount-asc fa-fw"> Registros
echo '<li class="divider">
echo ' href="'.base_url().'Usuarios/CambiaClave"><i class="fa fa-asterisk fa-fw"> Clave
echo ' href="'.base_url().'Login/"><i class="fa fa-user-times fa-fw"> Logout
echo '<li class="divider">
echo ' href="'.base_url().'About/"><i class="fa fa-thumbs-up fa-fw"> About
echo '
echo '
}
else
{
echo ' href="'.base_url().'Login/"><i class="fa fa-user-times fa-fw"> Logout
}
?>
<div class="row">
<div class="col-lg-12">
<div class="alert alert-success">
<i class="fa fa-magic fa-fw"> Sistema de Normalización de documentos de BI
|
php
| 10 | 0.540759 | 176 | 41.845588 | 136 |
starcoderdata
|
//
// walkFilters.js
// version 1.1
//
// Created by June 2015
// Copyright © 2014 - 2015 High Fidelity, Inc.
//
// Provides a variety of filters for use by the walk.js script v1.2+
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
// simple averaging (LP) filter for damping / smoothing
AveragingFilter = function(length) {
// initialise the array of past values
this.pastValues = [];
for (var i = 0; i < length; i++) {
this.pastValues.push(0);
}
// single arg is the nextInputValue
this.process = function() {
if (this.pastValues.length === 0 && arguments[0]) {
return arguments[0];
} else if (arguments[0] !== null) {
this.pastValues.push(arguments[0]);
this.pastValues.shift();
var nextOutputValue = 0;
for (var value in this.pastValues) nextOutputValue += this.pastValues[value];
return nextOutputValue / this.pastValues.length;
} else {
return 0;
}
};
};
// 2nd order 2Hz Butterworth LP filter
ButterworthFilter = function() {
// coefficients calculated at: http://www-users.cs.york.ac.uk/~fisher/mkfilter/trad.html
this.gain = 104.9784742;
this.coeffOne = -0.7436551950;
this.coeffTwo = 1.7055521455;
// initialise the arrays
this.xv = [];
this.yv = [];
for (var i = 0; i < 3; i++) {
this.xv.push(0);
this.yv.push(0);
}
// process values
this.process = function(nextInputValue) {
this.xv[0] = this.xv[1];
this.xv[1] = this.xv[2];
this.xv[2] = nextInputValue / this.gain;
this.yv[0] = this.yv[1];
this.yv[1] = this.yv[2];
this.yv[2] = (this.xv[0] + this.xv[2]) +
2 * this.xv[1] +
(this.coeffOne * this.yv[0]) +
(this.coeffTwo * this.yv[1]);
return this.yv[2];
};
}; // end Butterworth filter constructor
// Add harmonics to a given sine wave to form square, sawtooth or triangle waves
// Geometric wave synthesis fundamentals taken from: http://hyperphysics.phy-astr.gsu.edu/hbase/audio/geowv.html
WaveSynth = function(waveShape, numHarmonics, smoothing) {
this.numHarmonics = numHarmonics;
this.waveShape = waveShape;
this.smoothingFilter = new AveragingFilter(smoothing);
// NB: frequency in radians
this.calculate = function(frequency) {
// make some shapes
var harmonics = 0;
var multiplier = 0;
var iterations = this.numHarmonics * 2 + 2;
if (this.waveShape === TRIANGLE) {
iterations++;
}
for (var n = 1; n < iterations; n++) {
switch (this.waveShape) {
case SAWTOOTH: {
multiplier = 1 / n;
harmonics += multiplier * Math.sin(n * frequency);
break;
}
case TRIANGLE: {
if (n % 2 === 1) {
var mulitplier = 1 / (n * n);
// multiply (4n-1)th harmonics by -1
if (n === 3 || n === 7 || n === 11 || n === 15) {
mulitplier *= -1;
}
harmonics += mulitplier * Math.sin(n * frequency);
}
break;
}
case SQUARE: {
if (n % 2 === 1) {
multiplier = 1 / n;
harmonics += multiplier * Math.sin(n * frequency);
}
break;
}
}
}
// smooth the result and return
return this.smoothingFilter.process(harmonics);
};
};
// Create a motion wave by summing pre-calculated harmonics (Fourier synthesis)
HarmonicsFilter = function(magnitudes, phaseAngles) {
this.magnitudes = magnitudes;
this.phaseAngles = phaseAngles;
this.calculate = function(twoPiFT) {
var harmonics = 0;
var numHarmonics = magnitudes.length;
for (var n = 0; n < numHarmonics; n++) {
harmonics += this.magnitudes[n] * Math.cos(n * twoPiFT - this.phaseAngles[n]);
}
return harmonics;
};
};
// the main filter object literal
filter = (function() {
const HALF_CYCLE = 180;
// Bezier private variables
var _C1 = {x:0, y:0};
var _C4 = {x:1, y:1};
// Bezier private functions
function _B1(t) { return t * t * t };
function _B2(t) { return 3 * t * t * (1 - t) };
function _B3(t) { return 3 * t * (1 - t) * (1 - t) };
function _B4(t) { return (1 - t) * (1 - t) * (1 - t) };
return {
// helper methods
degToRad: function(degrees) {
var convertedValue = degrees * Math.PI / HALF_CYCLE;
return convertedValue;
},
radToDeg: function(radians) {
var convertedValue = radians * HALF_CYCLE / Math.PI;
return convertedValue;
},
// these filters need instantiating, as they hold arrays of previous values
// simple averaging (LP) filter for damping / smoothing
createAveragingFilter: function(length) {
var newAveragingFilter = new AveragingFilter(length);
return newAveragingFilter;
},
// provides LP filtering with improved frequency / phase response
createButterworthFilter: function() {
var newButterworthFilter = new ButterworthFilter();
return newButterworthFilter;
},
// generates sawtooth, triangle or square waves using harmonics
createWaveSynth: function(waveShape, numHarmonics, smoothing) {
var newWaveSynth = new WaveSynth(waveShape, numHarmonics, smoothing);
return newWaveSynth;
},
// generates arbitrary waveforms using pre-calculated harmonics
createHarmonicsFilter: function(magnitudes, phaseAngles) {
var newHarmonicsFilter = new HarmonicsFilter(magnitudes, phaseAngles);
return newHarmonicsFilter;
},
// the following filters do not need separate instances, as they hold no previous values
// Bezier response curve shaping for more natural transitions
bezier: function(input, C2, C3) {
// based on script by (www.pupius.net) http://13thparallel.com/archive/bezier-curves/
input = 1 - input;
return _C1.y * _B1(input) + C2.y * _B2(input) + C3.y * _B3(input) + _C4.y * _B4(input);
},
// simple clipping filter (special case for hips y-axis skeleton offset for walk animation)
clipTrough: function(inputValue, peak, strength) {
var outputValue = inputValue * strength;
if (outputValue < -peak) {
outputValue = -peak;
}
return outputValue;
}
}
})();
|
javascript
| 21 | 0.555649 | 112 | 33.8 | 205 |
starcoderdata
|
// Copyright (c) 2022 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package depgraph
type itemIterator struct {
graph *graph
curIdx int
begin, end int // [begin, end)
}
type itemListIterator struct {
items []ItemWithState
curIdx int
}
type subGraphIterator struct {
// graph can be nil, then it returns empty content.
graph *graph
curIdx int
}
type edgeIterator struct {
edges edges
curIdx int
}
// Item returns the current Item from the iterator.
func (iter *itemIterator) Item() (Item, ItemState) {
totalLen := iter.end - iter.begin
if iter.curIdx >= totalLen {
return nil, nil
}
node := iter.graph.sortedNodes[iter.begin+iter.curIdx]
return node.item, node.state
}
// Next advances the iterator and returns whether the next call
// to the Item() method will return non-nil values.
func (iter *itemIterator) Next() bool {
iter.curIdx++
totalLen := iter.end - iter.begin
return iter.curIdx < totalLen
}
// Len returns the number of items remaining in the iterator.
func (iter *itemIterator) Len() int {
totalLen := iter.end - iter.begin
if iter.curIdx >= totalLen {
return 0
}
return totalLen - (iter.curIdx + 1)
}
// Reset returns the iterator to its start position.
func (iter *itemIterator) Reset() {
iter.curIdx = -1
}
// Item returns the current Item from the iterator.
func (iter *itemListIterator) Item() (Item, ItemState) {
if iter.curIdx >= len(iter.items) {
return nil, nil
}
iws := iter.items[iter.curIdx]
return iws.Item, iws.State
}
// Next advances the iterator and returns whether the next call
// to the Item() method will return non-nil values.
func (iter *itemListIterator) Next() bool {
iter.curIdx++
return iter.curIdx < len(iter.items)
}
// Len returns the number of items remaining in the iterator.
func (iter *itemListIterator) Len() int {
if iter.curIdx >= len(iter.items) {
return 0
}
return len(iter.items) - (iter.curIdx + 1)
}
// Reset returns the iterator to its start position.
func (iter *itemListIterator) Reset() {
iter.curIdx = -1
}
// SubGraph returns the current subgraph from the iterator.
func (iter *subGraphIterator) SubGraph() GraphR {
if iter.graph == nil {
return nil
}
if iter.curIdx >= len(iter.graph.subgraphs) {
return nil
}
return iter.graph.subgraphs[iter.curIdx]
}
// Next advances the iterator and returns whether the next call
// to the SubGraph() method will return a non-nil value.
func (iter *subGraphIterator) Next() bool {
if iter.graph == nil {
return false
}
iter.curIdx++
return iter.curIdx < len(iter.graph.subgraphs)
}
// Len returns the number of subgraphs remaining in the iterator.
func (iter *subGraphIterator) Len() int {
if iter.graph == nil {
return 0
}
if iter.curIdx >= len(iter.graph.subgraphs) {
return 0
}
return len(iter.graph.subgraphs) - (iter.curIdx + 1)
}
// Reset returns the iterator to its start position.
func (iter *subGraphIterator) Reset() {
iter.curIdx = -1
}
// Edge returns the current Edge from the iterator.
func (iter *edgeIterator) Edge() Edge {
if iter.curIdx >= len(iter.edges) {
return Edge{}
}
return *iter.edges[iter.curIdx]
}
// Next advances the iterator and returns whether the next call
// to the Edge() method will return a non-nil value.
func (iter *edgeIterator) Next() bool {
iter.curIdx++
return iter.curIdx < len(iter.edges)
}
// Len returns the number of edges remaining in the iterator.
func (iter *edgeIterator) Len() int {
if iter.curIdx >= len(iter.edges) {
return 0
}
return len(iter.edges) - (iter.curIdx + 1)
}
// Reset returns the iterator to its start position.
func (iter *edgeIterator) Reset() {
iter.curIdx = -1
}
|
go
| 10 | 0.707832 | 86 | 23.45098 | 153 |
starcoderdata
|
int change_dir(const char *dir, int set_path_only)
{
static int initialised;
unsigned int len;
if (!initialised) {
initialised = 1;
if (getcwd(curr_dir, sizeof curr_dir - 1) == NULL) {
rsyserr(FERROR, errno, "getcwd()");
exit_cleanup(RERR_FILESELECT);
}
curr_dir_len = strlen(curr_dir);
}
if (!dir) /* this call was probably just to initialize */
return 0;
len = strlen(dir);
if (len == 1 && *dir == '.')
return 1;
if (*dir == '/') {
if (len >= sizeof curr_dir) {
errno = ENAMETOOLONG;
return 0;
}
if (!set_path_only && chdir(dir))
return 0;
memcpy(curr_dir, dir, len + 1);
} else {
if (curr_dir_len + 1 + len >= sizeof curr_dir) {
errno = ENAMETOOLONG;
return 0;
}
curr_dir[curr_dir_len] = '/';
memcpy(curr_dir + curr_dir_len + 1, dir, len + 1);
if (!set_path_only && chdir(curr_dir)) {
curr_dir[curr_dir_len] = '\0';
return 0;
}
}
curr_dir_len = clean_fname(curr_dir, CFN_COLLAPSE_DOT_DOT_DIRS);
if (sanitize_paths) {
if (module_dirlen > curr_dir_len)
module_dirlen = curr_dir_len;
curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
}
if (verbose >= 5 && !set_path_only)
rprintf(FINFO, "[%s] change_dir(%s)\n", who_am_i(), curr_dir);
return 1;
}
|
c
| 12 | 0.5984 | 65 | 21.745455 | 55 |
inline
|
"""
Letter Creation example using Pythons asyncio
This example bypasses the lob Python library and instead uses asyncio
to create letters, attempting to saturate the rate limit. It requires
Python 3.7 or later.
To customize:
* set API_KEY and API_BASE as needed; these may be set in the Python
code or via environment variables
* update getPayload to map an input row to the letter create payload
* update from_address as needed
These customziation points are marked with `TODO` comments in the code.
"""
import asyncio
import csv
import datetime
import functools
import os
import sys
import time
import aiohttp
import lob
# TODO: set your API key
API_KEY = lob.api_key = os.getenv('API_KEY')
API_BASE = lob.api_base = os.getenv('API_BASE', 'https://api.lob.com/v1')
DEBUG = False
SUCCESS_LOG_FIELDS = [
'name',
'id',
'url',
'address_line1',
'address_line2',
'address_city',
'address_state',
'address_zip'
]
ERROR_LOG_FIELDS = ['error', 'status']
WORKERS = 100
def logFiles():
"""Create an output directory for log files and return the filenames.
Returns (success_filename, error_filename)
"""
# create the output directory,
output_dir = os.path.join('.', 'output')
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
try:
output_dir = os.path.join(output_dir, timestamp)
os.mkdir(output_dir)
except Exception as e:
print('Error: ' + str(e))
print('Failed to create output directory. Aborting all sends.')
raise e
# output csv names
success_filename = os.path.join(output_dir, 'success.csv')
errors_filename = os.path.join(output_dir, 'errors.csv')
return (success_filename, errors_filename)
async def logSuccess(successLog, letter):
"""Logs a successful letter send to successLog.
`successLog` is a CSV writer and `letter` is a dict.
"""
successLog.writerow({
'name': letter['to']['name'],
'id': letter['id'],
'url': letter['url'],
'address_line1': letter['to']['address_line1'],
'address_line2': letter['to']['address_line2'],
'address_city': letter['to']['address_city'],
'address_state': letter['to']['address_state'],
'address_zip': letter['to']['address_zip'],
})
sys.stdout.write('.')
sys.stdout.flush()
async def logError(errorLog, resp):
if isinstance(resp, Exception):
errorLog.writerow(
{'error': resp},
)
else:
errorLog.writerow(
{'error': await resp.json(), 'status': resp.status},
)
sys.stdout.write('E')
sys.stdout.flush()
# TODO: customize getPayload based on your input file
def getPayload(row):
"""Return a create letter payload for the inputRow.
inputRow is a dict read from the input CSV.
This *must* return a dict suitable for serializing as a JSON letter
create request.
"""
payload = dict(
description='Bill for ' + row['name'],
metadata=dict(
**row.get('metadata', {}),
),
to={
'name': row['name'],
'address_line1': row['address1'],
'address_line2': row['address2'],
'address_city': row['city'],
'address_zip': row['postcode'],
'address_state': row['state']
},
file=row['file'],
merge_variables={
'date': datetime.datetime.now().strftime("%m/%d/%Y"),
'name': row['name'],
'amount': row['amount']
},
color=True,
)
payload['from'] = row['from_address']
return payload
async def sendWorker(session, queue, getPayload, underRateLimit, successLog, errorLog):
"""asyncio worker for processing letters from the queue.
session is the aiohttp session used to send requests.
queue is an asyncio.Queue, from which letters are read.
getPayload is a function which takes a row from the queue and returns
the create letter payload.
underRateLimit is an asyncio Event object, which is triggered when it's
safe to send.
successLog and errorLog are CSV writers used for logging results.
"""
url = '%s/letters' % API_BASE
# get the first letter to operate on
row = await queue.get()
while True:
# wait until we're under the rate limit
await underRateLimit.wait()
# send the request
payload = None
try:
payload = getPayload(row)
except Exception as e:
await logError(errorLog, e)
if payload is not None:
async with session.post(url, json=payload) as resp:
if resp.status == 200:
# if successful, mark the task done and wait for another letter
letter = await resp.json()
await logSuccess(successLog, letter)
elif resp.status == 429:
# if rate limited, set flag, sleep for delay, clear flag, repeat the loop
resetTime = float(resp.headers.get('X-Rate-Limit-Reset'))
delay = abs(resetTime - time.time())
sys.stdout.write('W')
sys.stdout.flush()
# block work by other workers, wait, and then set the "all clear" flag
underRateLimit.clear()
await asyncio.sleep(delay)
underRateLimit.set()
# continue without fetching another letter to work on
continue
else:
# report an error and mark the task as done
await logError(errorLog, resp)
queue.task_done()
row = await queue.get()
async def send_letters(inputCSV, *, getPayload=getPayload, extraData=None):
extraData = extraData or {}
successes, errors = logFiles()
with open(successes, 'w') as success, \
open(errors, 'w') as error:
# Print mode to screen
mode = API_KEY.split('_')[0]
print('Sending letters in ' + mode.upper() + ' mode.')
# create success and error logs
success_csv = csv.DictWriter(success, fieldnames=SUCCESS_LOG_FIELDS)
errors_csv = csv.DictWriter(error, fieldnames=ERROR_LOG_FIELDS)
success_csv.writeheader()
errors_csv.writeheader()
# create the Event used to signal the rate limit has been reached
underRateLimit = asyncio.Event()
underRateLimit.set()
# create a queue to hold the Tasks for each Letter
letters = asyncio.Queue()
# Create worker tasks to process the queue concurrently
async with aiohttp.ClientSession(
auth=aiohttp.BasicAuth(API_KEY),
) as session:
tasks = []
for i in range(WORKERS):
tasks.append(
asyncio.create_task(
sendWorker(session, letters, getPayload, underRateLimit, success_csv, errors_csv)
)
)
# add the letters to the queue
for letter in inputCSV:
letter.update(extraData)
await letters.put(letter)
# wait for all letters to complete
await letters.join()
# Cancel our worker tasks.
for task in tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
if __name__ == '__main__':
# TODO: Create your from_address
try:
from_address = lob.Address.create(
name='
company='Your Company',
address_line1='123 Test Avenue',
address_line2='STE 456',
address_city='San Francisco',
address_state='CA',
address_zip='94107'
)
except Exception as e:
print('Error: ' + str(e))
print('Failed to create from_address.')
sys.exit(1)
with open('letter.html', 'r') as html_file:
letter_html = html_file.read()
with open(sys.argv[-1], 'r') as inputFile:
# TODO: customize `extraData` if you need additional information to
# generate the create letter payload in `getPayload`
#
# extraData is added to every row from the input CSV, providing a channel
# to pass additional values into getPayload
extraData = dict(
metadata=dict(csv=sys.argv[-1]),
from_address=from_address.id,
file=letter_html,
)
input_csv = csv.DictReader(inputFile)
asyncio.run(send_letters(input_csv, extraData=extraData), debug=DEBUG)
|
python
| 19 | 0.582892 | 105 | 29.077966 | 295 |
starcoderdata
|
def open_file_selector(self):
"""
Open the file selector.
"""
self.file_selector = QtWidgets.QFileDialog(
options=QtWidgets.QFileDialog.DontUseNativeDialog
)
self.file_selector.setFileMode(QtWidgets.QFileDialog.ExistingFile)
authorized_files = [
"All media files (*.png *.jpg *.jpeg *.mp4 *.mov *.wmv *.obj)",
"Images (*.png *.jpg *.jpeg)",
"Video (*.mp4 *.mov *.wmv)",
"3D (*.obj)",
]
self.file_selector.setNameFilters(authorized_files)
self.file_selector.setViewMode(QtWidgets.QFileDialog.Detail)
if self.file_selector.exec_():
selected_file = self.file_selector.selectedFiles()
self.post_path = selected_file[0]
self.update_selector_btn()
|
python
| 10 | 0.575758 | 75 | 40.3 | 20 |
inline
|
using System;
using System.Runtime.Serialization;
using MessageBroker.Events;
namespace MessageBroker.Tests.Events
{
[Serializable]
public sealed class TestIntegrationEvent: IntegrationEvent
{
public TestIntegrationEvent()
{
}
private TestIntegrationEvent(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
|
c#
| 9 | 0.703704 | 108 | 23.055556 | 18 |
starcoderdata
|
import { healthStatus, createDependencyHandler } from '../health.handler';
describe('health check handler', () => {
let request;
let reply;
beforeEach(() => {
request = {
log: jest.fn()
};
reply = jest.fn();
});
describe('server status', () => {
it('should reply status ok', () => {
healthStatus(request, reply);
expect(reply).toHaveBeenCalled();
expect(reply).toHaveBeenCalledTimes(1);
expect(reply).toHaveBeenCalledWith({
status: 'OK'
});
});
});
describe('dependency status', () => {
let connection;
let logger;
beforeEach(() => {
connection = {
authenticate: jest.fn(() => Promise.resolve())
};
logger = {
error: jest.fn()
};
});
it('should reply with the up status of dependencies', async () => {
const dependencyHandler = createDependencyHandler(connection, logger);
await dependencyHandler(request, reply);
expect(reply).toHaveBeenCalled();
expect(reply).toHaveBeenCalledTimes(1);
const response = reply.mock.calls[0][0];
expect(response).toHaveLength(1);
});
it('should log that the dependency is down if down', async () => {
connection = {
authenticate: jest.fn(() => Promise.reject())
};
const dependencyHandler = createDependencyHandler(connection, logger);
await dependencyHandler(request, reply);
expect(reply).toHaveBeenCalled();
expect(reply).toHaveBeenCalledTimes(1);
const response = reply.mock.calls[0][0];
expect(response).toHaveLength(1);
expect(request.log).toHaveBeenCalled();
expect(request.log).toHaveBeenCalledTimes(1);
});
});
});
|
javascript
| 25 | 0.526236 | 82 | 28.58209 | 67 |
starcoderdata
|
import click
import getpass
import sys
from .jeecf import Jeecf
@click.group()
def main():
"""
Jeecf client commandline toooool.
Documents: https://github.com/cgfly/jeecf-cli
"""
@main.command()
def version():
click.echo("0.0.3")
@main.command()
@click.argument("path", required=True)
@click.option("--username", type=click.STRING)
@click.option("--password", type=click.STRING)
def login(path, username, password):
if path:
if not path.startswith("http"):
click.echo("Error:")
sys.exit("The url should starts with http or https...")
if not username:
username = input("username:")
if not password:
password = getpass.getpass("password:")
Jeecf.login(path, username, password)
@main.command()
@click.argument("command", required=False, type=click.Choice(['use']))
@click.argument("name", required=False)
def namespace(command, name):
if command == 'use':
click.echo(Jeecf().set_current_namespace(name))
else:
Jeecf().get_namespace_list()
@main.command()
@click.argument("command", required=False, type=click.Choice(['use']))
@click.argument("name", required=False)
def dbsource(command, name):
if command == 'use':
click.echo(Jeecf().set_current_dbsource(name))
else:
Jeecf().get_dbsource_list()
@main.command()
@click.option("--language", required=False, is_flag=True)
@click.argument("name", required=False, type=click.STRING)
def plugin(language, name):
if language:
Jeecf().get_plugin_language()
elif name:
Jeecf().get_plugin_detail(name)
else:
Jeecf().get_plugin_list()
@main.command()
@click.argument("subcommand", required=False, type=click.Choice(['pull', 'push']))
@click.argument("name", required=False)
def template(subcommand, name):
if subcommand == 'pull':
Jeecf().pull_template(name)
elif subcommand == 'push':
Jeecf().push_template(
name,
field=click.prompt('field', default=''),
language=click.prompt('language', default=''),
version=click.prompt('version', default=''),
tags=click.prompt('tags', default=''),
namespace=click.prompt('namespace', default=''),
description=click.prompt('description', default=''),
wiki_uri=click.prompt('wiki_uri', default=''),
)
else:
Jeecf().get_template_list()
@main.command()
@click.argument("name", required=True)
@click.option('--table_name',required=False, type=click.STRING)
@click.option('--namespace',required=False, type=click.STRING)
@click.option('--dbsource',required=False, type=click.STRING)
@click.option('--template',required=False, type=click.STRING)
def gen(name, table_name, namespace, dbsource, template):
Jeecf().gen_code(name, table_name, namespace, dbsource, template)
@main.command()
def logout():
Jeecf().logout()
|
python
| 15 | 0.645205 | 82 | 27.375 | 104 |
starcoderdata
|
const fs = require('fs')
const {
Template
} = require('./template.js')
const {
Data
} = require('./data.js')
const {
Parser
} = require('json2csv')
let appInfo = require('../package.json')
let commandLineArgs = require("command-line-args")
const commandLineUsage = require('command-line-usage')
class Main {
constructor() {
let log4js = require('log4js')
log4js.configure({
appenders: {
console: {
type: 'console'
}
},
categories: {
default: {
appenders: ['console'],
level: 'info'
}
}
})
this.log = log4js.getLogger()
this.optionDefinitions = [{
name: 'input',
alias: 'i',
type: String,
description: `The location of the imput spreadsheet that contains the data that will be applied to the template in order to build the jira import csv. Example {bold -i ./test/data.xlsx}`,
typeLabel: '{underline input}'
},
{
name: 'template',
alias: 't',
type: String,
description: 'The location of the template xlsx file that defines the structure of the jira items to create. Example {bold -t ./test/template.xlsx}',
typeLabel: '{underline template}'
},
{
name: 'output',
alias: 'o',
type: String,
description: 'The name of the file where you want the output CSV written. Example {bold -o ./test/output.csv}',
typeLabel: '{underline output}'
},
{
name: 'help',
alias: 'h',
type: Boolean,
description: '(optional) Prints the help for the tool',
typeLabel: '',
defaultValue: false
}
]
let cmd = 'xlsTemplate2Jira'
if (process.platform == 'darwin') {
cmd = './xlsTemplate2Jira'
}
this.usage = [{
header: `${appInfo.name} v${appInfo.version} by ${appInfo.author}`,
content: appInfo.description
}, {
header: 'Options',
optionList: this.optionDefinitions
},
{
header: 'Example',
content: `${cmd} -i ./test/data.xlsx -t ./test/template.xlsx -o ./test/output.csv`
}
]
this.validHeader = [this.usage[0]]
this.options = commandLineArgs(this.optionDefinitions)
this.jiraMax = 800
}
isValid() {
let isValid = false
if ((this.options.input != undefined) && (this.options.output != undefined) && (this.options.template != undefined)) {
isValid = true
this.templateFile = this.options.template
this.sourceFile = this.options.input
this.outputFile = this.options.output
}
return isValid
}
syntax() {
const usage = commandLineUsage(this.usage)
console.log(usage)
}
printHeader() {
const usage = commandLineUsage(this.validHeader)
console.log(usage)
}
processRequest() {
return new Promise((resolve, reject) => {
let output = []
this.data = new Data(this.log, this.sourceFile)
this.template = new Template(this.log, this.templateFile)
this.log.info(`loading template ${this.options.template}...`)
this.template.load()
this.log.info(`loading input data ${this.options.input}...`)
this.data.load()
this.log.info(`combining information...`)
let rows = this.data.getRows()
rows.forEach(row => {
this.template.build(row, output)
})
this.log.info(`writing output...`)
let segements = this.splitOutput(output)
let promises = []
segements.forEach(seg => {
promises.push(this.writeCSV(seg))
})
Promise.all(promises).then(data => {
resolve(true)
}).catch(err => {
reject(err)
})
})
}
splitOutput(outputList) {
let rc = []
// if can do in one pass (i.e., less than max then use list)
if (outputList.length < this.jiraMax) {
rc.push({
id: '',
list: outputList
})
} else {
let id = 0
let done = false
let list = outputList
while (!done) {
id++
let splitId = this.findSplit(list)
if (splitId == -1) {
rc.push({
"id": `-part-${id}`,
"list": list
})
done = true
} else {
rc.push({
"id": `-part-${id}`,
"list": list.slice(0, splitId)
})
list = list.slice(splitId);
}
}
}
return rc
}
findSplit(list) {
let id = -1
if (list.length > this.jiraMax) {
for (let i = this.jiraMax; i > 0 && id == -1; i--) {
if (list[i]["Issue Type"] == "Epic") {
id = i
}
}
}
return id
}
buildCSVFileName(filePostFix) {
let rc = this.options.output
if (filePostFix.length > 0) {
let idx = rc.toLowerCase().lastIndexOf(".csv")
rc = `${rc.substring(0,idx)}${filePostFix}.csv`
}
return rc
}
writeCSV(seg) {
return new Promise((resolve, reject) => {
const file = this.buildCSVFileName(seg.id)
const json2csvParser = new Parser()
const csv = json2csvParser.parse(seg.list)
fs.writeFile(file, csv, 'UTF-8', (err) => {
if (err) {
this.log.error(`failed writing ${file}`, err)
reject(err)
} else {
this.log.info(` ${file}`)
resolve(true)
}
})
})
}
run() {
if (this.isValid()) {
this.printHeader()
this.processRequest().then(() => {
this.log.info('done')
}).catch(() => {
this.log.error('errors detected')
})
} else {
this.syntax()
}
}
}
module.exports = {
Main
}
|
javascript
| 23 | 0.541446 | 196 | 23.656522 | 230 |
starcoderdata
|
/*
* Copyright (c) 2019. The Maker Playground Authors.
*
* 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
*
* https://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 io.makerplayground.ui.canvas;
import io.makerplayground.project.*;
import io.makerplayground.ui.canvas.node.BeginViewModel;
import io.makerplayground.ui.canvas.node.ConditionViewModel;
import io.makerplayground.ui.canvas.node.DelayViewModel;
import io.makerplayground.ui.canvas.node.SceneViewModel;
import io.makerplayground.ui.canvas.helper.DynamicViewModelCreator;
/**
*
* Created by tanyagorn on 6/13/2017.
*/
public class CanvasViewModel {
protected final Project project;
private final DynamicViewModelCreator<Begin, BeginViewModel> beginViewModel;
private final DynamicViewModelCreator<Scene, SceneViewModel> SceneViewModel;
private final DynamicViewModelCreator<Condition, ConditionViewModel> conditionViewModel;
private final DynamicViewModelCreator<Delay, DelayViewModel> delayViewModel;
private final DynamicViewModelCreator<Line, LineViewModel> lineViewModel;
public CanvasViewModel(Project project) {
this.project = project;
this.beginViewModel = new DynamicViewModelCreator<>(project.getBegin(), begin -> new BeginViewModel(begin, project));
this.SceneViewModel = new DynamicViewModelCreator<>(project.getUnmodifiableScene(), scene -> new SceneViewModel(scene, project));
this.conditionViewModel = new DynamicViewModelCreator<>(project.getUnmodifiableCondition(), condition -> new ConditionViewModel(condition, project));
this.delayViewModel = new DynamicViewModelCreator<>(project.getUnmodifiableDelay(), delay -> new DelayViewModel(delay, project));
this.lineViewModel = new DynamicViewModelCreator<>(project.getUnmodifiableLine(), LineViewModel::new);
}
public void connect(NodeElement nodeElement1, NodeElement nodeElement2) {
project.addLine(nodeElement1, nodeElement2);
}
public DynamicViewModelCreator<Begin, BeginViewModel> getBeginViewModelCreator() {
return beginViewModel;
}
public DynamicViewModelCreator<Line, LineViewModel> getLineViewModelCreator() {
return lineViewModel;
}
public DynamicViewModelCreator<Condition, ConditionViewModel> getConditionViewModelCreator() {
return conditionViewModel;
}
public DynamicViewModelCreator<Delay, DelayViewModel> getDelayViewModelCreator() {
return delayViewModel;
}
public DynamicViewModelCreator<Scene, SceneViewModel> getSceneViewModelCreator() {
return SceneViewModel;
}
public Project getProject() {
return project;
}
}
|
java
| 12 | 0.763366 | 157 | 41.146667 | 75 |
starcoderdata
|
#include "ast.h"
#include "parser.h"
#include "runner.h"
#include
#include
void run(const std::string &file_name) {
std::ifstream ifs(file_name);
if (!ifs) {
std::cerr << "Cannot open " << file_name << std::endl;
return;
}
std::string line;
std::string code;
while (getline(ifs, line)) {
const size_t n = line.length() - 1;
if (line[n] != '\n' && line[n] != ';')
line += ";";
code += line;
}
std::unique_ptr lexer = std::make_unique
Parser parser(std::move(lexer));
std::vector<Ast *> astvec = parser.parse();
Runner runner(astvec);
runner.run();
}
int main(int argc, char **argv) {
if (argc == 2) {
const std::string file_name = std::string(argv[1]);
run(file_name);
}
}
|
c++
| 11 | 0.539928 | 65 | 24.424242 | 33 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.