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 |
---|---|---|---|---|---|---|---|
package com.ruchi.roster;
import android.content.Intent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by ruchi on 9/24/2016.
*/
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String NOTE = "notes";
//public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.US);
private String mTitle = new String();
private String mNotes = new String();
// private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, String notes, Status status, Date date) {
this.mTitle = title;
this.mNotes = notes;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mNotes = intent.getStringExtra(ToDoItem.NOTE);
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public String getNotes() {
return mNotes;
}
public void setNotes(String notes) {
mNotes = notes;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public static void packageIntent(Intent intent, String title,
String note, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.NOTE, note);
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mNotes + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Notes:" + mNotes
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate) +"\n";
}
}
|
java
| 18 | 0.611548 | 80 | 24.232759 | 116 |
starcoderdata
|
package entities
type Mech struct {
base CharacterBase
}
func (m Mech) Display() string {
return m.base.Display()
}
func (m Mech) Name() string {
return m.base.Name
}
func (m Mech) Stats() Stats {
return m.base.Stats
}
func (Mech) Tribe() CharacterTribe {
return MechTribe
}
func (m Mech) Resource() GameResource {
return m.base.Resource
}
func NewMech() Character {
c := Mech{}
c.base.Name = "MechName"
c.base.Tribe = MechTribe
c.base.Stats = mechBaseStats()
c.base.Resource = GenerateResource(ResCharacter, "resource-character-mech")
return c
}
func mechBaseStats() Stats {
return Stats {
Health : 100,
AttackDamage : 50,
AttackSpeed : 1.0,
MovementSpeed : 40,
CritPercentage : 0.0,
}
}
func NewGeneticMech() Character {
character := NewMech()
mech, ok := character.(Mech)
if !ok {
panic("We expected a mech")
}
mech.base.Stats.Health += uint16(randomInt16(-10, 10))
mech.base.Stats.AttackDamage += uint16(randomInt16(-10, 10))
mech.base.Stats.AttackSpeed += randomFloat32(-0.3, 0.3)
mech.base.Stats.MovementSpeed += uint16(randomInt16(-10, 10))
return &mech
}
|
go
| 10 | 0.691269 | 76 | 17.516667 | 60 |
starcoderdata
|
package com.osaigbovo.udacity.popularmovies.di;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.osaigbovo.udacity.popularmovies.ui.moviedetails.MovieDetailViewModel;
import com.osaigbovo.udacity.popularmovies.ui.movieslist.MoviesListViewModel;
import com.osaigbovo.udacity.popularmovies.ui.search.SearchViewModel;
import com.osaigbovo.udacity.popularmovies.viewmodel.MoviesViewModelFactory;
import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;
/*
* @author
* */
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MoviesListViewModel.class)
abstract ViewModel bindMoviesListViewModel(MoviesListViewModel moviesListViewModel);
@Binds
@IntoMap
@ViewModelKey(MovieDetailViewModel.class)
abstract ViewModel bindMovieDetailViewModel(MovieDetailViewModel movieDetailViewModel);
@Binds
@IntoMap
@ViewModelKey(SearchViewModel.class)
abstract ViewModel bindSearchViewModel(SearchViewModel searchViewModel);
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(MoviesViewModelFactory factory);
}
|
java
| 8 | 0.815676 | 92 | 29.552632 | 38 |
starcoderdata
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal static class TodoCommentOptions
{
public const string OptionName = "TaskList/Tokens";
[ExportOption]
public static readonly Option TokenList = new Option "Token List", defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
}
}
|
c#
| 13 | 0.748288 | 169 | 40.714286 | 14 |
starcoderdata
|
window.App = function () {
return {
context: {
dependencies: {
default: {
async: [
{
url: 'build/todo.min.js',
instances: {
jquery: '$',
doT: 'doT',
storagejs: 'storage'
}
}
]
},
dev: {
async: [
{
url: '//cdn.rawgit.com/lcavadas/jquery/2.1.3/dist/jquery.min.js',
instances: {
jquery: '$'
}
},
{
url: '//cdn.rawgit.com/lcavadas/doT/1.0.1/doT.js',
instances: {
doT: 'doT'
}
},
{
url: '//cdn.rawgit.com/lcavadas/Storage.js/1.0.0/build/storage.js',
instances: {
storagejs: 'storage'
}
},
'//cdn.rawgit.com/lcavadas/arenite/1.1.0/js/extensions/bus/bus.js',
'//cdn.rawgit.com/lcavadas/arenite/1.1.0/js/extensions/storage/storage.js',
'//cdn.rawgit.com/lcavadas/arenite/1.1.0/js/extensions/template/dot.js',
'//cdn.rawgit.com/lcavadas/arenite/1.1.0/js/extensions/router/router.js',
'js/model.js',
'js/list/list.js',
'js/list/listView.js',
'js/list/toolbarView.js',
'js/todo/todo.js',
'js/todo/todoView.js'
]
}
},
extensions: {
bus: {
namespace: 'Arenite.Bus'
},
templates: {
namespace: 'Arenite.Templates',
args: [
{ref: 'arenite'},
{ref: 'doT'}
],
init: {
wait: true,
func: 'add',
args: [{
value: ['templates/template.html']
}]
}
},
storage: {
namespace: 'Arenite.Storage',
args: [
{ref: 'arenite'},
{ref: 'storagejs'}
],
init: 'init'
},
router: {
namespace: 'Arenite.Router',
args: [{ref: 'arenite'}],
init: {
func: 'init',
args: [
{
value: {
'/': [{
instance: 'arenite',
func: 'bus.publish',
args: [
{value: 'filter-change'},
{value: 'all'}
]
}],
'/active': [{
instance: 'arenite',
func: 'bus.publish',
args: [
{value: 'filter-change'},
{value: 'active'}
]
}],
'/completed': [{
instance: 'arenite',
func: 'bus.publish',
args: [
{value: 'filter-change'},
{value: 'completed'}
]
}]
}
},
{value: true}]
}
}
},
start: [
{
instance: 'model',
func: 'load'
}
],
instances: {
model: {
namespace: 'App.Model',
args: [
{ref: 'arenite'}
]
},
list: {
namespace: 'App.List',
init:'init',
args: [
{ref: 'arenite'},
{ref: 'model'},
{
instance: {
namespace: 'App.ListView',
args: [
{ref: 'arenite'},
{ref: 'jquery'}
],
init: 'init'
}
},
{
instance: {
namespace: 'App.ToolbarView',
args: [
{ref: 'arenite'},
{ref: 'jquery'}
],
init: 'init'
}
}
]
},
todo: {
factory: true,
namespace: 'App.Todo',
args: [
{ref: 'arenite'},
{ref: 'model'},
{
instance: {
namespace: 'App.TodoView',
args: [
{ref: 'arenite'},
{ref: 'jquery'}
]
}
}
]
}
}
}
};
};
|
javascript
| 28 | 0.314077 | 87 | 24.670455 | 176 |
starcoderdata
|
@Test
@Transactional
public void getAllTelegramBotsByTelegramBotNameIsEqualToSomething() throws Exception {
// Initialize the database
telegramBotRepository.saveAndFlush(telegramBot);
// Get all the telegramBotList where telegramBotName equals to DEFAULT_TELEGRAM_BOT_NAME
defaultTelegramBotShouldBeFound("telegramBotName.equals=" + DEFAULT_TELEGRAM_BOT_NAME);
// Get all the telegramBotList where telegramBotName equals to UPDATED_TELEGRAM_BOT_NAME
defaultTelegramBotShouldNotBeFound("telegramBotName.equals=" + UPDATED_TELEGRAM_BOT_NAME);
}
|
java
| 8 | 0.759934 | 98 | 49.416667 | 12 |
inline
|
import gzip
import httpretty
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
from tests.base_test import BaseTest
class GzipSupportTest(BaseTest):
def setUp(self) -> None:
super(GzipSupportTest, self).setUp()
httpretty.enable()
httpretty.reset()
def tearDown(self) -> None:
self.client.close()
httpretty.disable()
def test_gzip_disabled(self):
query_response = \
"#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string\n" \
"#group,false,false,false,false,false,false,false,false,false,true\n#default,_result,,,,,,,,\n" \
",result,table,_start,_stop,_time,_value,_field,_measurement,host\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,121,free,mem,A\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,122,free,mem,A\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,123,free,mem,A\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,124,free,mem,A\n"
httpretty.register_uri(httpretty.GET, uri="http://localhost/api/v2/me", status=200, body="{\"name\":\"Tom\"}",
adding_headers={'Content-Type': 'application/json'})
httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=204)
httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/query", status=200, body=query_response)
self.client = InfluxDBClient("http://localhost", "my-token", org="my-org", enable_gzip=False)
_user = self.client.users_api().me()
self.assertEqual("Tom", _user._name)
_response = self.client.write_api(write_options=SYNCHRONOUS) \
.write("my-bucket", "my-org", "h2o_feet,location=coyote_creek water_level=1 1")
self.assertEqual(None, _response)
_tables = self.client.query_api() \
.query('from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()', "my-org")
self.assertEqual(1, len(_tables))
self.assertEqual(4, len(_tables[0].records))
self.assertEqual(121, _tables[0].records[0].get_value())
self.assertEqual(122, _tables[0].records[1].get_value())
self.assertEqual(123, _tables[0].records[2].get_value())
self.assertEqual(124, _tables[0].records[3].get_value())
_requests = httpretty.httpretty.latest_requests
self.assertEqual(3, len(_requests))
# Unsupported
self.assertEqual("/api/v2/me", _requests[0].path)
self.assertEqual(None, _requests[0].headers['Content-Encoding'])
self.assertEqual("identity", _requests[0].headers['Accept-Encoding'])
# Write
self.assertEqual("/api/v2/write?org=my-org&bucket=my-bucket&precision=ns", _requests[1].path)
self.assertEqual("identity", _requests[1].headers['Content-Encoding'])
self.assertEqual("identity", _requests[1].headers['Accept-Encoding'])
self.assertEqual("h2o_feet,location=coyote_creek water_level=1 1", _requests[1].parsed_body)
# Query
self.assertEqual("/api/v2/query?org=my-org", _requests[2].path)
self.assertEqual(None, _requests[2].headers['Content-Encoding'])
self.assertEqual("identity", _requests[2].headers['Accept-Encoding'])
self.assertTrue('from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()' in str(
_requests[2].parsed_body))
def test_gzip_enabled(self):
query_response = \
"#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string\n" \
"#group,false,false,false,false,false,false,false,false,false,true\n#default,_result,,,,,,,,\n" \
",result,table,_start,_stop,_time,_value,_field,_measurement,host\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,121,free,mem,A\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,122,free,mem,A\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,123,free,mem,A\n" \
",,0,1970-01-01T00:00:10Z,1970-01-01T00:00:20Z,1970-01-01T00:00:10Z,124,free,mem,A\n"
httpretty.register_uri(httpretty.GET, uri="http://localhost/api/v2/me", status=200, body="{\"name\":\"Tom\"}",
adding_headers={'Content-Type': 'application/json'})
httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=204)
httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/query", status=200,
body=gzip.compress(bytes(query_response, "utf-8")),
adding_headers={'Content-Encoding': 'gzip'})
self.client = InfluxDBClient("http://localhost", "my-token", org="my-org", enable_gzip=True)
_user = self.client.users_api().me()
self.assertEqual("Tom", _user._name)
_response = self.client.write_api(write_options=SYNCHRONOUS) \
.write("my-bucket", "my-org", "h2o_feet,location=coyote_creek water_level=1 1")
self.assertEqual(None, _response)
_tables = self.client.query_api() \
.query('from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()', "my-org")
self.assertEqual(1, len(_tables))
self.assertEqual(4, len(_tables[0].records))
self.assertEqual(121, _tables[0].records[0].get_value())
self.assertEqual(122, _tables[0].records[1].get_value())
self.assertEqual(123, _tables[0].records[2].get_value())
self.assertEqual(124, _tables[0].records[3].get_value())
_requests = httpretty.httpretty.latest_requests
self.assertEqual(3, len(_requests))
# Unsupported
self.assertEqual("/api/v2/me", _requests[0].path)
self.assertEqual(None, _requests[0].headers['Content-Encoding'])
self.assertEqual("identity", _requests[0].headers['Accept-Encoding'])
# Write
self.assertEqual("/api/v2/write?org=my-org&bucket=my-bucket&precision=ns", _requests[1].path)
self.assertEqual("gzip", _requests[1].headers['Content-Encoding'])
self.assertEqual("identity", _requests[1].headers['Accept-Encoding'])
self.assertNotEqual("h2o_feet,location=coyote_creek water_level=1 1", _requests[1].parsed_body)
# Query
self.assertEqual("/api/v2/query?org=my-org", _requests[2].path)
self.assertEqual(None, _requests[2].headers['Content-Encoding'])
self.assertEqual("gzip", _requests[2].headers['Accept-Encoding'])
self.assertTrue('from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()' in str(
_requests[2].parsed_body))
def test_write_query_gzip(self):
httpretty.disable()
self.client = InfluxDBClient(self.host, token=" org="my-org", debug=False,
enable_gzip=True)
self.api_client = self.client.api_client
self.buckets_client = self.client.buckets_api()
self.query_client = self.client.query_api()
self.org = "my-org"
self.my_organization = self.find_my_org()
_bucket = self.create_test_bucket()
self.client.write_api(write_options=SYNCHRONOUS) \
.write(_bucket.name, self.org, "h2o_feet,location=coyote_creek water_level=111 1")
_result = self.query_client.query(
f"from(bucket:\"{_bucket.name}\") |> range(start: 1970-01-01T00:00:00.000000001Z)", self.org)
self.assertEqual(len(_result), 1)
self.assertEqual(_result[0].records[0].get_measurement(), "h2o_feet")
self.assertEqual(_result[0].records[0].get_value(), 111.0)
self.assertEqual(_result[0].records[0].get_field(), "water_level")
|
python
| 14 | 0.629953 | 118 | 53.598639 | 147 |
starcoderdata
|
private void addFolderToList(List<String> pathList, IFolder folder) {
// use a File instead of the IFolder API to ignore workspace refresh issue.
File testFile = new File(folder.getLocation().toOSString());
if (testFile.isDirectory()) {
pathList.add(testFile.getAbsolutePath());
}
}
|
java
| 10 | 0.657576 | 83 | 46.285714 | 7 |
inline
|
/*
* $Id: Destroy.c,v 1.15 1997-05-05 21:45:12 boote Exp $
*/
/************************************************************************
* *
* Copyright (C) 1992 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
************************************************************************/
/*
* File: Destroy.c
*
* Author:
* National Center for Atmospheric Research
* PO 3000, Boulder, Colorado
*
* Date: Fri Oct 23 10:53:17 MDT 1992
*
* Description: This file contains all the functions neccessary
* to support the Destroy methode of the hlu's.
* Design documentation for this module is
* NhlDOCREF(/design/hlu/Destroy.html,here).
*/
#include
#include
#include
/*
* Function: CallDestroy
*
* Description: This function is used to call the destroy methode's of the
* given function. It is a sub-to-superclass chained methode.
*
* In Args:
* NhlLayer l, NhlLayer to destroy
* NhlClass lc class or superclass of l
*
* Out Args:
*
* Scope: static
* Returns: NhlErrorTypes
* Side Effect:
*/
static NhlErrorTypes
CallDestroy
#if NhlNeedProto
(
NhlLayer l, /* NhlLayer to destroy */
NhlClass lc /* class or superclass of l */
)
#else
(l,lc)
NhlLayer l; /* NhlLayer to destroy */
NhlClass lc; /* class or superclass of l */
#endif
{
NhlErrorTypes scret = NhlNOERROR;
NhlErrorTypes lret = NhlNOERROR;
if(lc->base_class.layer_destroy != NULL){
lret = (*(lc->base_class.layer_destroy))(l);
}
if(lc->base_class.superclass != NULL){
scret = CallDestroy(l,lc->base_class.superclass);
}
return(MIN(scret,lret));
}
/*
* Function: NhlDestroy
*
* Description: This function is used to free the memory associated with
* an hlu object. It calls the destroy method of the
* object so the object can free all of it's ansilary data
* and then this function removes that object from the
* internal list of objects and then actually free's the
* instance record itself.
*
* In Args:
* int pid id associated with the object to delete
*
* Out Args:
*
* Scope: Global Public
* Returns: NhlErrorTypes
* Side Effect:
*/
NhlDOCTAG(NhlDestroy)
NhlErrorTypes
NhlDestroy
#if NhlNeedProto
(
int pid /* id associated with the object to delete */
)
#else
(pid)
int pid; /* id associated with the object to delete */
#endif
{
NhlErrorTypes ret, lret;
NhlLayer l = _NhlGetLayer(pid);
NhlArgVal cbdata,dummy;
if(l == NULL){
NhlPError(NhlFATAL,NhlEUNKNOWN,"Unable to Destroy (Bad PID#%d)",
pid);
return NhlFATAL;
}
if(l->base.being_destroyed)
return NhlNOERROR;
l->base.being_destroyed = True;
NhlINITVAR(dummy);
NhlINITVAR(cbdata);
cbdata.ptrval = l;
_NhlCallObjCallbacks(l,_NhlCBobjDestroy,dummy,cbdata);
if(_NhlIsWorkstation(l) ) {
_NhlCloseWorkstation(l);
}
ret = CallDestroy(l,l->base.layer_class);
/*
* remove this object from it's parents all_children list
*/
_NhlBaseRemoveChild(l);
lret = _NhlRemoveLayer(l);
(void)NhlFree(l);
return MIN(ret,lret);
}
/*
* Function: nhlpfdestroy
*
* Description: Fortran called destroy func
*
* In Args:
*
* Out Args:
*
* Scope:
* Returns:
* Side Effect:
*/
void
_NHLCALLF(nhlpfdestroy,NHLPFDESTROY)
#if NhlNeedProto
(
int *id_obj,
int *err_ret
)
#else
(id_obj,err_ret)
int *id_obj;
int *err_ret;
#endif
{
*err_ret = NhlDestroy(*id_obj);
}
/*
* Function: _NhlDestroyChild
*
* Description: This function is used from within one of a layer's methods
* to remove a child layer that currently exists within it.
* It destroy's the child and remove's it from the layer's
* children list.
*
* In Args:
* int pid, pid of layer to destroy
* NhlLayer parent parent of layer to destroy
*
* Out Args:
*
* Scope: Global layer writer
* Returns: NhlErrorTypes
* Side Effect:
*/
NhlDOCTAG(_NhlDestroyChild)
NhlErrorTypes
_NhlDestroyChild
#if NhlNeedProto
(
int pid, /* pid of layer to destroy */
NhlLayer parent /* parent of layer to destroy */
)
#else
(pid,parent)
int pid; /* pid of layer to destroy */
NhlLayer parent; /* parent of layer to destroy */
#endif
{
NhlErrorTypes ret=NhlNOERROR;
_NhlChildList *tchldnodeptr=NULL;
_NhlChildList tchldnode=NULL;
NhlBoolean found=False;
/*
* Not a valid function to call if parent is an ObjNhlLayer
*/
if(_NhlIsObj(parent)){
NhlPError(NhlFATAL,NhlEUNKNOWN,
"_NhlDestroyChild:parent has no children");
return NhlFATAL;
}
ret = NhlDestroy(pid);
tchldnodeptr = &parent->base.children;
while(*tchldnodeptr != NULL){
if((*tchldnodeptr)->pid == pid){
found = True;
tchldnode = *tchldnodeptr;
*tchldnodeptr = (*tchldnodeptr)->next;
(void)NhlFree(tchldnode);
break;
}
tchldnodeptr = &(*tchldnodeptr)->next;
}
if(!found){
NHLPERROR((NhlFATAL,NhlEUNKNOWN,
"Unable to remove pid#%d from internal table",pid));
return NhlFATAL;
}
return ret;
}
|
c
| 13 | 0.65691 | 74 | 19.752066 | 242 |
starcoderdata
|
@Override
public void onDestroy() {
Log.i(TAG, "MBE: service destroyed");
// There will be no any events from streamer after stop
// We should do it before destroying other stuff
streamer.stop();
cancelStateCheck();
cancelCallTimeout();
dismissCallNotification();
stopRingtone();
unlockWifi();
taskWakeLock.release();
callWakeLock.release();
stopForeground(true);
super.onDestroy();
}
|
java
| 7 | 0.585657 | 63 | 21.863636 | 22 |
inline
|
<?php
namespace PhpRest\Entity\Annotation;
use PhpRest\Entity\Entity;
use PhpRest\Annotation\AnnotationTag;
use PhpRest\Exception\BadCodeException;
class VarHandler
{
/**
* @param Entity $entity
* @param AnnotationTag $ann
*/
public function __invoke(Entity $entity, AnnotationTag $ann)
{
$target = $ann->parent->name;
$property = $entity->getProperty($target);
if ($property === false) { return; }
// 判断实体类属性是否嵌套实体类
$type = $ann->description;
if (strpos($type, '\\') !== false || preg_match("/^[A-Z]{1}$/", $type[0])) {
$entityClassPath = $type;
$type = 'Entity';
if (substr($entityClassPath, -2) === '[]') {
$entityClassPath = substr($entityClassPath, 0, -2);
$type = 'Entity[]';
}
if (strpos($entityClassPath, '\\') === false) {
// 如果没写全命名空间,需要通过反射取得全命名空间
$entityClassPath = \PhpRest\Utils\ReflectionHelper::resolveFromReflector($entity->classPath, $entityClassPath);
}
class_exists($entityClassPath) or \PhpRest\abort(new BadCodeException("{$entity->classPath} 属性 {$ann->name} 指定的实体类 {$entityClassPath} 不存在"));
$property->type = [$type, $entityClassPath];
} else {
$property->type = [$type, ''];
$property->validation = \PhpRest\Validator\Validator::ruleCast($type);
}
}
}
|
php
| 18 | 0.564171 | 153 | 34.642857 | 42 |
starcoderdata
|
static public string AusgabeWitworthflankendurchmesser(string[,] Witworth, double durchmessereingabe)
{
string durchmesserWW = "0";
for (int jj = 0; jj <= 7; jj++) // durchsuchen der Tabelle nach dem richtigen Durchmesser
{
double M = Convert.ToDouble(Witworth[jj, 1]); //umwandeln der Strings in der Tabelle in double
if (durchmessereingabe == M) // Vergleich ob in dem Tabellenfeld der gleiche Wert steht wie in der Eingabe
{
durchmesserWW = Witworth[jj, 5]; // Wert aus der Tabelle wird Gangzahl übergeben
}
}
return durchmesserWW;
}
|
c#
| 16 | 0.58226 | 122 | 42.75 | 16 |
inline
|
package com.grasea.grandroid.ble.controller;
import android.bluetooth.BluetoothDevice;
import com.grasea.grandroid.ble.BluetoothLeService;
/**
* Created by on 2016/5/13.
*/
public interface BleController {
void onGattServicesDiscovered();
void onGattServicesConnected();
void onGattServicesDisconnected();
boolean connect();
void disconnect();
boolean send(String serviceUUID, String channelUUID, String protocol);
boolean send(String serviceUUID, String channelUUID, byte[] protocol);
BleDevice.ConnectionState getState();
String getAddress();
String getName();
BluetoothDevice getBluetoothDevice();
BluetoothLeService getBluetoothLeService();
}
|
java
| 8 | 0.742323 | 74 | 18.710526 | 38 |
starcoderdata
|
package models;
public class Tariff {
private String name;
private String id;
private String operatorName;
private Integer payroll;
private Integer SMSPrice;
private CallPrices callPrices;
private Parameters parameters;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getPayroll() {
return payroll;
}
public void setPayroll(int payroll) {
this.payroll = payroll;
}
public int getSMSPrice() {
return SMSPrice;
}
public void setSMSPrice(int SMSPrice) {
this.SMSPrice = SMSPrice;
}
public CallPrices getCallPrices() {
return callPrices;
}
public void setCallPrices(CallPrices callPrices) {
this.callPrices = callPrices;
}
public Parameters getParameters() {
return parameters;
}
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
}
|
java
| 8 | 0.6226 | 54 | 17.547945 | 73 |
starcoderdata
|
using System;
using UnityEngine;
namespace UnityPlatformer {
///
/// Static Character
/// This is a nice hack for breackable ropes. Just disable all 'Action' logic
///
public class StaticCharacter : Character {
///
/// Listen death event
///
/// TODO do something...
///
public override void OnDeath() {
UpdateManager.Remove (this);
}
///
/// just do nothing!
///
public override void PlatformerUpdate(float delta) {
}
///
/// just do nothing!
///
public override void LatePlatformerUpdate(float delta) {
}
}
}
|
c#
| 12 | 0.63081 | 79 | 24.1 | 30 |
starcoderdata
|
# Punto 1
def multiplicar(a, b):
m = 0
for i in range(0, b):
m = m + a
return m
# Punto 2
def potencia(a, b):
p = 1
for i in range(0, b):
p = multiplicar(p, a)
return p
# Punto 3
a = input()
b = input()
print potencia(a, b)
|
python
| 9 | 0.507519 | 29 | 13.777778 | 18 |
starcoderdata
|
def pipe1(img_224, model):
print("Ensuring entered picture is a car...")
with graph.as_default():
out = model.predict(img_224)
preds = get_predictions(out, top=5)
for pred in preds[0]:
if pred[0:2] in cat_list:
return True # "Successful. Proceeding to damage assessment..."
return False
|
python
| 9 | 0.606414 | 75 | 36.333333 | 9 |
inline
|
package network;
/**
* @author
*/
public interface NetClient extends ConnectionPlus, Runnable {
}
|
java
| 6 | 0.714286 | 61 | 14.555556 | 9 |
starcoderdata
|
/*
* Copyright (C) 2017 Intel Deutschland GmbH, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
// PWM defines
#define PWM_CYCLE 1200
#define PWM_OFFSET 200
#define MR0_INT 1 << 0
#define MR1_INT 1 << 1
#define MR2_INT 1 << 2
#define MR3_INT 1 << 3
#define MR4_INT 1 << 8
#define MR5_INT 1 << 9
#define MR6_INT 1 << 10
#define TCR_CNT_EN 0x00000001
#define TCR_RESET 0x00000002
#define TCR_PWM_EN 0x00000008
#define PWMMR0I 1 << 0
#define PWMMR0R 1 << 1
#define PWMMR0S 1 << 2
#define PWMMR1I 1 << 3
#define PWMMR1R 1 << 4
#define PWMMR1S 1 << 5
#define PWMMR2I 1 << 6
#define PWMMR2R 1 << 7
#define PWMMR2S 1 << 8
#define PWMMR3I 1 << 9
#define PWMMR3R 1 << 10
#define PWMMR3S 1 << 11
#define PWMMR4I 1 << 12
#define PWMMR4R 1 << 13
#define PWMMR4S 1 << 14
#define PWMMR5I 1 << 15
#define PWMMR5R 1 << 16
#define PWMMR5S 1 << 17
#define PWMMR6I 1 << 18
#define PWMMR6R 1 << 19
#define PWMMR6S 1 << 20
#define PWMSEL2 1 << 2
#define PWMSEL3 1 << 3
#define PWMSEL4 1 << 4
#define PWMSEL5 1 << 5
#define PWMSEL6 1 << 6
#define PWMENA1 1 << 9
#define PWMENA2 1 << 10
#define PWMENA3 1 << 11
#define PWMENA4 1 << 12
#define PWMENA5 1 << 13
#define PWMENA6 1 << 14
#define LER0_EN 1 << 0
#define LER1_EN 1 << 1
#define LER2_EN 1 << 2
#define LER3_EN 1 << 3
#define LER4_EN 1 << 4
#define LER5_EN 1 << 5
#define LER6_EN 1 << 6
extern unsigned int processorClockFrequency(void);
extern unsigned int peripheralClockFrequency(void);
extern void init(void);
struct HL_STATUS
{
short battery_voltage_1;
short cpu_load;
};
extern struct HL_STATUS HL_Status;
|
c
| 5 | 0.615352 | 75 | 25.252874 | 87 |
starcoderdata
|
void tx1_sound_device::ay8910_a_w(uint8_t data)
{
m_stream->update();
/* All outputs inverted */
m_ay_outputa = ~data;
}
|
c++
| 6 | 0.653226 | 47 | 16.857143 | 7 |
inline
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var vue = require('vue');
var error = require('../../../utils/error.js');
const useStops = (props, initData, minValue, maxValue) => {
const stops = vue.computed(() => {
if (!props.showStops || props.min > props.max)
return [];
if (props.step === 0) {
error.debugWarn("Slider", "step should not be 0.");
return [];
}
const stopCount = (props.max - props.min) / props.step;
const stepWidth = 100 * props.step / (props.max - props.min);
const result = Array.from({ length: stopCount - 1 }).map((_, index) => (index + 1) * stepWidth);
if (props.range) {
return result.filter((step) => {
return step < 100 * (minValue.value - props.min) / (props.max - props.min) || step > 100 * (maxValue.value - props.min) / (props.max - props.min);
});
} else {
return result.filter((step) => step > 100 * (initData.firstValue - props.min) / (props.max - props.min));
}
});
const getStopStyle = (position) => {
return props.vertical ? { bottom: `${position}%` } : { left: `${position}%` };
};
return {
stops,
getStopStyle
};
};
exports.useStops = useStops;
//# sourceMappingURL=useStops.js.map
|
javascript
| 26 | 0.587264 | 154 | 32.473684 | 38 |
starcoderdata
|
const tracks = [
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e0238aae75dc37fb42457866ffd",
width: 300
},
artists: [
"Anne-Marie"
],
name: "2002",
preview_url: "https://p.scdn.co/mp3-preview/393689f63c149cefb1f1293494058b93a0e19891?cid=966a78f306684bedb490134661a7d6d8"
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e0213b3e37318a0c247b550bccd",
width: 300
},
artists: [
"
],
name: "Photograph",
preview_url: "https://p.scdn.co/mp3-preview/097c7b735ceb410943cbd507a6e1dfda272fd8a8?cid=966a78f306684bedb490134661a7d6d8"
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e02ae7abe97f7020d657e87bbec",
width: 300
},
artists: [
"
],
name: "Kasoor",
preview_url: "https://p.scdn.co/mp3-preview/ec9cfd29543be823883fb589e36e301e9361573e?cid=966a78f306684bedb490134661a7d6d8"
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e025eab23d2260268d2fab870d0",
width: 300
},
artists: [
"
"Ruben",
],
name: "Heading Home",
preview_url: "https://p.scdn.co/mp3-preview/13ac027f0feccbda1b767686100a89e4ff6859e3?cid=966a78f306684bedb490134661a7d6d8"
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e02d304ba2d71de306812eebaf4",
width: 300
},
artists: [
"One Direction"
],
name: "No Control",
preview_url: "https://p.scdn.co/mp3-preview/ec58550c9769804c8c5844aff57a797fe83b597e?cid=966a78f306684bedb490134661a7d6d8"
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e0201057d1932a83beeaa451d37",
width: 300
},
artists: [
"Harnoor"
],
name: "Waalian",
preview_url: null
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e02495ce6da9aeb159e94eaa453",
width: 300
},
artists: [
"The Chainsmokers",
"Halsey"
],
name: "Closer",
preview_url: "https://p.scdn.co/mp3-preview/8d3df1c64907cb183bff5a127b1525b530992afb?cid=966a78f306684bedb490134661a7d6d8"
},
{
imgUrl: {
height: 300,
url: "https://i.scdn.co/image/ab67616d00001e02fec5ef9f3133aff71c525acc",
width: 300
},
artists: [
"
],
name: "Therefore I Am",
preview_url: null
}
];
export {tracks};
|
javascript
| 8 | 0.53581 | 130 | 28.019417 | 103 |
starcoderdata
|
<?php
defined('BASEPATH') Or exit ('No direct script access allowed');
class Barang_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function insertBarang(){
$object = array (
'nama' =>$this->input->post('NAMA'),
'harga' =>$this->input->post('HARGA'),
'stok' =>$this->input->post('STOK'),
);
$this->db->insert('inventory',$object);
}
public function getinventory(){
$query = $this->db->query("SELECT * from inventory ");
return $query->result_array();
}
public function getBiodataQueryArray($nama){
$query = $this->db->query("SELECT * from user where username ='$nama'");
return $query->result_array();
}
public function getinventorybyid($id){
$this->db->where('inventory_id',$id);
$query = $this->db->get('inventory');
return $query->result();
}
public function getharga($nama){
$query = $this->db->query("SELECT * from inventory where gambar = '$nama'");
return $query->result_array();
}
public function UpdateById($id,$nama,$uang,$hargaa){
// $this->load->view('sasd');
// echo $uang;
// foreach ($hargaa as $key) {
// $haha=$key['harga'];
// }
// echo $haha;
$coba='(inventory1 != "")';
if($this->db->where($coba)){
$data = array
(
'inventory2'=>($id));
}
else{
$data = array
(
'inventory1'=>($id));
}
echo $nama;
// echo $id;
// echo $data;
$this->db->where('username',$nama);
$this->db->update('user',$data);
}
public function Updateinventory($id){
$data = array
(
'nama' =>$this->input->post('nama'),
'harga' =>$this->input->post('harga'),
'stok' =>$this->input->post('stok'),
);
$this->db->where('inventory_id',$id);
$this->db->update('inventory',$data);
}
public function Buyinventory($id){
$awal=$this->input->post('stok');
$beli=$this->input->post('beli');
$total=$awal+$beli;
$data = array
(
'stok' =>$total,
);
$this->db->where('inventory_id',$id);
$this->db->update('inventory',$data);
}
public function Sellinventory($id){
$awal=$this->input->post('stok');
$beli=$this->input->post('beli');
$total=$awal-$beli;
$data = array
(
'stok' =>$total,
);
$this->db->where('inventory_id',$id);
$this->db->update('inventory',$data);
}
public function delete($id){
$this->db->where('inventory_id',$id);
$this->db->delete('inventory');
}
}
?>
|
php
| 14 | 0.592875 | 78 | 21.254717 | 106 |
starcoderdata
|
def test_entries_for_tenant_external_multiple_regions(self):
"""
Test with multiple regions for the External APIs.
"""
iapi = make_example_internal_api(self)
eeapi = make_example_external_api(
self,
name=self.eeapi_name,
set_enabled=True
)
eeapi2_name = "alternate-external-api"
eeapi2_template_id = u"uuid-alternate-endpoint-template"
eeapi2_template = exampleEndpointTemplate(
name=eeapi2_name,
endpoint_uuid=eeapi2_template_id,
region=u"NEW_REGION",
url=u"https://api.new_region.example.com:9090"
)
eeapi2 = make_example_external_api(
self,
name=eeapi2_name,
endpoint_templates=[eeapi2_template],
set_enabled=True
)
core = MimicCore(Clock(), [eeapi, eeapi2, iapi])
prefix_map = {}
base_uri = "http://some/random/prefix"
catalog_entries = [
entry
for entry in core.entries_for_tenant(
'some-tenant',
prefix_map,
base_uri
)
]
self.assertEqual(len(core._uuid_to_api_internal), 1)
self.assertEqual(len(core._uuid_to_api_external), 2)
self.assertEqual(len(catalog_entries), 3)
found_internal = False
found_first_external = False
found_second_external = False
for catalog_entry in catalog_entries:
if catalog_entry.name == eeapi.name_key:
found_first_external = True
self.assertEqual(catalog_entry.type, eeapi.type_key)
self.assertEqual(catalog_entry.name, eeapi.name_key)
self.assertEqual(catalog_entry.tenant_id, "some-tenant")
self.assertEqual(len(catalog_entry.endpoints), 1)
elif catalog_entry.name == eeapi2.name_key:
found_second_external = True
self.assertEqual(catalog_entry.type, eeapi2.type_key)
self.assertEqual(catalog_entry.name, eeapi2.name_key)
self.assertEqual(catalog_entry.tenant_id, "some-tenant")
self.assertEqual(len(catalog_entry.endpoints), 1)
elif catalog_entry.name == "serviceName":
found_internal = True
self.assertEqual(catalog_entry.type, "serviceType")
self.assertEqual(catalog_entry.name, "serviceName")
self.assertEqual(catalog_entry.tenant_id, "some-tenant")
self.assertEqual(len(catalog_entry.endpoints), 1)
self.assertTrue(found_internal)
self.assertTrue(found_first_external)
self.assertTrue(found_second_external)
|
python
| 14 | 0.5767 | 72 | 37.943662 | 71 |
inline
|
package com.grayson.www.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.grayson.common.config.Configs;
import com.grayson.common.util.CommonUtils;
import com.grayson.www.pojo.Feedback;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
@Controller
@RequestMapping("/")
public class WWWController {
/**
* 首页
*
* @return 首页
*/
@RequestMapping("/")
public String getMovie(ModelMap map, HttpServletRequest request) {
CommonUtils commonUtils = new CommonUtils();
String cookieName = "userInfo";
JSONObject userInfo = commonUtils.getCookieValue(request, cookieName);
map.addAttribute("userInfo", userInfo);
return "index.html";
}
/**
* 登陆
*
* @return 登陆
*/
@RequestMapping("/login")
public String login(ModelMap map, HttpServletRequest request) {
return "login.html";
}
/**
* 注册
*
* @return 注册
*/
@RequestMapping("/register")
public String register() {
return "register.html";
}
/**
* 反馈
*
* @return 反馈
*/
@RequestMapping("/feedback")
public String feedback(ModelMap map, HttpServletRequest request, @RequestParam(value = "page_index", defaultValue = "1") String page_index) {
CommonUtils commonUtils = new CommonUtils();
String cookieName = "userInfo";
JSONObject userInfo = commonUtils.getCookieValue(request, cookieName);
map.addAttribute("userInfo", userInfo);
Integer pageSize = 18;
// 反馈信息
String feedbackListUrl = Configs.API + "/feedback/get/all?page_index=" + page_index + "&page_size=" + pageSize;
JSONObject feedbackObject = commonUtils.doGet(feedbackListUrl);
// 获取反馈信息数量
String countMovieUrl = Configs.API + "/count/get/feedback";
JSONObject countMovieObject = commonUtils.doGet(countMovieUrl);
Integer count = countMovieObject.getInteger("data");
// 获取页数相关信息
Integer pageIndex = Integer.parseInt(page_index);
Integer totalPage = count / pageSize;
totalPage = count % pageSize == 0 ? totalPage : totalPage + 1;
List pages = commonUtils.getPages(count, pageIndex, pageSize, totalPage);
map.addAttribute("feedbackList", feedbackObject.getJSONArray("data"));
map.addAttribute("page_index", pageIndex);
map.addAttribute("page_size", pageSize);
map.addAttribute("total_page", totalPage);
map.addAttribute("pages", pages);
map.addAttribute("title", "掌上影视 - 反馈");
return "feedback.html";
}
/**
* 添加反馈
*
* @return 添加反馈
*/
@RequestMapping("/feedback/add")
public String feedbackRelease(ModelMap map, HttpServletRequest request, @RequestBody String g_content) {
CommonUtils commonUtils = new CommonUtils();
String cookieName = "userInfo";
JSONObject userInfo = commonUtils.getCookieValue(request, cookieName);
String user_name = userInfo.getString("username");
String content = null;
try {
content = URLDecoder.decode(g_content.split("&")[2].split("=")[1],"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String device_uuid = request.getHeader("user-agent");
String device_version = System.getProperty("os.version");
String device_platform = System.getProperty("os.name");
Feedback feedback = new Feedback();
feedback.setUser_name(user_name);
feedback.setContent(content);
feedback.setDevice_uuid(device_uuid);
feedback.setDevice_version(device_version);
feedback.setDevice_platform(device_platform);
String feedbackAddUrl = Configs.API + "/feedback/add";
commonUtils.doPost(feedbackAddUrl, JSONObject.parseObject(JSON.toJSONString(feedback)));
return "feedback-add.html";
}
}
|
java
| 17 | 0.665251 | 145 | 33.423077 | 130 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace SpeedRacing
{
public class StartUp
{
public static void Main()
{
HashSet cars = new HashSet
int numberOfCars = int.Parse(Console.ReadLine());
for (int i = 0; i < numberOfCars; i++)
{
string[] inputCar = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string model = inputCar[0];
decimal fuelAmount = decimal.Parse(inputCar[1]);
decimal fuelConsumptionFor1km = decimal.Parse(inputCar[2]);
Car car = new Car(model, fuelAmount, fuelConsumptionFor1km);
cars.Add(car);
}
string command = Console.ReadLine();
while (command != "End")
{
string[] commandArgumenst = command
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string carModel = commandArgumenst[1];
decimal amountOfKm = decimal.Parse(commandArgumenst[2]);
var currentCar = cars.FirstOrDefault(x => x.Model == carModel);
currentCar.Drive(amountOfKm);
command = Console.ReadLine();
}
foreach (var car in cars)
{
Console.WriteLine($"{car.Model} {car.FuelAmount:F2} {car.TravelledDistance}");
}
}
}
}
|
c#
| 21 | 0.514036 | 94 | 28.145455 | 55 |
starcoderdata
|
const winston = require('winston');
const { combine, timestamp, simple, colorize, json } = winston.format;
const logger = winston.createLogger({
level: 'info',
format: timestamp(),
transports: [
new winston.transports.Console({
format: combine(
colorize(),
simple(),
)
}),
new winston.transports.File({ format: json(), filename: 'logs/error.log', level: 'error', encoding: 'utf-8' }),
new winston.transports.File({ format: json(), filename: 'logs/server.log', encoding: 'utf-8' }),
],
});
module.exports = function () {
console.log = (...args) => logger.info.call(logger, ...args);
console.info = (...args) => logger.info.call(logger, ...args);
console.warn = (...args) => logger.warn.call(logger, ...args);
console.error = (...args) => logger.error.call(logger, ...args);
console.debug = (...args) => logger.debug.call(logger, ...args);
}
|
javascript
| 16 | 0.588177 | 119 | 36.62963 | 27 |
starcoderdata
|
//===--- StmtPUBLIC_DOMAIN_TECHNOLOGY.cpp - Code transformation AST nodes --------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Transformation directive statement and clauses for the AST.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/StmtPUBLIC_DOMAIN_TECHNOLOGY.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtOpenMP.h"
using namespace clang;
bool PUBLIC_DOMAIN_TECHNOLOGYClause::isValidForPUBLIC_DOMAIN_TECHNOLOGY(PUBLIC_DOMAIN_TECHNOLOGY::Kind PUBLIC_DOMAIN_TECHNOLOGYKind,
PUBLIC_DOMAIN_TECHNOLOGYClause::Kind ClauseKind) {
switch (PUBLIC_DOMAIN_TECHNOLOGYKind) {
case clang::PUBLIC_DOMAIN_TECHNOLOGY::NoCheckKind:
case clang::PUBLIC_DOMAIN_TECHNOLOGY::CheckKind:
return ClauseKind == FullKind;
default:
return false;
}
}
PUBLIC_DOMAIN_TECHNOLOGYClause::Kind
PUBLIC_DOMAIN_TECHNOLOGYClause ::getClauseKind(PUBLIC_DOMAIN_TECHNOLOGY::Kind PUBLIC_DOMAIN_TECHNOLOGYKind,
llvm::StringRef Str) {
#define PUBLIC_DOMAIN_TECHNOLOGY_CLAUSE(Keyword, Name) \
if (isValidForPUBLIC_DOMAIN_TECHNOLOGY(PUBLIC_DOMAIN_TECHNOLOGYKind, PUBLIC_DOMAIN_TECHNOLOGYClause::Kind::Name##Kind) && \
Str == #Keyword) \
return PUBLIC_DOMAIN_TECHNOLOGYClause::Kind::Name##Kind;
#include "clang/AST/PUBLIC_DOMAIN_TECHNOLOGYClauseKinds.def"
return PUBLIC_DOMAIN_TECHNOLOGYClause::UnknownKind;
}
llvm::StringRef
PUBLIC_DOMAIN_TECHNOLOGYClause ::getClauseKeyword(PUBLIC_DOMAIN_TECHNOLOGYClause::Kind ClauseKind) {
assert(ClauseKind > UnknownKind);
assert(ClauseKind <= LastKind);
static const char *ClauseKeyword[LastKind] = {
#define PUBLIC_DOMAIN_TECHNOLOGY_CLAUSE(Keyword, Name) #Keyword,
#include "clang/AST/PUBLIC_DOMAIN_TECHNOLOGYClauseKinds.def"
};
return ClauseKeyword[ClauseKind - 1];
}
|
c++
| 8 | 0.653439 | 132 | 41.792453 | 53 |
starcoderdata
|
from rudp.sender import Sender
from rudp.receiver import Receiver
from node.network_util import count_incoming_packet, count_outgoing_packet
from pyee import EventEmitter
import logging
class Connection(object):
def __init__(self, packet_sender):
self.log = logging.getLogger(
'%s' % self.__class__.__name__
)
self.log.info('Init Connection')
self.ee = EventEmitter()
self._sender = Sender(packet_sender)
self._receiver = Receiver(packet_sender)
# pylint: disable=unused-variable
@self._receiver.ee.on('data')
def on_data(data):
self.log.debug('Received IncomingMessage: %s', data)
self.ee.emit('data', data)
# pylint: disable=unused-variable
@self._receiver.ee.on('_reset')
def on_reset(data):
self.log.debug('Received reset message')
#self._sender = Sender(packet_sender)
def send(self, data):
self._sender.send(data)
count_outgoing_packet(data)
def receive(self, packet):
if packet._acknowledgement:
self._sender.verify_acknowledgement(packet._sequenceNumber)
else:
self._receiver.receive(packet)
count_incoming_packet(packet)
|
python
| 12 | 0.623755 | 74 | 28 | 45 |
starcoderdata
|
package CompressionAlgorithms.domain;
import CompressionAlgorithms.utils.DataUtils;
/**
* The algorithm
*/
public class Lzw {
private static int initialDictSize = 256;
private static int maxDictSize = 65536;
/**
* Compresses a given string of text using LZW
*
* @param source String to compress
* @return compressed String
*/
public static List compress(String source) {
HashTable<String, Integer> dictionary = initializeCompressionDictionary();
List compressed = compressStringByDictionary(source, dictionary);
return compressed;
}
/**
* Decompresses given compressed content
*
* @param compressedContent List compressed content
* @return extracted String
*/
public static String decompress(List compressedContent) {
HashTable<Integer, String> dictionary = initializeDecompressionDictionary();
String result = decompressByDictionary(dictionary, compressedContent);
return result;
}
/**
* Initialize the compression dictionary
*
* @return dictionary HashTable<String, Integer>
*/
private static HashTable<String, Integer> initializeCompressionDictionary() {
HashTable<String, Integer> dictionary = new HashTable<>();
for (int i = 0; i < initialDictSize; i++) {
dictionary.put("" + (char) i, i);
}
return dictionary;
}
/**
* Initialize the decompression dictionary
*
* @return dictionary HashTable<Integer, String>
*/
private static HashTable<Integer, String> initializeDecompressionDictionary() {
HashTable<Integer, String> dictionary = new HashTable<>();
for (int i = 0; i < initialDictSize; i++) {
dictionary.put(i, "" + (char) i);
}
return dictionary;
}
/**
* Compress string using a given dictionary
* @param uncompressedString String to compress
* @param dictionary HashTable<String, Integer> dictionary
* @return List
*/
private static List compressStringByDictionary(String uncompressedString, HashTable<String, Integer> dictionary) {
int dictSize = dictionary.size();
String w = "";
List byteList = new List<>();
for (char character: uncompressedString.toCharArray()) {
String wc = w + character;
if (dictionary.containsKey(wc)) {
w = wc;
} else {
addToByteList(dictionary.get(w), byteList);
dictionary.put(wc, dictSize++);
w = "" + character;
}
// If the dictionary becomes full it ceases to work properly, so flush the dictionary
if (dictSize >= maxDictSize) {
dictionary = initializeCompressionDictionary();
dictSize = initialDictSize;
}
}
if (!w.isEmpty()) {
addToByteList(dictionary.get(w), byteList);
}
return byteList;
}
private static void addToByteList(Integer value, List byteList) {
byte[] bytes = DataUtils.convertIntTo2Bytes(value);
byteList.add(bytes[0]);
byteList.add(bytes[1]);
}
/**
* Decompress compressed content by given dictionary
* @param dictionary HashTable<Integer, String>
* @param byteList List
* @return String
*/
private static String decompressByDictionary(HashTable<Integer, String> dictionary, List byteList) {
if (byteList == null) {
return null;
}
if (byteList.size() == 0) {
return null;
}
int dictSize = dictionary.size();
byte[] firstBytes = {
byteList.remove(0),
byteList.remove(0)
};
String w = "" + (char) DataUtils.convert2BytesToInt(firstBytes);
String result = w;
for (int i = 0; i < byteList.size() - 1; i = i + 2) {
byte[] bytes = {
byteList.get(i),
byteList.get(i + 1)
};
int entry = DataUtils.convert2BytesToInt(bytes);
String text = "";
if (dictionary.containsKey(entry)) {
text = dictionary.get(entry);
} else if (entry == dictSize) {
text = w + w.charAt(0);
}
if (!text.isEmpty()) {
dictionary.put(dictSize++, w + text.charAt(0));
}
result += text;
w = text;
// If the dictionary becomes full it ceases to work properly, so flush the dictionary
if (dictSize >= maxDictSize) {
dictionary = initializeDecompressionDictionary();
dictSize = initialDictSize;
}
}
return result;
}
}
|
java
| 15 | 0.559359 | 124 | 31.397436 | 156 |
starcoderdata
|
#include <stdio.h>
int main (void){
int loop1,loop2;
int how_q;
scanf("%d",&how_q);
int how_time[how_q];
for(loop1=0;loop1<how_q;loop1++){
scanf("%d",&how_time[loop1]);
}
int how_drink;
scanf("%d",&how_drink);
int drink_data[how_drink][2];
int output;
for(loop1=0;loop1<how_drink;loop1++){
scanf("%d%d",&drink_data[loop1][0],&drink_data[loop1][1]);
output=0;
for(loop2=0;loop2<how_q;loop2++){
if(drink_data[loop1][0]-1==loop2){
output+=drink_data[loop1][1];
}else{
output+=how_time[loop2];
}
}
printf("%d\n",output);
output=0;
}
return 0;
}
|
c
| 13 | 0.49162 | 66 | 24.607143 | 28 |
codenet
|
package anjithsasindran.mapboxdemo.Modal;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Resource {
@SerializedName("__type")
@Expose
private String Type;
@SerializedName("bbox")
@Expose
private List bbox = new ArrayList
@SerializedName("name")
@Expose
private String name;
@SerializedName("point")
@Expose
private Point point;
@SerializedName("address")
@Expose
private Address address;
@SerializedName("confidence")
@Expose
private String confidence;
@SerializedName("entityType")
@Expose
private String entityType;
@SerializedName("geocodePoints")
@Expose
private List geocodePoints = new ArrayList
@SerializedName("matchCodes")
@Expose
private List matchCodes = new ArrayList
/**
*
* @return
* The Type
*/
public String getType() {
return Type;
}
/**
*
* @param Type
* The __type
*/
public void setType(String Type) {
this.Type = Type;
}
/**
*
* @return
* The bbox
*/
public List getBbox() {
return bbox;
}
/**
*
* @param bbox
* The bbox
*/
public void setBbox(List bbox) {
this.bbox = bbox;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The point
*/
public Point getPoint() {
return point;
}
/**
*
* @param point
* The point
*/
public void setPoint(Point point) {
this.point = point;
}
/**
*
* @return
* The address
*/
public Address getAddress() {
return address;
}
/**
*
* @param address
* The address
*/
public void setAddress(Address address) {
this.address = address;
}
/**
*
* @return
* The confidence
*/
public String getConfidence() {
return confidence;
}
/**
*
* @param confidence
* The confidence
*/
public void setConfidence(String confidence) {
this.confidence = confidence;
}
/**
*
* @return
* The entityType
*/
public String getEntityType() {
return entityType;
}
/**
*
* @param entityType
* The entityType
*/
public void setEntityType(String entityType) {
this.entityType = entityType;
}
/**
*
* @return
* The geocodePoints
*/
public List getGeocodePoints() {
return geocodePoints;
}
/**
*
* @param geocodePoints
* The geocodePoints
*/
public void setGeocodePoints(List geocodePoints) {
this.geocodePoints = geocodePoints;
}
/**
*
* @return
* The matchCodes
*/
public List getMatchCodes() {
return matchCodes;
}
/**
*
* @param matchCodes
* The matchCodes
*/
public void setMatchCodes(List matchCodes) {
this.matchCodes = matchCodes;
}
}
|
java
| 8 | 0.523956 | 77 | 16.668317 | 202 |
starcoderdata
|
func (p *Prop) getId() string {
if p.Name == "aura" {
// Two auras do not work even if they are different types
return p.Name
} else {
// Otherwise include both the prop type and sub-type
return p.Name + p.Par
}
}
|
go
| 9 | 0.651786 | 59 | 24 | 9 |
inline
|
import React from 'react'
import { ThemeProvider } from 'styled-components'
import PropTypes from 'prop-types'
const theme = {
header: 'white',
background: 'cyan',
text: 'red'
}
const ThemeMock = props => (
<ThemeProvider theme={theme}>
{props.children}
)
export default ThemeMock
ThemeMock.propTypes = {
children: PropTypes.any
}
|
javascript
| 9 | 0.69837 | 49 | 16.52381 | 21 |
starcoderdata
|
package org.simpleframework.xml.transform;
import junit.framework.TestCase;
public class TypeMatcherTest extends TestCase {
private static class BlankMatcher implements Matcher {
public Transform match(Class type) throws Exception {
return null;
}
}
private Matcher matcher;
public void setUp() {
this.matcher = new DefaultMatcher(new BlankMatcher());
}
public void testInteger() throws Exception {
Transform transform = matcher.match(Integer.class);
Object value = transform.read("1");
assertEquals(value, new Integer(1));
}
public void testString() throws Exception {
Transform transform = matcher.match(String.class);
Object value = transform.read("some text");
assertEquals("some text", value);
}
public void testCharacter() throws Exception {
Transform transform = matcher.match(Character.class);
Object value = transform.read("c");
assertEquals(value, new Character('c'));
}
public void testFloat() throws Exception {
Transform transform = matcher.match(Float.class);
Object value = transform.read("1.12");
assertEquals(value, new Float(1.12));
}
public void testDouble() throws Exception {
Transform transform = matcher.match(Double.class);
Object value = transform.read("12.33");
assertEquals(value, new Double(12.33));
}
public void testBoolean() throws Exception {
Transform transform = matcher.match(Boolean.class);
Object value = transform.read("true");
assertEquals(value, Boolean.TRUE);
}
public void testLong() throws Exception {
Transform transform = matcher.match(Long.class);
Object value = transform.read("1234567");
assertEquals(value, new Long(1234567));
}
public void testShort() throws Exception {
Transform transform = matcher.match(Short.class);
Object value = transform.read("12");
assertEquals(value, new Short((short)12));
}
public void testIntegerArray() throws Exception {
Transform transform = matcher.match(Integer[].class);
Object value = transform.read("1, 2, 3, 4, 5");
assertTrue(value instanceof Integer[]);
Integer[] array = (Integer[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Integer(1));
assertEquals(array[1], new Integer(2));
assertEquals(array[2], new Integer(3));
assertEquals(array[3], new Integer(4));
assertEquals(array[4], new Integer(5));
}
public void testPrimitiveIntegerArray() throws Exception {
Matcher matcher = new DefaultMatcher(new BlankMatcher());
Transform transform = matcher.match(int[].class);
Object value = transform.read("1, 2, 3, 4, 5");
assertTrue(value instanceof int[]);
int[] array = (int[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1);
assertEquals(array[1], 2);
assertEquals(array[2], 3);
assertEquals(array[3], 4);
assertEquals(array[4], 5);
}
}
|
java
| 12 | 0.631232 | 63 | 28.527778 | 108 |
starcoderdata
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsPagePrintTimer_h___
#define nsPagePrintTimer_h___
// Timer Includes
#include "nsITimer.h"
#include "nsIDocumentViewerPrint.h"
#include "mozilla/Attributes.h"
#include "mozilla/OwningNonNull.h"
#include "nsThreadUtils.h"
class nsPrintJob;
class nsPrintObject;
namespace mozilla::dom {
class Document;
}
//---------------------------------------------------
//-- Page Timer Class
//---------------------------------------------------
// Strictly speaking, this actually manages the timing of printing *sheets*
// (instances of "PrintedSheetFrame"), each of which may encompass multiple
// pages (nsPageFrames) of the document. The use of "Page" in the class name
// here is for historical / colloquial purposes.
class nsPagePrintTimer final : public mozilla::Runnable,
public nsITimerCallback {
public:
NS_DECL_ISUPPORTS_INHERITED
nsPagePrintTimer(nsPrintJob* aPrintJob,
nsIDocumentViewerPrint* aDocViewerPrint,
mozilla::dom::Document* aDocument, uint32_t aDelay);
NS_DECL_NSITIMERCALLBACK
nsresult Start(nsPrintObject* aPO);
NS_IMETHOD Run() override;
void Stop();
void WaitForRemotePrint();
void RemotePrintFinished();
void Disconnect();
private:
~nsPagePrintTimer();
nsresult StartTimer(bool aUseDelay);
nsresult StartWatchDogTimer();
void StopWatchDogTimer();
void Fail();
nsPrintJob* mPrintJob;
nsCOMPtr<nsIDocumentViewerPrint> mDocViewerPrint;
RefPtr<mozilla::dom::Document> mDocument;
nsCOMPtr<nsITimer> mTimer;
nsCOMPtr<nsITimer> mWatchDogTimer;
nsCOMPtr<nsITimer> mWaitingForRemotePrint;
uint32_t mDelay;
uint32_t mFiringCount;
nsPrintObject* mPrintObj;
uint32_t mWatchDogCount;
bool mDone;
static const uint32_t WATCH_DOG_INTERVAL = 1000;
static const uint32_t WATCH_DOG_MAX_COUNT =
#ifdef DEBUG
// Debug builds are very slow (on Mac at least) and can need extra time
30
#else
10
#endif
;
};
#endif /* nsPagePrintTimer_h___ */
|
c
| 10 | 0.67608 | 79 | 26.821429 | 84 |
research_code
|
body
{
background-color: light-blue;
}
<?php echo $this->session->userdata('email'); ?>
<a href="<?php echo base_url().'login/logout'; ?>" class = "btn btn-logout">logout
<a href="<?php echo base_url().'admin/index'; ?>">
<button type = "Admin" class = "btn btn-data-admin">Admin
<a href="<?php echo base_url().'code/index'; ?>" >
<button type = "Redeem Code" class = "btn btn-siswa">Siswa
0
|
php
| 6 | 0.588768 | 90 | 17.433333 | 30 |
starcoderdata
|
Oskari.registerLocalization(
{
"lang": "nl",
"key": "Printout",
"value": {
"title": "Kaartbeeld afdrukken",
"flyouttitle": "Kaartbeeld afdrukken",
"desc": "",
"btnTooltip": "Afdrukken",
"BasicView": {
"title": "Kaartbeeld afdrukken",
"name": {
"label": "Kaartnaam",
"placeholder": "vereist",
"tooltip": "Geef je kaart een beschrijvende naam. Let op de taal van de gebruikersinterface."
},
"language": {
"label": "Taal",
"options": {
"fi": "Fins",
"sv": "Zweeds",
"en": "Engels"
},
"tooltip": "Kies de taal van de kaartinterface en kaartgegevens."
},
"size": {
"label": "Grootte",
"tooltip": "Kies afdrukindeling. Voorbeeldkaart wordt dienovereenkomstig aangepast.",
"options": [
{
"id": "A4",
"label": "A4 staand",
"classForPreview": "preview-portrait",
"selected": true
},
{
"id": "A4_Landscape",
"label": "A4 liggend",
"classForPreview": "preview-landscape"
},
{
"id": "A3",
"label": "A3 staand",
"classForPreview": "preview-portrait"
},
{
"id": "A3_Landscape",
"label": "A3 liggend",
"classForPreview": "preview-landscape"
}
]
},
"preview": {
"label": "Voorbeeld",
"tooltip": "Klik op het kleine voorbeeld om een groter voorbeeld te openen",
"pending": "Voorbeeld zal binnenkort worden bijgewerkt",
"notes": {
"extent": "Voorbeeld kan worden gebruikt om er achter te komen wat de kaartomvang is voor de afdruk",
"restriction": "Niet alle kaartlagen worden getoond in het voorbeeld"
}
},
"buttons": {
"save": "Krijg afdruk",
"ok": "OK",
"back": "Vorige",
"cancel": "Annuleren"
},
"location": {
"label": "Locatie en het zoomniveau",
"tooltip": "Afdruk schaal komt overeen met de schaal van de kaart in de browser.",
"zoomlevel": "Zoomniveau"
},
"settings": {
"label": "Meer instellingen",
"tooltip": "Maak extra instellingen, zoals formaat, titel en de schaal"
},
"format": {
"label": "Formaat",
"tooltip": "Selecteer bestandsformaat",
"options": [
{
"id": "png",
"format": "image/png",
"label": "PNG afbeelding"
},
{
"id": "pdf",
"format": "application/pdf",
"selected": true,
"label": "PDF document"
}
]
},
"mapTitle": {
"label": "Voeg titel toe",
"tooltip": "Voeg een titel toe aan de kaart"
},
"content": {
"options": [
{
"id": "pageLogo",
"label": "Voeg het Oskari logo toe",
"tooltip": "U kunt het logo indien nodig verbergen",
"checked": "checked"
},
{
"id": "pageScale",
"label": "Voeg schaal toe aan de kaart",
"tooltip": "Voeg schaal toe aan de kaart",
"checked": "checked"
},
{
"id": "pageDate",
"label": "Voeg datum toe",
"tooltip": "U kunt de datum toevoegen aan de afdruk",
"checked": "checked"
}
]
},
"legend": {
"label": "Kaart legenda",
"tooltip": "Kies een positie voor de kaart legenda. Als er geen positie is geselecteerd, wordt er geen kaartlegenda getoond in de kaart afdruk.",
"options": [
{
"id": "oskari_legend_NO",
"loca": "NO",
"label": "Geen kaart legenda",
"tooltip": "De kaart legenda wordt niet getoond op de kaart afdruk",
"selected": true
},
{
"id": "oskari_legend_LL",
"loca": "LL",
"label": "Linksonder",
"tooltip": "De kaart legenda wordt getoond linksonder op de afdruk"
},
{
"id": "oskari_legend_LU",
"loca": "LU",
"label": "Linksboven",
"tooltip": "De kaart legenda wordt getoond linksboven op de afdruk"
},
{
"id": "oskari_legend_RU",
"loca": "RU",
"label": "Rechtsboven",
"tooltip": "De kaart legenda wordt getoond rechtsboven op de afdruk"
},
{
"id": "oskari_legend_RL",
"loca": "RL",
"label": "Rechtsonder",
"tooltip": "De kaart legenda wordt getoond rechtsonder op de afdruk"
}
]
},
"help": "Help",
"error": {
"title": "Fout",
"size": "Fout in grootte definities",
"name": "Naam is vereiste informatie",
"nohelp": "Er is geen hulp beschikbaar",
"saveFailed": "Kaart afdrukken mislukt. Probeer het later opnieuw.",
"nameIllegalCharacters": "De naam bevat niet-toegestane tekens. Toegestane tekens zijn de letters a-z, evenals å, ä and ö, nummers, backspace en koppeltekens."
}
},
"StartView": {
"text": "U kunt de kaartweergave die u zojuist gemaakt heeft gemaakt afdrukken.",
"info": {
"maxLayers": "U kunt maximaal 8 lagen in één keer afdrukken",
"printoutProcessingTime": "Verwerking van de afdruk zal enige tijd duren wanneer meerdere lagen geselecteerd zijn."
},
"buttons": {
"continue": "Doorgaan",
"cancel": "Annuleren"
}
}
}
}
);
|
javascript
| 13 | 0.391005 | 175 | 39.911602 | 181 |
starcoderdata
|
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
class A1(Enum):
VALUE_1 = 1
VALUE_2 = 2
VALUE_3 = 3
VALUE_4 = 4
@dataclass
class A2:
class Meta:
name = "A"
value: Optional[int] = field(
default=None,
metadata={
"required": True,
"min_exclusive": 0,
"max_inclusive": 10,
}
)
class B1(Enum):
A = "a"
B = "b"
C123456789 = "c123456789"
@dataclass
class B2:
class Meta:
name = "B"
value: str = field(
default="",
metadata={
"required": True,
"min_length": 0,
"max_length": 10,
}
)
class RA1(Enum):
VALUE_1 = 1
VALUE_2 = 2
class UnionA(Enum):
VALUE_1 = 1
VALUE_2 = 2
VALUE_3 = 3
VALUE_4 = 4
class UnionAb(Enum):
VALUE_1 = 1
VALUE_2 = 2
VALUE_3 = 3
VALUE_4 = 4
A = "a"
B = "b"
C123456789 = "c123456789"
@dataclass
class Item:
class Meta:
name = "item"
value: Optional[object] = field(
default=None
)
@dataclass
class A3:
class Meta:
name = "a"
value: Optional[A1] = field(
default=None,
metadata={
"required": True,
}
)
@dataclass
class B3:
class Meta:
name = "b"
value: Optional[B1] = field(
default=None,
metadata={
"required": True,
}
)
@dataclass
class La:
class Meta:
name = "la"
value: List[A1] = field(
default_factory=list,
metadata={
"tokens": True,
}
)
@dataclass
class Lab:
class Meta:
name = "lab"
value: List[UnionAb] = field(
default_factory=list,
metadata={
"tokens": True,
}
)
@dataclass
class Ra:
class Meta:
name = "ra"
value: Optional[RA1] = field(
default=None,
metadata={
"required": True,
}
)
@dataclass
class Root:
class Meta:
name = "root"
ra: List[RA1] = field(
default_factory=list,
metadata={
"type": "Element",
}
)
lab: List[List[UnionAb]] = field(
default_factory=list,
metadata={
"type": "Element",
"tokens": True,
}
)
la: List[List[A1]] = field(
default_factory=list,
metadata={
"type": "Element",
"tokens": True,
}
)
uab: List[UnionAb] = field(
default_factory=list,
metadata={
"type": "Element",
}
)
ua: List[UnionA] = field(
default_factory=list,
metadata={
"type": "Element",
}
)
b_element: List[B1] = field(
default_factory=list,
metadata={
"name": "b",
"type": "Element",
}
)
a_element: List[A1] = field(
default_factory=list,
metadata={
"name": "a",
"type": "Element",
}
)
b: List[str] = field(
default_factory=list,
metadata={
"name": "B",
"type": "Element",
"min_length": 0,
"max_length": 10,
}
)
a: List[int] = field(
default_factory=list,
metadata={
"name": "A",
"type": "Element",
"min_exclusive": 0,
"max_inclusive": 10,
}
)
item: List[object] = field(
default_factory=list,
metadata={
"type": "Element",
}
)
@dataclass
class Ua:
class Meta:
name = "ua"
value: Optional[UnionA] = field(
default=None,
metadata={
"required": True,
}
)
@dataclass
class Uab:
class Meta:
name = "uab"
value: Optional[UnionAb] = field(
default=None,
metadata={
"required": True,
}
)
|
python
| 13 | 0.455621 | 40 | 15.421053 | 247 |
starcoderdata
|
package com.creolophus.im.entity;
import com.creolophus.liuyi.common.base.AbstractEntity;
import io.swagger.annotations.ApiModelProperty;
import org.beetl.sql.core.annotatoin.AssignID;
import java.util.Date;
/**
* @author magicnana
* @date 2019-10-29
*/
public class MessageIdSection extends AbstractEntity {
@ApiModelProperty(notes = "SectionID")
@AssignID
private Long sectionId;
@ApiModelProperty(notes = "每次增加步长")
private Integer step;
@ApiModelProperty(notes = "当前 MessageID")
private Long currentId;
@ApiModelProperty(notes = "最大 MessageID")
private Long maxId;
private Date createTime;
private Date updateTime;
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getCurrentId() {
return currentId;
}
public void setCurrentId(Long currentId) {
this.currentId = currentId;
}
public Long getMaxId() {
return maxId;
}
public void setMaxId(Long maxId) {
this.maxId = maxId;
}
public Long getSectionId() {
return sectionId;
}
public void setSectionId(Long sectionId) {
this.sectionId = sectionId;
}
public Integer getStep() {
return step;
}
public void setStep(Integer step) {
this.step = step;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
java
| 9 | 0.653798 | 55 | 19.589744 | 78 |
starcoderdata
|
package com.sun.source.tree;
import checkers.inference.reim.quals.*;
public interface CatchTree extends Tree {
@Polyread VariableTree getParameter(@Polyread CatchTree this) ;
@Polyread BlockTree getBlock(@Polyread CatchTree this) ;
}
|
java
| 12 | 0.797143 | 105 | 37.888889 | 9 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace dotNETClassLibraryUsingUWPAPIs
{
class LiveTileHelper
{
[DllExport(CallingConvention.StdCall)]
public static string UpdatePrimaryTile(string text, int durationSeconds = 10)
{
var template = Windows.UI.Notifications.TileTemplateType.TileSquare150x150Block;
var tileXml = Windows.UI.Notifications.TileUpdateManager.GetTemplateContent(template);
var tileTextAttributes = tileXml.GetElementsByTagName("text");
tileTextAttributes[0].AppendChild(tileXml.CreateTextNode(text));
var tileNotification = new Windows.UI.Notifications.TileNotification(tileXml);
tileNotification.ExpirationTime = DateTime.Now.AddSeconds(durationSeconds);
Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
return "Ok";
}
}
}
|
c#
| 16 | 0.736323 | 114 | 37.448276 | 29 |
starcoderdata
|
import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import moment from 'moment';
import ResultsListItem from './ResultsListItem';
configure({adapter: new Adapter()});
describe('If a result is found, then <ResultsListItem />', () => {
const resultsTest = {
id: '123',
score: '223',
title: 'Test title',
domain: 'youtube.com',
date: '1579395373',
comments: '52',
subreddit: 'Music',
titleUrl: 'https://www.youtube.com/watch?v=nN_FafYL38Q&feature=youtu.be',
commentsUrl: 'https://www.reddit.com/r/Music/comments/eqelu8/lara6683_dance_monkey_piano_cover_electropop/'
};
let wrapper;
beforeEach(() => {
wrapper = shallow(<ResultsListItem />);
wrapper.setProps(resultsTest);
});
it(`should render a <ResultsListItem /> with the correct post score`, () => {
expect(wrapper.text()).toContain(resultsTest.score);
});
it(`should render a <ResultsListItem /> with the correct post title`, () => {
expect(wrapper.text()).toContain(resultsTest.title);
});
it(`should render a <ResultsListItem /> with the correct post domain`, () => {
expect(wrapper.text()).toContain(resultsTest.domain);
});
it(`should render a <ResultsListItem /> with the correct post timestamp`, () => {
expect(wrapper.text()).toContain(moment.unix(resultsTest.date).format(' h:mmA MMMM Do, YYYY'));
});
it(`should render a <ResultsListItem /> with the correct link to the post comments`, () => {
expect(wrapper.text()).toContain(`${resultsTest.comments} comments`);
});
});
|
javascript
| 19 | 0.645902 | 127 | 35.62 | 50 |
starcoderdata
|
public void Connect(int connectTimeout, int retries = 0) {
Exception exception = null;
for (int i = 0; i != retries + 1; i++)
try {
_connectWaitHandle.Reset();
exception = null;
if (connectTimeout < 1) {
_socket.Connect(_remoteEP);
_connectWaitHandle.Set();
} else {
//Connect async to the remote endpoint.
_socket.BeginConnect(_remoteEP, ConnectCallback, _socket);
//Use a timeout to connect.
_connectWaitHandle.WaitOne(connectTimeout, false);
if (!_socket.Connected)
throw new Exception("Connecting to the server timed out.");
}
break;
} catch (Exception ex) {
//Wait for the end connect call.
//_connectWaitHandle.WaitOne(connectTimeout, false);
//Reuse the socket for re-trying to connect.
try {
if (_socket.Connected)
_socket.Disconnect(true);
} catch {
//Ignore.
}
_socket = new Socket(_socket.AddressFamily, _socket.SocketType, _socket.ProtocolType);
exception = ex;
}
_connectWaitHandle.Set();
if (exception != null) throw exception;
}
|
c#
| 16 | 0.420219 | 106 | 40.153846 | 39 |
inline
|
const Discord = require("discord.js");
var TOKEN = process.env.TOKEN;
module.exports.run = async (client,message,args) => {
if (message.author.id !== "314165916264955904")return;
message.channel.send('Restarting...')
client.destroy()
.then(() => client.login(TOKEN));
}
module.exports.help = {
name: "restart"
}
|
javascript
| 11 | 0.627507 | 54 | 17.388889 | 18 |
starcoderdata
|
<?php
/**
* Copyright (C) 2018 - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the MIT license.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require_once __DIR__ . "/src/initapp.php";
$container->logger->addInfo("Hello World");
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
$app->get('/', function (Request $request, Response $response, array $args) {
$this->logger->addInfo("Opened Index page");
$newResponse = $response->withJson([
"version" => "1.0.0",
"status" => "running",
]);
return $newResponse;
});
$app->post('/jobs/add', function (Request $request, Response $response) {
$this->logger->addInfo("Adding a job");
$payload = $request->getParsedBody();
$job_id = $this->jobs->addJob($payload);
$newResponse = $response->withJson([
"status" => "OK",
"job_id" => $job_id
]);
return $newResponse;
});
//Get the job status for a specific job
$app->get('/jobs/status/{id}', function (Request $request, Response $response, array $args) {
$job_id = (int) $args['id'];
$status = $this->jobs->getStatus($job_id);
$status_code = 200;
if(!$status){
$status_code = 404;
$status = 'Job not found';
}
$status = [
'status' => $status_code,
'data' => $status,
];
$newResponse = $response->withJson($status, $status_code);
return $newResponse;
});
//Get the job status for all jobs in the queue
$app->get('/jobs/status', function (Request $request, Response $response) {
$status = $this->jobs->getJobsCount();
$status = [
'status' => 200,
'data' => $status,
];
$newResponse = $response->withJson($status);
return $newResponse;
});
//Middleware - will be used later for auth
$app->add(function ($request, $response, $next) {
//$response->getBody()->write('BEFORE');
$response = $next($request, $response);
//$response->getBody()->write('AFTER');
return $response;
});
$app->run();
|
php
| 15 | 0.607622 | 93 | 22.333333 | 99 |
starcoderdata
|
<?php
namespace AwemaPL\Task\Common\Exceptions;
use AwemaPL\BaseJS\Exceptions\PublicException;
class StatusException extends PublicException
{
const ERROR_UNIQUE_TASK = 'ERROR_UNIQUE_TASK';
}
|
php
| 6 | 0.785714 | 50 | 20 | 10 |
starcoderdata
|
void
stordb_coro_create (const v8::FunctionCallbackInfo<v8::Value> &args) {
V8SCOPE(args);
// isolate
v8::Isolate *iso = args.GetIsolate();
// coro struct wrap
coro_wrap *wrap = NULL;
if (1 != args.Length() || !args[0]->ToObject()->IsCallable()) {
V8THROW("coro.create expects a function");
return;
}
// coro v8 wrap
v8::Handle<v8::ObjectTemplate> co = v8::ObjectTemplate::New(iso);
// coro ctx
coro_context *ctx = NULL;
// alloc
ctx = (struct coro_context *) malloc(sizeof(struct coro_context *));
wrap = (struct coro_wrap *) malloc(sizeof(struct coro_wrap *));
// create context
coro_create(ctx, coro_call, wrap, wrap->stack.sptr, wrap->stack.ssze);
// alloc stack
coro_stack_alloc(&wrap->stack, 1);
// init
wrap->ctx = ctx;
// attach callback
wrap->fn = v8::Handle<v8::Function>::Cast(args[0]->ToObject());
// set field count
co->SetInternalFieldCount(1);
// instance
v8::Handle<v8::Object> instance = co->NewInstance();
// set internal wrap
instance->SetInternalField(0, V8EXTERNAL(wrap));
V8RETURN(instance);
}
|
c++
| 13 | 0.645662 | 72 | 21.833333 | 48 |
inline
|
#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from qr_stamp.stampper import StampBot
import threading
from ttkthemes import ThemedTk
import os
from sys import platform
from qr_stamp.msgs import error_msgs as err
def csv_chooser_event():
text = csv_path_field.get()
selected = askopenfilename()
if not len(selected) == 0:
csv_path_field.delete(first=0, last=len(text))
csv_path_field.insert(0, selected)
progress_bar["value"] = 0
def run():
progress_bar["value"] = 0
bot.stamp_ratio = float(scale.get())
bot.csv_path = csv_path_field.get()
bot.print = pop_up
t1 = threading.Thread(target=bot.stamp_all, args=[])
t1.start()
def preview():
width = root.winfo_screenwidth()*0.3
height = width*1.4142
progress_bar["value"] = 0
bot.stamp_ratio = float(scale.get())
bot.csv_path = csv_path_field.get()
bot.print = pop_up
img = bot.preview(size=int(height))
if img is None:
return
preview_window = tk.Toplevel(root)
preview_window.title("Preview")
# sets the geometry of toplevel
width = root.winfo_screenwidth()*0.3
height = width*1.4142
if not height < root.winfo_screenheight():
pass
preview_window.geometry("{}x{}".format(int(width), int(height)))
preview_window.configure(bg='#fafafa')
panel = ttk.Label(preview_window, text="")
panel.pack(side="bottom", fill="both", expand="yes")
panel.configure(image=img)
panel.image = img
def pop_up(text, parent=None):
if parent is None:
parent = root
window = tk.Toplevel(parent)
window.geometry("400x200")
window.configure(bg='#fafafa')
window.title("Message")
label = ttk.Label(window, text=text)
label.grid(column=0, row=0, pady=20, padx=20)
run_btn = ttk.Button(window, text="OK", command=window.destroy, width=20)
run_btn.grid(column=0, row=1, pady=20, padx=20)
if __name__ == '__main__':
root = ThemedTk(theme="adapta")
width = 560
height = 215
root.geometry('{}x{}'.format(width, height))
root.title("QR Stamp Tool")
root.option_add('*Dialog.msg.font', 'Helvetica 11')
root.configure(bg='#fafafa')
if platform == "win32":
dir_path = os.path.dirname(os.path.realpath(__file__))
root.wm_iconbitmap(dir_path+'/icon.ico')
left = ttk.Frame(root)
left.grid(column=0, row=0)
fileschooser_frame = ttk.Frame(left)
fileschooser_frame.grid(column=0, row=0, padx=10)
csv_chooser_frame = ttk.Frame(fileschooser_frame)
csv_chooser_frame.grid(column=0, row=0, padx=10, pady=20)
scale_frame = ttk.Frame(left)
scale_frame.grid(column=0, row=1, padx=10, pady=10)
buttons_frame = ttk.Frame(left)
buttons_frame.grid(column=0, row=2, padx=10)
# stamp details
csv_label = ttk.Label(csv_chooser_frame, text="Choose CSV file: ")
csv_label.grid(column=0, row=0)
csv_path_field = ttk.Entry(csv_chooser_frame, width=40)
csv_path_field.grid(column=0, row=1)
csv_browse = ttk.Button(csv_chooser_frame, text="Browse",
command=csv_chooser_event)
csv_browse.grid(column=1, row=1, padx=10)
# scale
scale_label = ttk.Label(scale_frame, text="scale stamp:")
scale_label.grid(column=0, row=0)
scale = ttk.Scale(scale_frame, from_=0.05, to=0.2, length=300)
scale.set(0.15)
scale.grid(column=1, row=0, padx=10)
# run
run_btn = ttk.Button(buttons_frame, text="Run",
command=run, width=20)
run_btn.grid(column=0, row=0, padx=10, pady=10)
# preview
preview_btn = ttk.Button(buttons_frame, text="Preview",
command=preview, width=20)
preview_btn.grid(column=1, row=0, padx=10, pady=10)
# progress bar
progress_bar = ttk.Progressbar(
left, orient="horizontal", length=width, mode='determinate')
progress_bar.grid(column=0, row=4, padx=0, pady=10)
bot = StampBot(progress_bar=progress_bar)
root.mainloop()
|
python
| 12 | 0.640556 | 77 | 29.81203 | 133 |
starcoderdata
|
public static String getFromPool(String value) {
if (value == null) return null;
if (value.length() == 0) return EMPTY;
final long hash = StringHash.calc(value);
String reused = (String) myReusableStrings.get(hash);
if (reused != null) return reused;
// new String() is required because value often is passed as substring which has a reference to original char array
// see {@link String.substring(int, int} method implementation.
//noinspection RedundantStringConstructorCall
reused = new String(value);
myReusableStrings.put(hash, reused);
return reused;
}
|
java
| 8 | 0.707438 | 119 | 42.285714 | 14 |
inline
|
using KuiLang.Compiler.Symbols;
using KuiLang.Diagnostics;
using KuiLang.Semantic;
using KuiLang.Syntax;
using System.Linq;
using static KuiLang.Syntax.Ast.Expression;
using static KuiLang.Syntax.Ast.Expression.Literal;
using static KuiLang.Syntax.Ast.Statement.Definition;
namespace KuiLang.Compiler
{
public class SymbolTreeBuilder : AstVisitor
{
readonly DiagnosticChannel _diagnostics;
public SymbolTreeBuilder( DiagnosticChannel diagnostics )
{
_diagnostics = diagnostics;
}
ISymbol _current = null!;
public override ProgramRootSymbol Visit( Ast ast )
{
var root = new ProgramRootSymbol( ast );
_current = root;
base.Visit( ast );
_current = null!;
return root;
}
// Definitions :
protected override object Visit( MethodDeclaration method )
{
var current = (TypeSymbol)_current;
var symbol = new MethodSymbol( current, method );
current.Add( symbol );
_current = symbol;
base.Visit( method );
_current = symbol.Parent;
return default!;
}
protected override object Visit( TypeDeclaration type )
{
var current = (ProgramRootSymbol)_current;
var symbol = new TypeSymbol( current, type );
current.Add( symbol );
_current = symbol;
base.Visit( type );
_current = symbol.Parent;
return default!;
}
protected override object Visit( FieldDeclaration field )
{
if( _current is TypeSymbol type )
{
var symbol = new FieldSymbol( field, type );
type.Add( symbol );
_current = symbol;
symbol.InitValue = field.InitValue != null ? Visit( field.InitValue ) : null;
_current = symbol.Parent;
}
if( _current is ISymbolWithAStatement singleStatement )
{
_diagnostics.EmitDiagnostic( Diagnostic.FieldSingleStatement( field ) );
var symbol = new VariableSymbol( SingleOrMultiStatementSymbol.From( singleStatement ), null!, field );
singleStatement.Statement = symbol;
_current = symbol;
symbol.InitValue = field.InitValue != null ? Visit( field.InitValue ) : null;
_current = symbol.Parent.Value;
}
if( _current is StatementBlockSymbol block )
{
var symbol = new VariableSymbol( SingleOrMultiStatementSymbol.From( block ), block, field );
block.Statements.Add( symbol );
_current = symbol;
symbol.InitValue = field.InitValue != null ? Visit( field.InitValue ) : null;
_current = symbol.Parent.Value;
}
return default!;
}
// Statements:
protected override object Visit( Ast.Statement.Block statementBlock )
{
return base.Visit( statementBlock );
}
protected override object Visit( Ast.Statement.FieldAssignation assignation )
{
var symbol = new FieldAssignationStatementSymbol(
SingleOrMultiStatementSymbol.From( _current ),
assignation
);
var prev = _current;
_current = symbol;
symbol.NewFieldValue = Visit( assignation.NewFieldValue );
base.Visit( assignation );
_current = prev;
return default!;
}
protected override object Visit( Ast.Statement.If @if )
{
var symbol = new IfStatementSymbol( SingleOrMultiStatementSymbol.From( _current ), @if );
var prev = _current;
_current = symbol;
base.Visit( @if );
_current = prev;
return default!;
}
protected override object Visit( Ast.Statement.Return returnStatement )
{
var symbol = new ReturnStatementSymbol( SingleOrMultiStatementSymbol.From( _current ), returnStatement );
var prev = _current;
_current = symbol;
symbol.ReturnedValue = returnStatement.ReturnedValue != null ? Visit( returnStatement.ReturnedValue ) : null;
_current = prev;
return default!;
}
protected override object Visit( Ast.Statement.MethodCallStatement methodCallStatement )
{
var symbol = new MethodCallStatementSymbol( SingleOrMultiStatementSymbol.From( _current ), methodCallStatement );
var prev = _current;
_current = symbol;
symbol.MethodCallExpression = Visit( methodCallStatement.MethodCallExpression );
_current = prev;
return default!;
}
// Expressions:
protected override IExpressionSymbol Visit( Ast.Expression expression ) => (IExpressionSymbol)base.Visit( expression );
protected override MethodCallExpressionSymbol Visit( MethodCall methodCall )
{
var prev = _current;
var expr = new MethodCallExpressionSymbol( _current, methodCall );
_current = expr;
expr.Arguments = methodCall.Arguments.Select( Visit ).ToList();
_current = prev;
return expr;
}
protected override FieldReferenceExpressionSymbol Visit( FieldReference variable )
=> new FieldReferenceExpressionSymbol( _current, variable );
protected override IExpressionSymbol Visit( Literal literal ) => (IExpressionSymbol)base.Visit( literal );
protected override NumberLiteralSymbol Visit( Number constant ) => new( _current, constant );
protected override AddExpressionSymbol Visit( Operator.Add add )
{
var prev = _current;
var expr = new AddExpressionSymbol( _current, add);
_current = expr;
expr.Left = Visit( add.Left );
expr.Right = Visit( add.Right );
_current = prev;
return expr;
}
protected override DivideExpressionSymbol Visit( Operator.Divide divide )
{
var prev = _current;
var expr = new DivideExpressionSymbol( _current, divide );
_current = expr;
expr.Left = Visit( divide.Left );
expr.Right = Visit( divide.Right );
_current = prev;
return expr;
}
protected override MultiplyExpressionSymbol Visit( Operator.Multiply multiply )
{
var prev = _current;
var expr = new MultiplyExpressionSymbol( _current, multiply );
_current = expr;
expr.Left = Visit( multiply.Left );
expr.Right = Visit( multiply.Right );
_current = prev;
return expr;
}
protected override SubtractExpressionSymbol Visit( Operator.Subtract subtract )
{
var prev = _current;
var expr = new SubtractExpressionSymbol( _current, subtract );
_current = expr;
expr.Left = Visit( subtract.Left );
expr.Right = Visit( subtract.Right );
_current = prev;
return expr;
}
}
}
|
c#
| 19 | 0.574442 | 127 | 35.791045 | 201 |
starcoderdata
|
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AdamsLair.WinForms.PropertyEditing;
using AdamsLair.WinForms.PropertyEditing.Editors;
using Duality;
using Duality.Resources;
using Duality.Editor.Controls.PropertyEditors;
namespace Duality.Editor.Plugins.Base.PropertyEditors
{
public class TextureContentPropertyEditor : ResourcePropertyEditor
{
public TextureContentPropertyEditor()
{
this.Hints = HintFlags.None;
this.HeaderHeight = 0;
this.HeaderValueText = null;
this.Expanded = true;
}
}
}
|
c#
| 11 | 0.793165 | 67 | 22.166667 | 24 |
starcoderdata
|
namespace Pact.Palantir.Cache
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Tangle.Net.Entity;
///
/// The TransactionCache interface.
///
public interface ITransactionCache
{
Task FlushAsync();
Task LoadTransactionsByAddressAsync(Address address);
Task SaveTransactionAsync(TransactionCacheItem item);
}
}
|
c#
| 8 | 0.761134 | 85 | 23.75 | 20 |
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 co.edu.uniandes.csw.fiestas.persistence;
import co.edu.uniandes.csw.fiestas.entities.ContratoEntity;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
* Clase que maneja la persistencia para Contrato. Se conecta a través del Entity
* Manager de javax.persistance con la base de datos SQL.
*
* @author mc.gonzalez15
*/
@Stateless
public class ContratoPersistence {
private static final Logger LOGGER = Logger.getLogger(ContratoPersistence.class.getName());
@PersistenceContext(unitName = "FiestasPU")
protected EntityManager em;
/**
* Buscar un contrato
*
* Busca si hay algun contrato asociado a un evento y con un ID específico
*
*
* @param id El ID del contrato buscado
* @return El contrato encontrado o null. Nota: Si existe una o más contratos
* devuelve siempre el primer que encuentra
*/
public ContratoEntity find(Long id) {
LOGGER.log(Level.INFO, "Consultando contrato con id={0}", id);
return em.find(ContratoEntity.class, id);
}
/**
* Buscar todos los contrato
*
* Busca todos los contratos del sistema
*
* @return Lista con todos los contratos.
*/
public List findAll() {
LOGGER.info("Consultando todos los contratos");
Query q = em.createQuery("select u from ContratoEntity u");
return q.getResultList();
}
/**
* Crear un contrato
*
* Crea una nuevo contrato con la información recibida en la entidad.
*
* @param entity La entidad que representa el nuevo contrato
* @return La entidad creada
*/
public ContratoEntity create(ContratoEntity entity) {
LOGGER.info("Creando un contrato nuevo");
em.persist(entity);
LOGGER.info("Contrato creado");
return entity;
}
/**
* Actualizar un contrato
*
* Actualiza la entidad que recibe en la base de datos
*
* @param entity La entidad actualizada que se desea guardar
* @return La entidad resultante luego de la acutalización
*/
public ContratoEntity update(ContratoEntity entity) {
LOGGER.log(Level.INFO, "Actualizando contrato con id={0}", entity.getId());
return em.merge(entity);
}
/**
* Eliminar un contrato
*
* Elimina el contrato asociada al ID que recibe
*
* @param id El ID del contrato que se desea borrar
*/
public void delete(Long id) {
LOGGER.log(Level.INFO, "Borrando contrato con id={0}", id);
ContratoEntity entity = em.find(ContratoEntity.class, id);
em.remove(entity);
}
}
|
java
| 10 | 0.64181 | 95 | 28.764706 | 102 |
starcoderdata
|
void ParticlePolisherMpi::run()
{
// Fit straight lines through all beam-induced translations
if (fitting_mode != NO_FIT)
fitMovementsAllMicrographs();
// Perform single-frame reconstructions to estimate dose-dependent B-factors
if (do_weighting)
calculateAllSingleFrameReconstructionsAndBfactors();
// Make a logfile in pdf format
if (node->isMaster())
generateLogFilePDF();
// Write out the polished particles
polishParticlesAllMicrographs();
// Now reconstruct with all polished particles: two independent halves, FSC-weighting of the sum of the two...
reconstructShinyParticlesAndFscWeight(1);
if (verb > 0)
std::cout << " done!" << std::endl;
}
|
c++
| 8 | 0.750742 | 111 | 27.125 | 24 |
inline
|
class FPD
{
public:
// The 3D mean shape vector of the FPD [x1,..,xn,y1,...yn,z1,...,zn]
cv::Mat_<double> mean_shape;
// Principal components or variation bases of the model,
cv::Mat_<double> princ_comp;
// Eigenvalues (variances) corresponding to the bases
cv::Mat_<double> eigen_values;
FPD(){;}
|
c
| 8 | 0.627273 | 70 | 22.642857 | 14 |
inline
|
<?php namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserLogoutApiController extends Controller {
public function __construct() {
}
public function index() {
return $this->save(request());
}
public function save(Request $request) {
//Auth::logout();
$token = $request->input('token', $request->header('token'));
if ($token) {
$user = User::firstByToken($token);
if ($user) {
$user->status = 'offline';
$user->channel_id = '';
$user->save();
return $this->success();
}
}
}
}
|
php
| 14 | 0.546405 | 69 | 22.181818 | 33 |
starcoderdata
|
using System;
using System.Windows.Input;
namespace CanvasTesting.Commands {
public class RelayCommand : ICommand {
private Action _command;
private Func _can_excecute;
public RelayCommand (Action command, Func canExcecute) {
_command = command;
_can_excecute = canExcecute;
}
public event EventHandler CanExecuteChanged {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute (object parameter) {
return _can_excecute.Invoke();
}
public void Execute (object parameter) {
_command.Invoke();
}
}
}
|
c#
| 12 | 0.596282 | 70 | 25.892857 | 28 |
starcoderdata
|
package dapper
import (
"io"
"github.com/dogmatiq/iago/must"
)
// visitPtr formats values with a kind of reflect.Ptr.
func (vis *visitor) visitPtr(w io.Writer, v Value) {
if v.Value.IsNil() {
vis.renderNil(w, v)
return
}
if v.IsAmbiguousType() {
must.WriteByte(w, '*')
}
elem := v.Value.Elem()
vis.Write(
w,
Value{
Value: elem,
DynamicType: elem.Type(),
StaticType: v.StaticType,
IsAmbiguousDynamicType: v.IsAmbiguousDynamicType,
IsAmbiguousStaticType: v.IsAmbiguousStaticType,
IsUnexported: v.IsUnexported,
},
)
}
|
go
| 12 | 0.621931 | 54 | 17.515152 | 33 |
starcoderdata
|
using System;
using LinCms.Entities;
namespace LinCms.Blog.Notifications
{
public class CommentEntry:EntityDto
{
public Guid? RespId { get; set; }
public string Text { get; set; }
}
}
|
c#
| 8 | 0.65272 | 45 | 18.916667 | 12 |
starcoderdata
|
@Test
public void checkIfDiscardFallbackActionIsTriggered() {
final String topic = "test";
final Map<String, String> configs = new HashMap<>();
configs.put(BucketPriorityConfig.TOPIC_CONFIG, topic);
configs.put(BucketPriorityConfig.BUCKETS_CONFIG, "B1, B2");
configs.put(BucketPriorityConfig.ALLOCATION_CONFIG, "70%, 30%");
configs.put(BucketPriorityConfig.FALLBACK_PARTITIONER_CONFIG,
DiscardPartitioner.class.getName());
BucketPriorityPartitioner partitioner = new BucketPriorityPartitioner();
partitioner.configure(configs);
// Create two partitions to make things a little bit more interesting
PartitionInfo partition0 = new PartitionInfo(topic, 0, null, null, null);
PartitionInfo partition1 = new PartitionInfo(topic, 1, null, null, null);
List<PartitionInfo> partitions = List.of(partition0, partition1);
Cluster cluster = createCluster(partitions);
try (MockProducer<String, String> producer = new MockProducer<>(cluster,
true, partitioner, new StringSerializer(), new StringSerializer())) {
int counter = 0;
ProducerRecord<String, String> record = null;
List<Integer> chosenPartitions = new ArrayList<>();
// Produce 10 different records where 5 of them will
// be sent using the key "B1" and thus need to end up
// in the partition 0. The other 5 records will be sent
// without a key and thus... will be discarded.
for (int i = 0; i < 10; i++) {
if (++counter > 5) {
record = new ProducerRecord<String, String>(topic, "B1", "value");
} else {
record = new ProducerRecord<String, String>(topic, null, "value");
}
producer.send(record, (metadata, exception) -> {
// Ignoring partition -1 because this means
// not leveraging any available partition.
if (metadata.partition() != -1) {
chosenPartitions.add(metadata.partition());
}
});
}
// The expected output is:
// - The first 5 records need to be discarded
// - The last 5 records need to end up on partition 0 (B1)
assertEquals(List.of(0, 0, 0, 0, 0), chosenPartitions);
}
}
|
java
| 19 | 0.585218 | 86 | 45.735849 | 53 |
inline
|
package com.github.stcarolas.gittemplateloader;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
import com.github.jknack.handlebars.io.AbstractTemplateLoader;
import com.github.jknack.handlebars.io.TemplateSource;
import org.eclipse.jgit.api.Git;
import io.vavr.control.Try;
import lombok.Builder;
import lombok.val;
import lombok.extern.log4j.Log4j2;
@Builder
@Log4j2
public class GitTemplateLoader extends AbstractTemplateLoader {
private final String url;
private final UrlType urlType;
private final String id = UUID.randomUUID().toString();
@Override
public TemplateSource sourceAt(String filename) throws IOException {
val source = getDirectory()
.map(
dir -> {
return GitTemplateSource.builder()
.directory(dir)
.filename(filename)
.build();
}
);
if (source.isPresent()) {
return source.get();
}
return null;
}
public Optional getDirectory() {
val directory = new File("/tmp/enki/" + id);
if (directory.exists()) {
return Optional.of(directory);
}
directory.mkdirs();
return Try.of(
() -> {
Git.cloneRepository()
.setURI(url)
.setDirectory(directory)
.setTransportConfigCallback(new DefaultTransportConfigCallback())
.call();
return directory;
}
)
.onFailure(error -> log.error("error: {}", error))
.toOptional();
}
}
|
java
| 17 | 0.711934 | 70 | 23.711864 | 59 |
starcoderdata
|
<?php
return [
'develop' => 'ZKTecoの歴史',
'culture' => 'ZKTecoの文化',
'Team' => 'ZKTecoのチーム',
'team_des' => '夢のため、様々な分野の専門家が一緒にここに来て、ZKTecoのコアチームを形成しています',
'company_profile' => '会社概要',
'msg_err' => 'メッセージフォーマットエラー.',
'main_business' => '主な事業',
'application_area' => '応用分野',
'win_win' => 'Win - Winの関係',
'cooperative_styles'=> '多様な協力',
'core_technology' => '最先端の技術',
'honor' => 'ZKtecoの成果',
'quality_manage' => 'ZKteco品質管理',
'recrui' => 'メンバー募集',
'customer' => 'お客様',
'next1' => '次ページへ',
'prev1' => '前ページへ',
'duty' => '会社責任',
];
|
php
| 5 | 0.533997 | 64 | 21.269231 | 26 |
starcoderdata
|
using System.Collections.Generic;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
namespace Primavera.Extensibility.Wizard
{
public class PRIExtensibilityEx : IWizard
{
#region private objects
private int i = 1;
private string Name { get; set; }
#endregion
#region public methods
// This method is called before opening any item that
// has the OpenInEditor attributes.
public void BeforeOpeningFile(ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(Project project)
{
}
// This method is only called for item templates,
// not for project templates.
public void ProjectItemFinishedGenerating(ProjectItem projectItem)
{
// Add the module reference..,
if (this.Name == "PriCustomForm.cs" || this.Name == "PriCustomForm.vb")
{
// Add the module reference..,
WizardHelper.AddModuleReference(projectItem.ContainingProject, "Primavera.Extensibility.CustomForm");
//WizardHelper.AddModuleReference(projectItem.ContainingProject, "DevExpress.Utils.v18.1");
}
else
{
WizardHelper.AddModuleReference(projectItem.ContainingProject, "Primavera.Extensibility.CustomCode");
}
}
// This method is called after the project is created.
public void RunFinished()
{
}
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
}
// This method is only called for item templates,
// not for project templates.
public bool ShouldAddProjectItem(string filePath)
{
this.Name = filePath;
return true;
}
#endregion
}
}
|
c#
| 14 | 0.6004 | 117 | 31.306452 | 62 |
starcoderdata
|
<?php
/*
Plugin Name: DC - Facebook Like Box Popup (Increase Facebook Fans)
Version: 1.1
Description: This WordPress plugin helps you add Facebook Fans by popping up a window with a Facebook Like box.
Contributors: dattardwp-21
Author URI: https://www.collectiveray.com
Author: CollectiveRay
Donate link: https://www.collectiveray.com/joomla-25-and-joomla-3-modules/75-donate-a-beer
Tags: wordpress, facebook, like, popin, responsive
Requires at least: 3.0.1
Tested up to: 4.3
Stable tag: 4.3
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
if(!defined('WP_FACEBOOK_POPUP_URL'))
define('WP_FACEBOOK_POPUP_URL',WP_PLUGIN_URL.'/dc-facebook-like-box-popup-increase-facebook-fans');
require_once (dirname(__FILE__).'/settings.php');
require_once (dirname(__FILE__).'/controls.php');
require_once (dirname(__FILE__).'/footer.php');
/* Begin MCE Button */
add_action('admin_enqueue_scripts', 'wp_facebook_popup_admin_enqueue_scripts');
function wp_facebook_popup_admin_enqueue_scripts() {
wp_enqueue_style('wp-facebook-popup', WP_FACEBOOK_POPUP_URL.'/css/mce.css');
}
add_action('init', 'wp_facebook_popup_admin_head');
function wp_facebook_popup_admin_head() {
if(!current_user_can('edit_posts') && !current_user_can('edit_pages')) {
return;
}
if('true' == get_user_option('rich_editing')) {
add_filter('mce_external_plugins', 'wp_facebook_popup_mce_external_plugins');
add_filter('mce_buttons', 'wp_facebook_popup_mce_buttons');
}
}
function wp_facebook_popup_mce_external_plugins($plugin_array) {
$plugin_array['wp_facebook_popup'] = WP_FACEBOOK_POPUP_URL.'/js/mce.js';
return $plugin_array;
}
function wp_facebook_popup_mce_buttons($buttons) {
array_push($buttons, 'wp_facebook_popup');
return $buttons;
}
/* End MCE Button */
?>
|
php
| 11 | 0.732207 | 167 | 38.08 | 50 |
starcoderdata
|
#include "rtkTest.h"
#include "rtkCudaGradientImageFilter.h"
#include "itkImageFileReader.h"
#include "itkConstantBoundaryCondition.h"
/**
* \file rtkcudagradientimagefiltertest.cxx
*
* \brief Functional test for gradient computation
*
*
* \author
*/
int main(int argc, char* argv[] )
{
constexpr unsigned int Dimension = 3;
using PixelType = float;
using VectorPixelType = itk::CovariantVector<PixelType, Dimension>;
using ImageType = itk::CudaImage<PixelType, Dimension>;
using VectorImageType = itk::CudaImage<VectorPixelType, Dimension>;
using CudaGradientImageFilterType = rtk::CudaGradientImageFilter<ImageType, float, VectorImageType>;
auto CudaGradientImageFilter = CudaGradientImageFilterType::New();
auto BoundaryCondition = new itk::ConstantBoundaryCondition
CudaGradientImageFilter->ChangeBoundaryCondition(BoundaryCondition);
auto FileReader = itk::ImageFileReader
FileReader->SetFileName(argv[1]);
auto InputVolume = FileReader->GetOutput();
InputVolume->Update();
CudaGradientImageFilter->SetInput(InputVolume);
CudaGradientImageFilter->Print(std::cout);
try
{
CudaGradientImageFilter->Update();
}
catch (itk::ExceptionObject &EO)
{
EO.Print(std::cout);
return EXIT_FAILURE;
}
auto FileWriter = itk::ImageFileWriter
FileWriter->SetInput(CudaGradientImageFilter->GetOutput());
FileWriter->SetFileName("OUTPUT.nrrd");
try
{
FileWriter->Update();
}
catch (itk::ExceptionObject& EO)
{
EO.Print(std::cout);
return EXIT_FAILURE;
}
std::cout << "\n\nTest PASSED! " << std::endl;
return EXIT_SUCCESS;
}
|
c++
| 11 | 0.730244 | 102 | 24.5 | 66 |
starcoderdata
|
from numpy import expand_dims
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
dir = "/home/kittipong/dataset/Color/"
i = 15
img_data = os.listdir(dir)
for k in range(len(img_data)):
img = cv2.imread('/home/kittipong/dataset/Color/color_image'+str(k)+'.png')
file1 = open("/home/kittipong/dataset/label/color_image"+str(k)+".txt","r")
label = file1.read()
data = img_to_array(img)
# expand dimension to one sample
samples = expand_dims(data, 0)
# create image data augmentation generator
datagen = ImageDataGenerator(brightness_range=[0.2,1.0])
# prepare iterator
it = datagen.flow(samples, batch_size=1)
for j in range(9):
batch = it.next()
image = batch[0].astype('uint8')
cv2.imwrite('/home/kittipong/dataset/augment/color_image'+str(i)+'.png', image)
f= open("/home/kittipong/dataset/label/color_image"+str(i)+'.txt',"w")
f.write(label)
f.close()
i=i+1
file1.close()
|
python
| 13 | 0.699921 | 87 | 35.114286 | 35 |
starcoderdata
|
classes.__indexes__.m = {
mask: [
classes.c.cairocontext
],
masksurface: [
classes.c.cairocontext
],
moveto: [
classes.c.cairocontext,
classes.h.harupage,
classes.s.swfdisplayitem,
classes.s.swffill,
classes.s.swftext
],
merge: [
classes.c.cairofontoptions,
classes.s.solrdocument,
classes.s.solrinputdocument,
classes.t.threaded
],
multiply: [
classes.c.cairomatrix
],
markdirty: [
classes.c.cairosurface
],
markdirtyrectangle: [
classes.c.cairosurface
],
modify: [
classes.c.collection,
classes.d.datetime,
classes.d.datetimeimmutable
],
makerequest: [
classes.e.eventhttpconnection
],
memcmp: [
classes.f.ffi
],
memcpy: [
classes.f.ffi
],
memset: [
classes.f.ffi
],
magnifyimage: [
classes.g.gmagick,
classes.i.imagick
],
mapimage: [
classes.g.gmagick,
classes.i.imagick
],
medianfilterimage: [
classes.g.gmagick,
classes.i.imagick
],
minifyimage: [
classes.g.gmagick,
classes.i.imagick
],
modulateimage: [
classes.g.gmagick,
classes.i.imagick
],
motionblurimage: [
classes.g.gmagick,
classes.i.imagick
],
measuretext: [
classes.h.harufont,
classes.h.harupage
],
movetextpos: [
classes.h.harupage
],
movetonextline: [
classes.h.harupage
],
move: [
classes.h.hw_api,
classes.s.sdo_sequence,
classes.s.swfdisplayitem
],
mimetype: [
classes.h.hw_api_content
],
mattefloodfillimage: [
classes.i.imagick
],
mergeimagelayers: [
classes.i.imagick
],
montageimage: [
classes.i.imagick
],
morphimages: [
classes.i.imagick
],
morphology: [
classes.i.imagick
],
mosaicimages: [
classes.i.imagick
],
matte: [
classes.i.imagickdraw
],
memoryusage: [
classes.j.judy
],
maxtimems: [
classes.m.mongocursor
],
more_results: [
classes.m.mysqli,
classes.m.mysqli_stmt
],
multi_query: [
classes.m.mysqli
],
moreresults: [
classes.m.mysqlnduhconnection
],
mapphar: [
classes.p.phar
],
mount: [
classes.p.phar
],
mungserver: [
classes.p.phar
],
mkdir: [
classes.s.streamwrapper
],
multcolor: [
classes.s.swfdisplayitem
],
movepen: [
classes.s.swfshape
],
movepento: [
classes.s.swfshape
],
metasearch: [
classes.t.tokyotyrantquery
],
movetoattribute: [
classes.x.xmlreader
],
movetoattributeno: [
classes.x.xmlreader
],
movetoattributens: [
classes.x.xmlreader
],
movetoelement: [
classes.x.xmlreader
],
movetofirstattribute: [
classes.x.xmlreader
],
movetonextattribute: [
classes.x.xmlreader
],
match: [
classes.y.yaf_route_static
]
};
|
javascript
| 8 | 0.615742 | 33 | 15.345029 | 171 |
starcoderdata
|
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from what_apps.do.models import Task
from what_apps.social.models import DrawAttention
T = ContentType.objects.get_for_model(Task)
def get_messages_for_user(user):
'''
Takes a user, returns a sorted list of tuples where the first element is an unread message and the second element is the datetime of the message's creation
'''
#Tasks
#DrawAttentions to this user
#Messages pointed at this user
#We want all tasks..... #That this user has created, #Posted a message on, #Or had their attention drawn to (we know by comparing it to the queryset above) #so long as they have at least one message
tasks_with_messages = Task.objects.filter( \
Q(ownership__owner = user) | \
Q(messages__creator = user) | \
Q(notices__target__user = user),\
messages__isnull=False)\
.distinct()\
#TODO: Get the above queryset to exclude tasks which have only messages that have already been read by this user
messages = []
for task in tasks_with_messages:
for message in task.messages.exclude(read_by_users__creator = user).exclude(creator=user).distinct(): #All messages that this user hasn't read
messages.append( (message, message.created) )
sorted_message_list = sorted(messages, key=lambda n: n[1], reverse=True)
return sorted_message_list
|
python
| 14 | 0.56069 | 203 | 40.790698 | 43 |
starcoderdata
|
// ----------------------------------------------------------------------------
// Copyright (C) 2020 Apoapse
// Copyright (C) 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// For more information visit https://github.com/apoapse/
// And https://apoapse.space/
// ----------------------------------------------------------------------------
#include "stdafx.h"
#include "NetworkPayload.h"
#include "ByteUtils.hpp"
#include "Diagnostic.hpp"
#include "Maths.hpp"
NetworkPayload::NetworkPayload(const std::string& cmdShortName, std::vector data)
{
m_rawPayloadData = std::move(data);
WriteHeader(cmdShortName, m_rawPayloadData);
headerInfo = NetworkMessageHeader();
headerInfo->cmdShortName = cmdShortName;
headerInfo->payloadLength = (static_cast - headerLength);
}
void NetworkPayload::Insert(Range<std::array<byte, READ_BUFFER_SIZE>>& range, size_t length)
{
const size_t currentPayloadLength = std::min(std::min((length), static_cast range.size());
m_rawPayloadData.insert(m_rawPayloadData.end(), range.begin(), range.begin() + currentPayloadLength);
range.Consume(currentPayloadLength);
if (!headerInfo.has_value() && m_rawPayloadData.size() >= headerLength)
{
ReadHeader();
const size_t bytesLeft = BytesLeft();
if (range.size() > 0 && bytesLeft > 0)
Insert(range, std::min(range.size(), bytesLeft));
}
}
Range NetworkPayload::GetPayloadContent() const
{
ASSERT_MSG(BytesLeft() == 0, "Trying to access to the payload data while the payload is not complete yet");
Range range(m_rawPayloadData);
range.Consume(headerLength);
return range;
}
const std::vector NetworkPayload::GetRawData() const
{
return m_rawPayloadData;
}
UInt32 NetworkPayload::BytesLeft() const
{
if (headerInfo.has_value())
return static_cast - (m_rawPayloadData.size() - headerLength));
else
return std::max(static_cast - m_rawPayloadData.size()), (UInt32)1); // Make sure the size can never be to 0 in this particular case
}
void NetworkPayload::ReadHeader()
{
ASSERT(m_rawPayloadData.size() >= headerLength);
Range range(m_rawPayloadData);
headerInfo = NetworkMessageHeader();
{
headerInfo->cmdShortName = std::string(range.begin(), range.begin() + 2);
range.Consume(2);
}
{
headerInfo->payloadLength = FromBytes Endianness::AP_BIG_ENDIAN);
if (headerInfo->payloadLength > payloadMaxAllowedLength)
throw std::length_error("");
}
//range.Consume(sizeof(UInt32)); // Not needed since it's the last operatation on the temporary Range
}
void NetworkPayload::WriteHeader(const std::string& cmdShortName, std::vector data)
{
ASSERT(data.size() >= headerLength);
ASSERT_MSG(CanFit , "The vector provided is to big for its size to fit into a UInt32");
std::copy(cmdShortName.begin(), cmdShortName.end(), data.begin());
{
const UInt32 pyaloadContentSize = (static_cast - headerLength);
const auto payloadLength = ToBytes Endianness::AP_BIG_ENDIAN);
std::copy(payloadLength.begin(), payloadLength.end(), data.begin() + cmdShortName.size());
}
}
|
c++
| 13 | 0.692816 | 154 | 32.786408 | 103 |
starcoderdata
|
using UnityEngine;
using UnityEngine.EventSystems;
public class ButtonADMOB : MonoBehaviour, IPointerClickHandler
{
public ButtonAdmobType buttonType;
public void OnPointerClick(PointerEventData pointerEventData){
switch (buttonType){
case ButtonAdmobType.RewardBasedVideo:
FindObjectOfType
break;
case ButtonAdmobType.Interstitial:
FindObjectOfType
break;
}
}
}
public enum ButtonAdmobType
{
Interstitial,RewardBasedVideo
}
|
c#
| 14 | 0.78125 | 66 | 22.695652 | 23 |
starcoderdata
|
from tests.module import exposed
import moray
try:
# moray起動
moray.run('web', port=0, cmdline_args = ['--disable-http-cache', '--incognito'])
except Exception as e:
print(e)
|
python
| 9 | 0.633333 | 84 | 22.1 | 10 |
starcoderdata
|
#include "server.h"
sigset_t sig_mask;
void* sig_handler_thread(void* arg){
int* pipe = (int*)arg;
debug("Hello, I'm the handler thread!\n");
logger("[SIG-HANDLER] Started signal handler thread.\n");
while(true){
int sig;
int err = sigwait(&sig_mask, &sig);
if(err != 0){
errno = err;
perror("Error in sigwait");
return NULL;
}
switch (sig) {
// closing server immediately
case SIGINT:
case SIGQUIT:
mode = CLOSE_SERVER;
debug("\nReceived signal, closing server!\n");
logger("[SIG-HANDLER] Received signal to close server.\n");
// signaling to main thread
close(pipe[W_ENDP]);
pipe[W_ENDP] = -1;
return NULL;
// blocking new connections
case SIGHUP:
mode = REFUSE_CONN;
logger("[SIG-HANDLER] Received signal to refuse incoming connections.\n");
// signaling to main thread
close(pipe[W_ENDP]);
pipe[W_ENDP] = -1;
return NULL;
default: ;
}
}
return NULL;
}
int install_sig_handler(int* pipe, pthread_t* sig_handler_tid){
int err;
sigemptyset(&sig_mask);
sigaddset(&sig_mask, SIGINT);
sigaddset(&sig_mask, SIGQUIT);
sigaddset(&sig_mask, SIGHUP);
if((err = pthread_sigmask(SIG_BLOCK, &sig_mask, NULL)) != 0) {
errno = err;
return -1;
}
debug("Masked SIGINT, SIGQUIT and SIGHUP\n");
// Ignoring SIGPIPE
struct sigaction sig_act;
memset(&sig_act, 0, sizeof(sig_act));
sig_act.sa_handler = SIG_IGN;
if( (sigaction(SIGPIPE, &sig_act, NULL) == -1)){
perror("Error while trying to ignore SIGPIPE");
return -1;
}
debug("Ignored SIGPIPE\n");
// ------------ SIGHANDLER THREAD ------------ //
if( (err = pthread_create(sig_handler_tid, NULL, sig_handler_thread, pipe)) != 0) {
// perror("Error while creating sig_handler thread");
errno = err;
return -1;
}
return 0;
}
|
c
| 12 | 0.513795 | 90 | 25.333333 | 84 |
starcoderdata
|
#include "stdafx.h"
#include "zealot.h"
#include "zealotai.h"
using namespace graphic;
cZealot::cZealot()
: m_ai(NULL)
{
}
cZealot::~cZealot()
{
SAFE_DELETE(m_ai);
}
bool cZealot::Create(graphic::cRenderer &renderer)
{
RETV2(!__super::Create(renderer, common::GenerateId(), "zealot.fbx"), false);
m_ai = new cZealotBrain(this);
RETV2(!m_ai->Init(), false);
return true;
}
bool cZealot::Render(cRenderer &renderer
, const XMMATRIX &parentTm //= XMIdentity
, const int flags //= 1
)
{
__super::Render(renderer, parentTm, flags);
return true;
}
bool cZealot::Update(cRenderer &renderer, const float deltaSeconds)
{
__super::Update(renderer, deltaSeconds);
m_ai->Update(deltaSeconds);
return true;
}
|
c++
| 11 | 0.68603 | 78 | 14.717391 | 46 |
starcoderdata
|
<?php
namespace Poll\PollBundle\Entity;
use Poll\PollBundle\Common\Identified;
use Poll\PollBundle\Exception\IncompatibleClassException;
/**
* Rozhrani pro odpoved na otazku - spolecna cast
* @author jirkovoj
*/
interface Answer extends Identified {
/**
* Vrati respondenta
* @return Respondent
*/
public function getRespondent();
/**
* Nastavi respondenta
* @param Respondent $respondent
*/
public function setRespondent(Respondent $respondent);
/**
* Vrati otazku, ke ktere se tato odpoved vztahuje
* @return \Poll\PollBundle\Entity\Question
*/
public function getQuestion();
/**
* Metoda resi na zaklade konstanty potomka compatibleClass
* kontrolu, zda je predany datovy typ spravny (nejen Question,
* ale konkretni Question napr. TextQuestion).
* @param Question $question
* @return \Poll\PollBundle\Entity\Answer
* @throws \LogicException pokud trida/rozhrani, se kterou je odpoved kompatibilni, neexistuje
* @throws IncompatibleClassException otazka neni kompatibilni s touto odpovedi
*/
public function setQuestion(Question $question);
}
|
php
| 8 | 0.749778 | 95 | 25.209302 | 43 |
starcoderdata
|
def check_bingo(boards_marked, boards_with_bingo):
# find new bingo boards and update boards with bingo
count = 0
for b, board in enumerate(boards_marked):
if b in boards_with_bingo:
# already marked as bingo board
continue
hori = any(all(board[row : row + 5]) for row in range(0, 25, 5))
verti = any(all(board[col:25:5]) for col in range(5))
if verti or hori:
boards_with_bingo.append(b)
count += 1
return count > 0
|
python
| 14 | 0.586745 | 72 | 38.538462 | 13 |
inline
|
import gmpy2
import hashlib
import socketserver
import os,random,string
from hashlib import sha256
from Crypto.Util.number import bytes_to_long
from SECRET import FLAG
p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
a = 0
b = 7
xG = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
yG = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
h = 1
zero = (0,0)
G = (xG, yG)
kbits = 8
def add(p1, p2):
if p1 == zero:
return p2
if p2 == zero:
return p1
(p1x,p1y),(p2x,p2y) = p1,p2
if p1x == p2x and (p1y != p2y or p1y == 0):
return zero
if p1x == p2x:
tmp = (3 * p1x * p1x + a) * gmpy2.invert(2 * p1y , p) % p
else:
tmp = (p2y - p1y) * gmpy2.invert(p2x - p1x , p) % p
x = (tmp * tmp - p1x - p2x) % p
y = (tmp * (p1x - x) - p1y) % p
return (int(x),int(y))
def mul(n, p):
r = zero
tmp = p
while 0 < n:
if n & 1 == 1:
r = add(r,tmp)
n, tmp = n >> 1, add(tmp,tmp)
return r
def sha256(raw_message):
return hashlib.sha256(raw_message).hexdigest().encode()
def _sha256(raw_message):
return bytes_to_long(hashlib.sha256(raw_message).digest())
class Task(socketserver.BaseRequestHandler):
def proof_of_work(self):
random.seed(os.urandom(8))
proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)]).encode()
digest = sha256(proof)
self.request.send(b"sha256(XXXX+%b) == %b\n" % (proof[4:],digest))
self.request.send(b'Give me XXXX:')
x = self.request.recv(10)
x = x.strip()
if len(x) != 4 or sha256(x+proof[4:]) != digest:
return False
return True
def recvall(self, sz):
try:
r = sz
res = ""
while r > 0:
res += self.request.recv(r).decode()
if res.endswith("\n"):
r = 0
else:
r = sz - len(res)
res = res.strip()
except:
res = ""
return res.strip("\n")
def dosend(self, msg):
self.request.sendall(msg)
def handle(self):
try:
if not self.proof_of_work():
return
dA = random.randrange(n)
Public_key = mul(dA, G)
self.dosend(str(Public_key).encode() + b'\n')
for _ in range(100):
self.dosend(b"Give me your message:\n")
msg = self.recvall(100)
hash = _sha256(msg.encode())
k = random.randrange(n)
kp = k % (2 ** kbits)
P = mul(k, G)
r_sig = P[0]
k_inv = gmpy2.invert(k, n)
s_sig = (k_inv * (hash + r_sig * dA)) % n
self.dosend(b"r = " + str(r_sig).encode() + b'\n')
self.dosend(b"s = " + str(s_sig).encode() + b'\n')
self.dosend(b"kp = " + str(kp).encode() + b'\n')
self.dosend(b"hash = " + str(hash).encode() + b'\n')
self.dosend(b"Give me dA\n")
private_key = self.recvall(300)
if int(private_key) == dA:
self.dosend(FLAG)
except:
self.dosend(b"Something error!\n")
self.request.close()
class ForkingServer(socketserver.ForkingTCPServer, socketserver.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = '0.0.0.0', 23333
server = ForkingServer((HOST, PORT), Task)
server.allow_reuse_address = True
server.serve_forever()
|
python
| 18 | 0.527311 | 104 | 29.274194 | 124 |
starcoderdata
|
def mae_metric(self, predictions):
"""
Return the MAE metrics based on predictions
:param predictions:
:return:
"""
y_true = self.test_corpus.Rating
y_hat = np.round(predictions, 0)
mae = mean_absolute_error(y_true, y_hat)
return mae
|
python
| 7 | 0.68254 | 45 | 22 | 11 |
inline
|
import collections
import logging
import enum
import tempfile
Proxy = collections.namedtuple("Proxy", "url login password")
AIOProxy = collections.namedtuple("_AIOProxy", "url auth")
class Response:
def __init__(self, content_descriptor=None, url_and_status=list()):
self.__logger = logging.getLogger("{}.{}".format(__name__, __class__.__name__))
self.__content_descriptor = None
self.__url_and_status = None
self.url_and_status = url_and_status
self.content_descriptor = content_descriptor
def __del__(self):
try:
self.__content_descriptor.close()
except Exception as e:
self.__logger.warning(e)
@property
def content_descriptor(self):
return self.__content_descriptor
@content_descriptor.setter
def content_descriptor(self, content_descriptor: tempfile.NamedTemporaryFile):
self.__content_descriptor = content_descriptor
self.__content_descriptor.seek(0)
@property
def url_and_status(self):
return self.__url_and_status
@url_and_status.setter
def url_and_status(self, url_and_status: list):
self.__url_and_status = url_and_status
@property
def requested_url(self):
try:
url, _ = self.url_and_status[0]
except Exception as e:
url = None
self.__logger.error(e)
finally:
return url
@property
def accessed_url(self):
try:
url, _ = self.url_and_status[-1]
except Exception as e:
url = None
self.__logger.error(e)
finally:
return url
class InstanceStatus(enum.Enum):
RESERVED = enum.auto()
AWALIABLE = enum.auto()
|
python
| 13 | 0.601925 | 87 | 25.757576 | 66 |
starcoderdata
|
//
// Created by http://krupke.cc on 8/17/17.
//
#ifndef TURNCOSTCOVER_APX_CONNECT_COMPONENT_MST_H
#define TURNCOSTCOVER_APX_CONNECT_COMPONENT_MST_H
#include "../../../problem_instance/solution/solution.h"
#include "component_graph.h"
#include "greedy_connect.h"
#include "path_to_cycle.h"
#include "component_edge.h"
#include
namespace turncostcover {
namespace apx {
namespace details {
class ComponentMst {
public:
ComponentMst(const IntegralSolution &integralSolution, Costs costs)
: solution_{integralSolution}, costs_{costs}
{
}
void Solve();
std::vector GetEdges() const { return mst_edges_; }
private:
using MstGraph = boost::adjacency_list<boost::vecS,
boost::vecS,
boost::undirectedS,
boost::property<boost::vertex_distance_t,
CostUnit>,
boost::property<boost::edge_weight_t,
CostUnit> >;
MstGraph CreateGraph(ComponentGraph &comp_graph);
std::vector
CalculateMst(MstGraph &mstGraph, ComponentGraph &comp_graph);
const IntegralSolution &solution_;
const Costs costs_;
std::vector mst_edges_;
};
}
}
}
#endif //TURNCOSTCOVER_APX_CONNECT_COMPONENT_MST_H
|
c
| 20 | 0.608195 | 82 | 26.892857 | 56 |
starcoderdata
|
//go:build js && wasm
// Package socket contains the logic to communicate with the server for the game via websocket communication
package socket
import (
"context"
"encoding/json"
"errors"
"sync"
"syscall/js"
"github.com/jacobpatterson1549/selene-bananas/game"
"github.com/jacobpatterson1549/selene-bananas/game/message"
"github.com/jacobpatterson1549/selene-bananas/ui"
)
type (
// Socket can be used to easily push and pull messages from the server.
Socket struct {
dom DOM
log Log
webSocket js.Value
user User
game Game
lobby Lobby
jsFuncs struct {
onOpen js.Func
onClose js.Func
onError js.Func
onMessage js.Func
}
}
// User is the state of the current user.
User interface {
// JWT gets the user's Java Web Token.
JWT() string
// Username gets the user's username.
Username() string
// Logout releases the use credentials from the browser.
Logout()
}
// Game is the game the user is currently playing.
Game interface {
// ID is the id for the game.
ID() game.ID
// Leave removes the user from his current game.
Leave()
// UpdateInfo updates the game for the specified message.
UpdateInfo(m message.Message)
}
// Lobby is used to display available games and give users a place to join a game from.
Lobby interface {
SetGameInfos(gameInfos []game.Info, username string)
}
// DOM interacts with the page.
DOM interface {
QuerySelector(query string) js.Value
QuerySelectorAll(document js.Value, query string) []js.Value
SetChecked(query string, checked bool)
NewWebSocket(url string) js.Value
EncodeURIComponent(str string) string
NewJsFunc(fn func()) js.Func
NewJsEventFunc(fn func(event js.Value)) js.Func
AlertOnPanic()
}
// Log is notify users about changes to the game.
Log interface {
Info(text string)
Warning(text string)
Error(text string)
Chat(text string)
}
)
// New creates a new socket.
func New(dom DOM, log Log, user User, game Game, lobby Lobby) *Socket {
s := Socket{
dom: dom,
log: log,
user: user,
game: game,
lobby: lobby,
}
return &s
}
// InitDom registers socket dom functions.
func (s *Socket) InitDom(ctx context.Context, wg *sync.WaitGroup) {
wg.Add(1)
go s.releaseJsFuncsOnDone(ctx, wg)
}
// releaseJsFuncsOnDone waits for the context to be done before releasing the event listener functions.
func (s *Socket) releaseJsFuncsOnDone(ctx context.Context, wg *sync.WaitGroup) {
defer s.dom.AlertOnPanic()
<-ctx.Done() // BLOCKING
s.releaseWebSocketJsFuncs()
wg.Done()
}
// releaseWebSocketJsFuncs releases the event listener functions.
func (s *Socket) releaseWebSocketJsFuncs() {
s.jsFuncs.onOpen.Release()
s.jsFuncs.onClose.Release()
s.jsFuncs.onError.Release()
s.jsFuncs.onMessage.Release()
}
// Connect establishes the websocket connection if it has not yet been established.
func (s *Socket) Connect(event js.Value) error {
if s.isOpen() {
return nil
}
f, err := ui.NewForm(s.dom.QuerySelectorAll, event)
if err != nil {
return err
}
url := s.webSocketURL(*f)
s.releaseWebSocketJsFuncs()
errC := make(chan error, 1)
s.jsFuncs.onOpen = s.dom.NewJsFunc(s.onOpen(errC))
s.jsFuncs.onClose = s.dom.NewJsEventFunc(s.onClose)
s.jsFuncs.onError = s.dom.NewJsFunc(s.onError(errC))
s.jsFuncs.onMessage = s.dom.NewJsEventFunc(s.onMessage)
s.webSocket = s.dom.NewWebSocket(url)
s.webSocket.Set("onopen", s.jsFuncs.onOpen)
s.webSocket.Set("onclose", s.jsFuncs.onClose)
s.webSocket.Set("onerror", s.jsFuncs.onError)
s.webSocket.Set("onmessage", s.jsFuncs.onMessage)
return <-errC
}
// getWebSocketURL creates a websocket url from the form, changing it's scheme and adding an access_token.
func (s *Socket) webSocketURL(f ui.Form) string {
switch f.URL.Scheme {
case "http":
f.URL.Scheme = "ws"
default:
f.URL.Scheme = "wss"
}
jwt := s.user.JWT()
f.Params.Add("access_token", jwt)
f.URL.RawQuery = f.Params.Encode(s.dom)
return f.URL.String()
}
// onMessage is called when the websocket opens.
func (s *Socket) onOpen(errC chan<- error) func() {
return func() {
s.dom.SetChecked("#has-websocket", true)
errC <- nil
}
}
// onMessage is called when the websocket is closing.
func (s *Socket) onClose(event js.Value) {
if reason := event.Get("reason"); !reason.IsUndefined() && len(reason.String()) != 0 {
s.log.Warning("left lobby: " + reason.String())
}
s.closeWebSocket()
}
// closeWebSocket releases the event listeners and does some dom cleanup.
func (s *Socket) closeWebSocket() {
s.webSocket.Set("onopen", nil)
s.webSocket.Set("onclose", nil)
s.webSocket.Set("onerror", nil)
s.webSocket.Set("onmessage", nil)
s.releaseWebSocketJsFuncs()
s.dom.SetChecked("#has-websocket", false)
s.dom.SetChecked("#hide-game", true)
s.dom.SetChecked("#tab-lobby", true)
}
// onMessage is called when the websocket encounters an unwanted error.
func (s *Socket) onError(errC chan<- error) func() {
return func() {
s.user.Logout()
errC <- errors.New("lobby closed")
}
}
// onMessage is called when the websocket receives a message.
func (s *Socket) onMessage(event js.Value) {
jsMessage := event.Get("data")
messageJSON := jsMessage.String()
var m message.Message
err := json.Unmarshal([]byte(messageJSON), &m)
if err != nil {
s.log.Error("unmarshalling message: " + err.Error())
return
}
switch m.Type {
case message.LeaveGame:
s.handleGameLeave(m)
case message.GameInfos:
s.lobby.SetGameInfos(m.Games, s.user.Username())
case message.PlayerRemove:
s.handlePlayerRemove(m)
case message.JoinGame, message.ChangeGameStatus, message.ChangeGameTiles, message.RefreshGameBoard:
s.handleInfo(m)
case message.SocketError:
s.log.Error(m.Info)
case message.SocketWarning:
s.log.Warning(m.Info)
case message.SocketHTTPPing:
s.httpPing()
case message.GameChat:
s.log.Chat(m.Info)
default:
s.log.Error("unknown message type received")
}
}
// Send delivers a message to the server via it's websocket.
func (s *Socket) Send(m message.Message) {
if !s.isOpen() {
s.log.Error("websocket not open")
return
}
if m.Game == nil {
var g game.Info
m.Game = &g
}
if m.Type != message.CreateGame { // all messages except CREATE are for a specific game
m.Game.ID = s.game.ID()
}
messageJSON, err := json.Marshal(m)
if err != nil {
s.log.Error("marshalling socket message to send: " + err.Error())
return
}
s.webSocket.Call("send", string(messageJSON))
}
// Close releases the websocket
func (s *Socket) Close() {
if s.isOpen() {
s.closeWebSocket() // removes onClose
s.webSocket.Call("close")
}
s.game.Leave()
}
// isOpen determines if the socket is defined and has a readyState of OPEN.
func (s *Socket) isOpen() bool {
return !s.webSocket.IsUndefined() &&
s.webSocket.Get("readyState").Int() == 1
}
// handleGameLeave leaves the game and logs any info text from the message.
func (s *Socket) handleGameLeave(m message.Message) {
s.game.Leave()
if len(m.Info) > 0 {
s.log.Info(m.Info)
}
}
// handlePlayerRemove closes the socket and logs any info text from the message.
func (s *Socket) handlePlayerRemove(m message.Message) {
s.Close()
if len(m.Info) > 0 {
s.log.Info(m.Info)
}
}
// handleInfo contains the logic for handling messages with types Info and GameJoin.
func (s *Socket) handleInfo(m message.Message) {
s.game.UpdateInfo(m)
if len(m.Info) > 0 {
s.log.Info(m.Info)
}
}
// httpPing submits the small ping form to keep the server's http handling active.
func (s *Socket) httpPing() {
pingFormElement := s.dom.QuerySelector("form.ping")
pingFormElement.Call("requestSubmit")
}
|
go
| 12 | 0.70664 | 108 | 25.684211 | 285 |
starcoderdata
|
package config
import (
"archive/tar"
"compress/gzip"
"io"
"net/http"
"os"
"strings"
C "github.com/Dreamacro/clash/constant"
log "github.com/sirupsen/logrus"
)
func downloadMMDB(path string) (err error) {
resp, err := http.Get("http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz")
if err != nil {
return
}
defer resp.Body.Close()
gr, err := gzip.NewReader(resp.Body)
if err != nil {
return
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
h, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return err
}
if !strings.HasSuffix(h.Name, "GeoLite2-Country.mmdb") {
continue
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, tr)
if err != nil {
return err
}
}
return nil
}
// Init prepare necessary files
func Init() {
// initial config.ini
if _, err := os.Stat(C.ConfigPath); os.IsNotExist(err) {
log.Info("Can't find config, create a empty file")
os.OpenFile(C.ConfigPath, os.O_CREATE|os.O_WRONLY, 0644)
}
// initial mmdb
if _, err := os.Stat(C.MMDBPath); os.IsNotExist(err) {
log.Info("Can't find MMDB, start download")
err := downloadMMDB(C.MMDBPath)
if err != nil {
log.Fatalf("Can't download MMDB: %s", err.Error())
}
}
}
|
go
| 12 | 0.630644 | 100 | 17.506849 | 73 |
starcoderdata
|
const dgraph = require("dgraph-js");
const grpc = require("grpc");
var request = require('request');
var config_fs_name = './config.json';
var axios = require('axios')
var fs = require('fs');
const bodyParser = require('body-parser');
var globalConfigFile = require(config_fs_name)
var config = globalConfigFile.designer;
config.grpcPort = globalConfigFile.persistent_storage.port;
config.HostIp = globalConfigFile.external_hostip;
config.brokerIp=globalConfigFile.coreservice_ip
config.brokerPort=globalConfigFile.broker.http_port
/*
creating grpc client for making connection with dgraph
*/
async function newClientStub() {
return new dgraph.DgraphClientStub(config.HostIp+":"+config.grpcPort, grpc.credentials.createInsecure());
}
// Create a client.
async function newClient(clientStub) {
return new dgraph.DgraphClient(clientStub);
}
// Drop All - discard all data and start from a clean slate.
/*async function dropAll(dgraphClient) {
const op = new dgraph.Operation();
op.setDropAll(true);
await dgraphClient.alter(op);
}*/
/*
create scheema for node
*/
async function setSchema(dgraphClient) {
const schema = `
attributes: [uid] .
domainMetadata: [uid] .
entityId: uid .
updateAction: string .
id: string .
isPattern: bool .
latitude: float .
longitude: float .
name: string .
type: string .
value: string .
`;
const op = new dgraph.Operation();
op.setSchema(schema);
await dgraphClient.alter(op);
}
/*
convert object domainmetadata data into string to store entity as single node
*/
async function resolveDomainMetaData(data) {
if ('domainMetadata' in data) {
var len=data.domainMetadata.length
for(var i=0;i < len; i++) {
if('value' in data.domainMetadata[i]) {
if(data.domainMetadata[i].type != 'global' && data.domainMetadata[i].type != 'stringQuery'){
data.domainMetadata[i].value=JSON.stringify(data.domainMetadata[i].value)
}
}
}
}
}
/*
convert object attributes data into string to store entity as single node
*/
async function resolveAttributes(data) {
if ('attributes' in data){
var length=data.attributes.length
for(var i=0;i < length; i++) {
if('type' in data.attributes[i]) {
if (data.attributes[i].type=='object')
data.attributes[i].value=JSON.stringify(data.attributes[i].value)
else {
data.attributes[i].value=data.attributes[i].value.toString()
}
}
}
}
}
/*
insert data into database
*/
async function createData(dgraphClient,ctx) {
const txn = dgraphClient.newTxn();
try {
const mu = new dgraph.Mutation();
mu.setSetJson(ctx);
const response = await txn.mutate(mu);
await txn.commit();
}
finally {
await txn.discard();
}
}
/*
send data to cloud broker
*/
async function sendData(contextEle) {
var updateCtxReq = {};
updateCtxReq.contextElements = [];
updateCtxReq.updateAction = 'UPDATE'
updateCtxReq.contextElements.push(contextEle)
await axios({
method: 'post',
url: 'http://'+config.brokerIp+':'+config.brokerPort+'/ngsi10/updateContext',
data: updateCtxReq
}).then( function(response){
if (response.status == 200) {
return response.data;
} else {
return null;
}
});
}
/*
convert string object into structure to register data into cloud broker
*/
async function changeFromDataToobject(contextElement) {
contextEle=contextElement['contextElements']
for (var ctxEle=0; ctxEle < contextEle.length; ctxEle=ctxEle+1) {
ctxEleReq=contextEle[ctxEle]
if('attributes' in ctxEleReq) {
for(var ctxAttr=0; ctxAttr<ctxEleReq.attributes.length ;ctxAttr=ctxAttr+1) {
if (ctxEleReq.attributes[ctxAttr].type=='object') {
const value=ctxEleReq.attributes[ctxAttr].value
ctxEleReq.attributes[ctxAttr].value=JSON.parse(value)
}
if (ctxEleReq.attributes[ctxAttr].type=='integer') {
const value=ctxEleReq.attributes[ctxAttr].value
ctxEleReq.attributes[ctxAttr].value=parseInt(value)
}
if (ctxEleReq.attributes[ctxAttr].type=='float') {
const value=ctxEleReq.attributes[ctxAttr].value
ctxEleReq.attributes[ctxAttr].value=parseFloat(value)
}
if (ctxEleReq.attributes[ctxAttr].type=='boolean') {
const value=ctxEleReq.attributes[ctxAttr].value
if(value=='false')
ctxEleReq.attributes[ctxAttr].value=false
else
ctxEleReq.attributes[ctxAttr].value=true
}
}
}
if ('domainMetadata' in ctxEleReq){
for(ctxdomain=0; ctxdomain<ctxEleReq.domainMetadata.length; ctxdomain=ctxdomain+1) {
if ('value' in ctxEleReq.domainMetadata[ctxdomain]) {
if(ctxEleReq.domainMetadata[ctxdomain].type!='global'&& ctxEleReq.domainMetadata[ctxdomain].type!='stringQuery'){
const value=ctxEleReq.domainMetadata[ctxdomain].value
ctxEleReq.domainMetadata[ctxdomain].value=JSON.parse(value)
}
}
}
}
await sendData(ctxEleReq)
}
}
async function sendPostRequestToBroker(contextElement) {
await changeFromDataToobject(contextElement)
}
/*
Query for getting the registered node
*/
async function queryData(dgraphClient) {
const query = `{
contextElements(func: has(entityId)) {
{
entityId{
id
type
isPattern
}
attributes{
name
type
value
}
domainMetadata{
name
type
value
location
}
}
}
}`;
responseBody = await dgraphClient.newTxn().queryWithVars(query);
const responsData= responseBody.getJson();
//const responseObject=JSON.stringify(responsData)
const responseObject=responsData
sendPostRequestToBroker(responsData)
}
/*
main handler
*/
async function db(contextData) {
try{
const dgraphClientStub = await newClientStub();
const dgraphClient = await newClient(dgraphClientStub);
//await dropAll(dgraphClient);
if ('contextElements' in contextData) {
contextData=contextData['contextElements']
contextData=contextData[0]
}
await resolveAttributes(contextData)
await resolveDomainMetaData(contextData)
await createData(dgraphClient,contextData);
await dgraphClientStub.close();
}catch(err){
console.log('DB ERROR::',err);
}
}
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
});
async function queryForEntity() {
const dgraphClientStub = await newClientStub();
const dgraphClient = await newClient(dgraphClientStub);
await setSchema(dgraphClient);
await queryData(dgraphClient);
await dgraphClientStub.close();
}
module.exports={db,queryForEntity}
|
javascript
| 17 | 0.624207 | 117 | 27.836576 | 257 |
starcoderdata
|
/******************************************************************************
* Copyright © 2014-2018 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
//
// LP_messages.c
// marketmaker
//
struct LP_messageinfo { struct LP_messageinfo *next,*prev; cJSON *msgjson; int32_t ind; } *LP_MSGS;
int32_t Num_messages;
void LP_gotmessage(cJSON *argjson)
{
struct LP_messageinfo *msg = calloc(1,sizeof(*msg));
msg->msgjson = jduplicate(argjson);
msg->ind = Num_messages++;
portable_mutex_lock(&LP_messagemutex);
DL_APPEND(LP_MSGS,msg);
portable_mutex_unlock(&LP_messagemutex);
}
void LP_deletemessages(int32_t firsti,int32_t num)
{
struct LP_messageinfo *msg,*tmp; int32_t lasti;
if ( num == 0 )
num = 100;
if ( firsti < 0 )
firsti = 0;
else if ( firsti >= Num_messages )
return;
lasti = firsti + num - 1;
if ( lasti < Num_messages-1 )
lasti = Num_messages - 1;
DL_FOREACH_SAFE(LP_MSGS,msg,tmp)
{
if ( msg->ind >= firsti && msg->ind <= lasti )
{
portable_mutex_lock(&LP_messagemutex);
DL_DELETE(LP_MSGS,msg);
portable_mutex_unlock(&LP_messagemutex);
free_json(msg->msgjson);
free(msg);
}
}
}
cJSON *LP_getmessages(int32_t firsti,int32_t num)
{
struct LP_messageinfo *msg,*tmp; int32_t lasti,n=0,maxi=-1,mini=-1; cJSON *retjson,*item,*array = cJSON_CreateArray();
retjson = cJSON_CreateObject();
if ( num == 0 )
num = 100;
if ( firsti < 0 )
firsti = 0;
else if ( firsti >= Num_messages )
{
jadd(retjson,"messages",array);
return(retjson);
}
lasti = firsti + num - 1;
if ( lasti < Num_messages-1 )
lasti = Num_messages - 1;
DL_FOREACH_SAFE(LP_MSGS,msg,tmp)
{
if ( msg->ind >= firsti && msg->ind <= lasti )
{
item = cJSON_CreateObject();
jaddnum(item,"ind",msg->ind);
jadd(item,"msg",jduplicate(msg->msgjson));
jaddi(array,item);
if ( mini == -1 || msg->ind < mini )
mini = msg->ind;
if ( maxi == -1 || msg->ind > maxi )
maxi = msg->ind;
n++;
}
}
jadd(retjson,"messages",array);
jaddnum(retjson,"firsti",firsti);
jaddnum(retjson,"lasti",lasti);
jaddnum(retjson,"minind",mini);
jaddnum(retjson,"maxind",maxi);
jaddnum(retjson,"num",n);
return(retjson);
}
|
c
| 12 | 0.502443 | 122 | 34.5 | 98 |
starcoderdata
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.codebaseRouter = void 0;
const express_1 = require("express");
const tree_router_1 = require("./tree/tree.router");
exports.codebaseRouter = express_1.Router();
exports.codebaseRouter.use('/tree', tree_router_1.treeRouter);
//# sourceMappingURL=codebase.router.js.map
|
javascript
| 6 | 0.744318 | 62 | 43.125 | 8 |
starcoderdata
|
__author__ = 'Nasser'
# Import Folder with Several Classes
from OpenSeesAPI.Analysis import Algorithm
from OpenSeesAPI.Analysis import Analysis
from OpenSeesAPI.Analysis import Analyze
from OpenSeesAPI.Analysis import Constraints
from OpenSeesAPI.Analysis import Integrator
from OpenSeesAPI.Analysis import Numberer
from OpenSeesAPI.Analysis import System
from OpenSeesAPI.Analysis import Test
# Import One Class Files
from OpenSeesAPI.Analysis.Eigen import Eigen
|
python
| 4 | 0.847639 | 44 | 32.285714 | 14 |
starcoderdata
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Ristlbat17.Disposition.Material.Events;
using Swashbuckle.AspNetCore.Annotations;
namespace Ristlbat17.Disposition.Material
{
[Route("api/[controller]")]
[ApiController]
public class InventoryController : ControllerBase
{
private readonly IMaterialInventoryService _materialInventoryService;
public InventoryController(IMaterialInventoryService materialInventoryService)
{
_materialInventoryService = materialInventoryService;
}
///
/// Get the inventory for one company
///
/// <param name="company">
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerOperation(OperationId = nameof(GetMaterialInventory))]
[HttpGet("{company}")]
public async Task GetMaterialInventory(string company)
{
return await _materialInventoryService.GetInventoryForCompany(company);
}
///
/// Get the inventory for all companies
///
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerOperation(OperationId = nameof(GetMaterialInventoryForAll))]
[HttpGet]
public async Task GetMaterialInventoryForAll()
{
return await _materialInventoryService.GetInventoryForAll();
}
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerOperation(OperationId = nameof(GetMaterialInventoryForLocation))]
[HttpGet("{company}/material/{sapNr}/locations/{location}")]
public async Task GetMaterialInventoryForLocation(string company,
string location, string sapNr)
{
var inventoryItem = await _materialInventoryService.GetInventoryItem(sapNr, company);
if (inventoryItem == null) return NotFound();
return inventoryItem.Distribution.FirstOrDefault(dist => dist.Location == location);
}
///
/// (currently not in use) Distribute the company stock to it's locations (typically done after a "Micro Dispo".
///
/// <param name="companyName">
/// <param name="sapNr">
/// <param name="distributionList">
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
[SwaggerOperation(OperationId = nameof(DistributeMaterialForCompany))]
[HttpPut("{companyName}/material/{sapNr}/distribution")]
public async Task DistributeMaterialForCompany([FromRoute] string companyName,
[FromRoute] string sapNr,
MaterialDistribution distributionList)
{
await _materialInventoryService.DistributeMaterialForCompany(companyName, sapNr, distributionList);
return Ok();
}
///
/// Report that a certain material got damaged (typically only used during exercises)
///
/// <param name="company">
/// <param name="location">
/// <param name="sapNr">
/// <param name="patch">
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
[SwaggerOperation(OperationId = nameof(MaterialDefect))]
[HttpPatch("{company}/locations/{location}/material/{sapNr}/defected")]
public async Task MaterialDefect([FromRoute] string company, [FromRoute] string location,
[FromRoute] string sapNr, PatchAmount patch)
{
var current = await _materialInventoryService.GetInventoryItem(sapNr, company);
if (current == null) return BadRequest("No inventory available");
if (current.Available - patch.Amount < 0)
return BadRequest($"Can not damage more than stock {current.Available} at {company}");
current.Distribution.First(item => item.Location == location).Damaged += patch.Amount;
await _materialInventoryService.UpsertInventoryItem(company, sapNr, current);
await _materialInventoryService.NewEventJournalEntry(new MaterialDamaged(sapNr, company, location,
patch.Amount));
return Ok();
}
///
/// Report a damaged material got repaired (typically only used during exercises)
///
/// <param name="company">
/// <param name="location">
/// <param name="sapNr">
/// <param name="patch">
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
[SwaggerOperation(OperationId = nameof(MaterialRepaired))]
[HttpPatch("{company}/locations/{location}/material/{sapNr}/repaired")]
public async Task MaterialRepaired([FromRoute] string company, [FromRoute] string location,
[FromRoute] string sapNr,
PatchAmount patch)
{
var current = await _materialInventoryService.GetInventoryItem(sapNr, company);
if (current == null) return BadRequest("No inventory available");
if (current.Damaged - patch.Amount < 0) return BadRequest("Can not repair more than damaged");
current.Distribution.First(item => item.Location == location).Damaged -= patch.Amount;
await _materialInventoryService.UpsertInventoryItem(company, sapNr, current);
await _materialInventoryService.NewEventJournalEntry(new MaterialRepaired(sapNr, location, company,
patch.Amount));
return Ok();
}
///
/// You can change (+/-) the material in use on a location.
///
/// <param name="company">Company identifier
/// <param name="sapNr">Material used
/// <param name="location">Location of the company
/// <param name="patch">Change
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
[SwaggerOperation(OperationId = nameof(MaterialUsed))]
[HttpPatch("{company}/locations/{location}/material/{sapNr}/used")]
public async Task MaterialUsed([FromRoute] string company, [FromRoute] string sapNr,
[FromRoute] string location,
PatchAmount patch)
{
var inventoryItem = await _materialInventoryService.GetInventoryItem(sapNr, company);
if (inventoryItem == null) return BadRequest();
var usedAtLocation = inventoryItem.Distribution.SingleOrDefault(used => used.Location == location);
if (usedAtLocation is null)
{
usedAtLocation = new MaterialAllocation {Used = 0, Location = location};
inventoryItem.Distribution.Add(usedAtLocation);
}
usedAtLocation.Used += patch.Amount;
if (usedAtLocation.Available < 0 || usedAtLocation.Used < 0)
return BadRequest("Can not use more than on stock");
await _materialInventoryService.UpsertInventoryItem(company, sapNr, inventoryItem);
await _materialInventoryService.NewEventJournalEntry(new MaterialUsed(sapNr, company, patch.Amount,
location));
return Ok();
}
///
/// Corrects the stock.
///
/// <param name="company">
/// <param name="sapNr">
/// <param name="location">
/// <param name="newStock">
///
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
[SwaggerOperation(OperationId = nameof(CorrectMaterialStock))]
[HttpPatch("{company}/locations/{location}/material/{sapNr}/stock")]
public async Task CorrectMaterialStock(string company, string sapNr, string location,
PatchAmount newStock)
{
var current = await _materialInventoryService.GetInventoryItem(sapNr, company);
if (current == null) return BadRequest("No inventory available");
if (newStock.Amount < 0) return BadRequest("Stock must be a positive value");
if (newStock.Amount < current.Used + current.Damaged)
return BadRequest(
"you are not allowed to correct stock to lower number than (used + damaged) please redistribute");
current.Distribution.First(item => item.Location == location).Stock = newStock.Amount;
await _materialInventoryService.UpsertInventoryItem(company, sapNr, current);
await _materialInventoryService.NewEventJournalEntry(new StockCorrected(sapNr, company, location,
newStock.Amount));
return Ok();
}
}
}
|
c#
| 17 | 0.641712 | 125 | 44.166667 | 210 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use App\Articles;
use Illuminate\Support\Carbon;
class TopController extends Controller
{
public function index()
{
// modelのインスタンス生成
$articles = new Articles;
// 投稿データ取得
$data = $articles->getPageViewCountsForAll();
// 現在日時の取得
$now = new Carbon(Carbon::now());
return view('top', compact('data', 'now'));
}
}
|
php
| 13 | 0.604119 | 53 | 17.208333 | 24 |
starcoderdata
|
text = "abcd"
print(text) # abcd
text = text + "ef"
print(text) # abcdef
other = text
print(other) # abcdef
text = "xyz"
print(text) # xyz
print(other) # abcdef
# When assigning a variable pointing a string, the new variable is pointing to the same string..
# If we then assign some other string to either of the variables, then they will point to two different
# strings.
|
python
| 5 | 0.722667 | 103 | 24.066667 | 15 |
starcoderdata
|
def sync_trekking(self, lang):
self.sync_geojson(lang, TrekViewSet, 'treks.geojson', type_view={'get': 'list'})
treks = trekking_models.Trek.objects.existing().order_by('pk')
treks = treks.filter(**{'published_{lang}'.format(lang=lang): True})
if self.portal:
treks = treks.filter(Q(portal__name__in=self.portal) | Q(portal=None))
for trek in treks:
self.sync_geojson(lang, TrekViewSet, '{pk}/trek.geojson'.format(pk=trek.pk), pk=trek.pk,
type_view={'get': 'retrieve'})
self.sync_trek_pois(lang, trek)
self.sync_trek_touristic_contents(lang, trek)
self.sync_trek_touristic_events(lang, trek)
# Sync detail of children too
for child in trek.children:
self.sync_geojson(
lang, TrekViewSet,
'{pk}/treks/{child_pk}.geojson'.format(pk=trek.pk, child_pk=child.pk),
pk=child.pk, type_view={'get': 'retrieve'}, params={'root_pk': trek.pk},
)
|
python
| 14 | 0.555042 | 100 | 50.52381 | 21 |
inline
|
using System;
using System.Collections.Generic;
using Ncqrs.Eventing;
using Ncqrs.Eventing.Sourcing.Mapping;
namespace Ncqrs.Domain
{
///
/// A aggregate root that uses lambda style mapping to map internal event handlers. The following method should be mapped
///
///
/// This aggregate root uses the <see cref="ExpressionBasedSourcedEventHandlerMappingStrategy"/> to get the internal event handlers.
///
/// <seealso cref="ExpressionBasedSourcedEventHandlerMappingStrategy"/>
public abstract class AggregateRootMappedWithExpressions : MappedAggregateRoot
{
[NonSerialized]
private readonly IList _mappinghandlers = new List
///
/// Gets the <see cref="IList{ExpressionHandler}"/> list of mapping rules.
///
internal IList MappingHandlers
{
get { return _mappinghandlers; }
}
protected AggregateRootMappedWithExpressions()
: base(new ExpressionBasedSourcedEventHandlerMappingStrategy())
{
/* I know, calling virtual methods from the constructor isn't the smartest thing to do
* but in this case it doesn't really matter because the implemented
* method isn't (and shouldn't be) using any derived resources
**/
InitializeEventHandlers();
}
///
/// Maps the given generic eventtype to the expressed handler.
///
/// <typeparam name="T">This should always be a <see cref="SourcedEvent"/>.
/// <see cref="ExpressionHandler{T}"/>which allows us to define the mapping to a handler.
protected ExpressionHandler Map where T : IEvent
{
var handler = new ExpressionHandler
_mappinghandlers.Add(handler);
return handler;
}
///
/// Defines the method that derived types need to implement to support strongly typed mapping.
///
public abstract void InitializeEventHandlers();
}
}
|
c#
| 14 | 0.637469 | 137 | 39.912281 | 57 |
starcoderdata
|
import {
typeDispatch
} from './Notification-constants'
export const initialState = {
loading: false,
called: false,
error: null,
notifications: []
}
export const reducer = (state, action) => {
const {type} = action;
switch (type) {
case typeDispatch.ERRO:
return {...state, error: action.error, loading: false, called: true}
case typeDispatch.LOADING:
return {...state, loading: true}
case typeDispatch.NEW_NOTIFICATION:
return {...state, loading: false, called: true, notifications: [...state.notifications, ...action.notifications]}
case typeDispatch.UPDATE_NOTIFICATION:
return {...state, loading: false, called: true, notifications: [...action.notifications]}
default:
return state
}
}
|
javascript
| 9 | 0.684466 | 119 | 28.428571 | 28 |
starcoderdata
|
#pragma once
namespace JGSL {
template <class T, int dim = 3>
VECTOR<int, 4> Make_Rod_From_Points(const Eigen::Matrix<T, -1, dim> &pts,
MESH_NODE<T, dim>& X,
std::vector<VECTOR<int, 2>>& rod)
{
VECTOR<int, 4> counter;
counter[0] = X.size;
counter[1] = rod.size();
size_t nv = pts.rows();
X.Reserve(X.size + nv);
rod.reserve(rod.size() + nv - 1);
for (int i = 0; i < nv - 1; ++i) {
X.Append(VECTOR<T, dim>(pts(i, 0), pts(i, 1), pts(i, 2)));
rod.emplace_back(counter[0] + i, counter[0] + i + 1);
}
X.Append(VECTOR<T, dim>(pts(nv-1, 0), pts(nv-1, 1), pts(nv-1, 2)));
counter[2] = X.size;
counter[3] = rod.size();
return counter;
}
template <class T, int dim = 3>
VECTOR<int, 4> Make_Rod(T len, int nSeg,
MESH_NODE<T, dim>& X,
std::vector<VECTOR<int, 2>>& rod)
{
VECTOR<int, 4> counter;
counter[0] = X.size;
counter[1] = rod.size();
X.Reserve(X.size + nSeg + 1);
rod.reserve(rod.size() + nSeg);
X.Append(VECTOR<T, dim>(-len / 2, 0, 0));
const T segLen = len / nSeg;
for (int i = 0; i < nSeg; ++i) {
X.Append(VECTOR<T, dim>(-len / 2 + (i + 1) * segLen, 0, 0));
rod.emplace_back(counter[0] + i, counter[0] + i + 1);
}
counter[2] = X.size;
counter[3] = rod.size();
return counter;
}
template <class T, int dim = 3>
VECTOR<int, 4> Make_Rod_Net(T len, int nSeg,
int midPointAmt,
MESH_NODE<T, dim>& X,
std::vector<VECTOR<int, 2>>& rod)
{
VECTOR<int, 4> counter;
counter[0] = X.size;
counter[1] = rod.size();
X.Reserve(X.size + (nSeg + 1) * (nSeg + 1));
rod.reserve(rod.size() + nSeg * (nSeg + 1) * 2);
const T segLen = len / nSeg;
for (int i = 0; i < nSeg + 1; ++i) {
for (int j = 0; j < nSeg + 1; ++j) {
X.Append(VECTOR<T, dim>(-len / 2 + i * segLen, 0, -len / 2 + j * segLen));
}
}
for (int i = 0; i < nSeg; ++i) {
for (int j = 0; j < nSeg; ++j) {
rod.emplace_back(counter[0] + i * (nSeg + 1) + j, counter[0] + i * (nSeg + 1) + j + 1);
rod.emplace_back(counter[0] + i * (nSeg + 1) + j, counter[0] + (i + 1) * (nSeg + 1) + j);
}
}
for (int i = 0; i < nSeg; ++i) {
rod.emplace_back(counter[0] + i * (nSeg + 1) + nSeg, counter[0] + (i + 1) * (nSeg + 1) + nSeg);
}
for (int j = 0; j < nSeg; ++j) {
rod.emplace_back(counter[0] + nSeg * (nSeg + 1) + j, counter[0] + nSeg * (nSeg + 1) + j + 1);
}
if (midPointAmt > 0) {
std::vector<VECTOR<int, 2>> subRods;
for (int rodI = counter[1]; rodI < rod.size(); ++rodI) {
const VECTOR<T, dim>& v0 = std::get
const VECTOR<T, dim>& v1 = std::get
T ratio = 1.0 / (midPointAmt + 1);
X.Append(v0 * ratio + v1 * (1 - ratio));
int rodEndVI = rod[rodI][1];
rod[rodI][1] = X.size - 1;
for (int mpI = 1; mpI < midPointAmt; ++mpI) {
T ratio = (mpI + 1) / (midPointAmt + 1);
X.Append(v0 * ratio + v1 * (1 - ratio));
subRods.emplace_back(X.size - 2, X.size - 1);
}
subRods.emplace_back(X.size - 1, rodEndVI);
}
rod.insert(rod.end(), subRods.begin(), subRods.end());
}
counter[2] = X.size;
counter[3] = rod.size();
return counter;
}
template <class T, int dim = 3>
T Initialize_Discrete_Rod(
MESH_NODE<T, dim>& X,
const std::vector<VECTOR<int, 2>>& rod,
T rho, T E, T thickness,
const VECTOR<T, dim>& gravity,
std::vector b,
MESH_NODE_ATTR<T, dim>& nodeAttr,
CSR_MATRIX M, // mass matrix
std::vector<VECTOR<T, 3>>& rodInfo, // rodInfo: k_i, l_rest_i
std::vector<VECTOR<int, 3>>& rodHinge,
std::vector<VECTOR<T, 3>>& rodHingeInfo,
T rodBendStiffMult,
T h, T dHat2, VECTOR<T, 3>& kappa)
{
std::map<int, std::vector rodVNeighbor;
rodInfo.resize(rod.size());
std::vector triplets;
int i = 0;
for (const auto& segI : rod) {
rodVNeighbor[segI[0]].emplace_back(segI[1]);
rodVNeighbor[segI[1]].emplace_back(segI[0]);
const VECTOR<T, dim>& X0 = std::get
const VECTOR<T, dim>& X1 = std::get
rodInfo[i][0] = E;
rodInfo[i][1] = (X0 - X1).length();
rodInfo[i][2] = thickness;
const T massPortion = rodInfo[i][1] * M_PI * thickness * thickness / 4 * rho / 2;
for (int endI = 0; endI < 2; ++endI) {
std::get<FIELDS<MESH_NODE_ATTR<T, dim>>::m>(nodeAttr.Get_Unchecked(segI[endI])) += massPortion;
for (int dimI = 0; dimI < dim; ++dimI) {
triplets.emplace_back(segI[endI] * dim + dimI, segI[endI] * dim + dimI, massPortion);
b[segI[endI] * dim + dimI] += massPortion * gravity[dimI];
}
}
++i;
}
CSR_MATRIX M_add;
M_add.Construct_From_Triplet(X.size * dim, X.size * dim, triplets);
M.Get_Matrix() += M_add.Get_Matrix();
for (const auto& RVNbI : rodVNeighbor) {
if (RVNbI.second.size() >= 2) {
// > 2 means non-manifold connection
for (int i = 0; i < RVNbI.second.size(); ++i) {
for (int j = i + 1; j < RVNbI.second.size(); ++j) {
rodHinge.emplace_back(RVNbI.second[i], RVNbI.first, RVNbI.second[j]);
}
}
}
}
rodHingeInfo.resize(rodHinge.size());
for (int rhI = 0; rhI < rodHinge.size(); ++rhI) {
const VECTOR<T, dim>& X0 = std::get
const VECTOR<T, dim>& X1 = std::get
const VECTOR<T, dim>& X2 = std::get
rodHingeInfo[rhI][0] = E * rodBendStiffMult;
rodHingeInfo[rhI][1] = (X1 - X0).length() + (X2 - X1).length();
rodHingeInfo[rhI][2] = thickness;
}
//TODO: EIPC volume
if (kappa[0] == 0 && rodInfo.size()) {
const T nu = 0.4;
const T h2vol = h * h * rodInfo[0][1] * thickness * thickness / 10000;
const T lambda = E * nu / ((T)1 - nu * nu);
const T mu = E / ((T)2 * ((T)1 + nu));
kappa[0] = h2vol * mu;
kappa[1] = h2vol * lambda;
kappa[2] = nu;
dHat2 = thickness * thickness;
}
return dHat2;
}
template<class T, int dim>
void Compute_Max_And_Avg_Stretch_Rod(
MESH_NODE<T, dim>& X, // mid-surface node coordinates
const std::vector<VECTOR<int, 2>>& rod,
const std::vector<VECTOR<T, 3>>& rodInfo, // rodInfo: k_i, l_rest_i
T& maxs, T& avgs)
{
TIMER_FLAG("Compute_Max_And_Avg_Stretch_Rod");
maxs = 1.0, avgs = 0.0;
int stretchedAmt = 0;
if constexpr (dim == 2) {
//TODO
}
else {
for (int rodI = 0; rodI < rod.size(); ++rodI) {
const VECTOR<T, dim>& x1 = std::get
const VECTOR<T, dim>& x2 = std::get
T maxsI = (x1 - x2).length() / rodInfo[rodI][1];
if (maxsI > maxs) {
maxs = maxsI;
}
if (maxsI > 1) {
++stretchedAmt;
avgs += maxsI;
}
}
}
if (stretchedAmt) {
avgs /= stretchedAmt;
}
}
}
|
c
| 18 | 0.508352 | 107 | 32.115044 | 226 |
starcoderdata
|
(function(document) {
'use strict';
function definition(path, Pledge, abstractHandler, resolveSourcemaps, isObject, merge, onAnimationFrame) {
var target = document.getElementsByTagName('head')[0],
resolver = document.createElement('a'),
regexMatchUrl = /url\s*\(\s*["']?(.+?)["']?\s*\)/gi,
regexMatchImport = /@import\s+["'](.+?)["']/gi,
regexIsAbsolutePath = /^\//i,
regexIsAbsoluteUri = /^data:|http(s?):|\/\//i,
regexMatchType = /^text\/css/,
settings = { suffix: '.css' };
demand
.on('postConfigure:' + path, function(options) {
if(isObject(options)) {
merge(settings, options);
}
});
function resolveUrl(url) {
resolver.href = url;
return resolver;
}
function replaceUri(source, match, replacement) {
if(!regexIsAbsoluteUri.test(match[1])) {
source = source.replace(match[0], replacement);
}
return source;
}
function HandlerCss() {}
HandlerCss.prototype = {
validate: function(type) {
return regexMatchType.test(type);
},
onPreRequest: function(dependency, suffix) {
var pathname;
suffix = (typeof suffix !== 'undefined') ? suffix : settings.suffix;
if(suffix) {
pathname = dependency.url.pathname;
dependency.url.pathname = pathname.slice(-suffix.length) !== suffix ? pathname + suffix : pathname;
}
},
onPostRequest: function(dependency) {
var url = resolveUrl(dependency.url + '/..'),
base = url.href,
host = '//' + url.host,
source = dependency.source,
match;
while((match = regexMatchUrl.exec(source))) {
source = replaceUri(source, match, 'url("' + resolveUrl(regexIsAbsolutePath.test(match[1]) ? host + match[1] : base + match[1]).href + '")');
}
while((match = regexMatchImport.exec(source))) {
source = replaceUri(source, match, '@import "' + resolveUrl(regexIsAbsolutePath.test(match[1]) ? host + match[1] : base + match[1]).href + '"');
}
dependency.source = resolveSourcemaps(dependency.url, source);
},
onPreProcess: function(dependency) {
dependency.enqueue = new Pledge(onAnimationFrame);
},
process: function(dependency) {
var element = document.querySelector('[demand-id="' + dependency.id + '"]');
if(!element) {
element = document.createElement('style');
element.type = 'text/css';
element.setAttribute('demand-id', dependency.id);
target.appendChild(element);
}
if(element.tagName === 'STYLE') {
if(element.styleSheet) {
element.styleSheet.cssText = dependency.source;
} else {
element.textContent = dependency.source;
}
}
provide(function() { return element; });
}
};
return new (HandlerCss.extends(abstractHandler));
}
provide([ 'path', '/demand/pledge', '/demand/abstract/handler', '/demand/function/resolveSourcemaps', '/demand/validator/isObject', '/demand/function/merge', '/demand/function/onAnimationFrame' ], definition);
}(document));
|
javascript
| 29 | 0.625413 | 210 | 29.606061 | 99 |
starcoderdata
|
// Copyright 2020 Google LLC
//
// 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.
//
#include "utils/tflite/dist_diversification.h"
#include
#include "tensorflow/lite/context.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/model.h"
namespace libtextclassifier3 {
namespace {
// Returns a vector of row indices in a distance matrix.
// Indices are increasing and the distance of every selected index to others
// is larger than `min_distance`.
template <typename DistanceMatrixType>
std::vector DiversifyByDistance(const DistanceMatrixType& distance_matrix,
const int matrix_size,
const float min_distance,
const int max_num_results) {
std::vector result{0};
result.reserve(max_num_results);
int index = 1;
while (result.size() < max_num_results && index < matrix_size) {
for (; index < matrix_size; ++index) {
bool too_close = false;
for (const int selected_index : result) {
if (distance_matrix(index, selected_index) < min_distance) {
too_close = true;
break;
}
}
if (!too_close) {
result.push_back(index);
++index;
break;
}
}
}
return result;
}
// Input parameters for the op.
enum DistDiversificationInputs {
DIST_DIVERSIFICATION_INPUT_DISTANCE_MATRIX = 0,
DIST_DIVERSIFICATION_INPUT_MIN_DISTANCE = 1,
DIST_DIVERSIFICATION_INPUT_NUM_RESULTS = 2
};
// Output parameters for the op.
enum DistDiversificationOutputs {
DIST_DIVERSIFICATION_OUTPUT_INDICES = 0,
DIST_DIVERSIFICATION_OUTPUT_LENGTH = 1,
};
TfLiteIntArray* CreateSizeArray(const std::initializer_list sizes) {
TfLiteIntArray* array_size = TfLiteIntArrayCreate(sizes.size());
int index = 0;
for (const int size : sizes) {
array_size->data[index++] = size;
}
return array_size;
}
TfLiteStatus AllocateOutputIndexes(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor& num_results =
context
->tensors[node->inputs->data[DIST_DIVERSIFICATION_INPUT_NUM_RESULTS]];
TfLiteTensor& output_indices =
context
->tensors[node->outputs->data[DIST_DIVERSIFICATION_OUTPUT_INDICES]];
return context->ResizeTensor(context, &output_indices,
CreateSizeArray({num_results.data.i32[0]}));
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor& num_results =
context
->tensors[node->inputs->data[DIST_DIVERSIFICATION_INPUT_NUM_RESULTS]];
if (tflite::IsConstantTensor(&num_results)) {
TF_LITE_ENSURE_OK(context, AllocateOutputIndexes(context, node));
} else {
TfLiteTensor& output_indices =
context
->tensors[node->outputs->data[DIST_DIVERSIFICATION_OUTPUT_INDICES]];
tflite::SetTensorToDynamic(&output_indices);
}
TfLiteTensor& output_length =
context->tensors[node->outputs->data[DIST_DIVERSIFICATION_OUTPUT_LENGTH]];
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, &output_length,
CreateSizeArray({1})));
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor& output_indices =
context
->tensors[node->outputs->data[DIST_DIVERSIFICATION_OUTPUT_INDICES]];
if (tflite::IsDynamicTensor(&output_indices)) {
TF_LITE_ENSURE_OK(context, AllocateOutputIndexes(context, node));
}
const TfLiteTensor& distance_matrix =
context->tensors[node->inputs
->data[DIST_DIVERSIFICATION_INPUT_DISTANCE_MATRIX]];
const int distance_matrix_dim = distance_matrix.dims->data[0];
const float min_distance =
context
->tensors[node->inputs->data[DIST_DIVERSIFICATION_INPUT_MIN_DISTANCE]]
.data.f[0];
const int num_results =
context
->tensors[node->inputs->data[DIST_DIVERSIFICATION_INPUT_NUM_RESULTS]]
.data.i32[0];
const auto indices = DiversifyByDistance(
[&](int row, int col) {
return distance_matrix.data.f[row * distance_matrix_dim + col];
},
distance_matrix_dim, min_distance, num_results);
std::copy(indices.begin(), indices.end(), output_indices.data.i32);
std::fill_n(output_indices.data.i32 + indices.size(),
num_results - indices.size(), -1);
TfLiteTensor& output_length =
context->tensors[node->outputs->data[DIST_DIVERSIFICATION_OUTPUT_LENGTH]];
*output_length.data.i32 = indices.size();
return kTfLiteOk;
}
} // namespace
} // namespace libtextclassifier3
namespace tflite {
namespace ops {
namespace custom {
TfLiteRegistration* Register_DISTANCE_DIVERSIFICATION() {
static TfLiteRegistration r = {nullptr, nullptr, libtextclassifier3::Prepare,
libtextclassifier3::Eval};
return &r;
}
} // namespace custom
} // namespace ops
} // namespace tflite
|
c++
| 19 | 0.673645 | 89 | 35.058065 | 155 |
starcoderdata
|
public async Task<PostArchive<T>> GetByIdAsync<T>(Guid archiveId, int? currentPage = 1,
Guid? categoryId = null, Guid? tagId = null, int? year = null, int? month = null, int? pageSize = null)
where T : Models.PostBase
{
var model = new PostArchive<T>();
// Ensure page size
if (!pageSize.HasValue)
{
using (var config = new Config(_paramService))
{
// No page size provided, get from config
pageSize = config.ArchivePageSize;
if (!pageSize.HasValue || pageSize == 0)
{
// No config available, default to 5
pageSize = 5;
}
}
}
// Set basic fields
model.Year = year;
model.Month = month;
// Get paging info
model.TotalPosts = await _repo.GetPostCount(archiveId, categoryId, tagId, year, month).ConfigureAwait(false);
model.TotalPages = Math.Max(Convert.ToInt32(Math.Ceiling((double)model.TotalPosts / pageSize.Value)), 1);
model.CurrentPage = Math.Min(Math.Max(1, currentPage.HasValue ? currentPage.Value : 1), model.TotalPages);
// Set related info
if (categoryId.HasValue)
{
model.Category = await _postService.GetCategoryByIdAsync(categoryId.Value).ConfigureAwait(false);
}
if (tagId.HasValue)
{
model.Tag = await _postService.GetTagByIdAsync(tagId.Value).ConfigureAwait(false);
}
// Get the id of the current posts
var posts = await _repo.GetPosts(archiveId, pageSize.Value, model.CurrentPage, categoryId, tagId, year, month).ConfigureAwait(false);
// Get the posts
foreach (var postId in posts)
{
var post = await _postService.GetByIdAsync<T>(postId).ConfigureAwait(false);
if (post != null)
{
model.Posts.Add(post);
}
}
return model;
}
|
c#
| 18 | 0.516056 | 145 | 38.5 | 56 |
inline
|
/*******************************************************************************
* Copyright 2006 - 2012 Vienna University of Technology,
* Department of Software Technology and Interactive Systems, IFS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package eu.scape_project.planning.user;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import eu.scape_project.planning.model.User;
import eu.scape_project.planning.utils.FacesMessages;
/**
* View for group configuration.
*/
@Named("groups")
@SessionScoped
public class GroupsView implements Serializable {
private static final long serialVersionUID = -2162378700125807065L;
@Inject
private FacesMessages facesMessages;
@Inject
private Groups groups;
@Inject
private User user;
private String inviteMailsString = "";
/**
* Initializes the view and returns the navigation path.
*
* @return the navigation path.
*/
public String init() {
groups.init();
return "/user/groups.jsf";
}
/**
* Method responsible for saving the made changes.
*
* @return Outcome String redirecting to start page.
*/
public String save() {
groups.save();
// why return to index page, we might have been working on a plan... "/index.jsp";
return null;
}
/**
* Method responsible for discarding the made changes.
*
* @return Outcome String redirecting to start page.
*/
public String discard() {
groups.discard();
// why return to index page, we might have been working on a plan... "/index.jsp";
return null;
}
/**
* Invite users by their email addresses.
*/
public void inviteUsers() {
if (inviteMailsString.equals("")) {
facesMessages.addWarning("No email addresses of people to invite were entered");
return;
}
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
String serverString = request.getServerName() + ":" + request.getServerPort();
ArrayList inviteMails = new ArrayList
// Invite users
Iterator inviteMailsIter = inviteMails.iterator();
while (inviteMailsIter.hasNext()) {
String inviteMail = inviteMailsIter.next();
try {
groups.inviteUser(inviteMail, serverString);
inviteMailsIter.remove();
facesMessages.addInfo(inviteMail + " invited");
} catch (AlreadyGroupMemberException e) {
inviteMailsIter.remove();
facesMessages.addWarning(inviteMail + " is already a member of your group");
} catch (InvitationMailException e) {
facesMessages.addError(inviteMail + " could not be invited");
}
}
// Get missing mails
StringBuffer failedMailsBuffer = new StringBuffer();
Iterator failedMailsIter = inviteMails.iterator();
while (failedMailsIter.hasNext()) {
failedMailsBuffer.append(failedMailsIter.next());
if (failedMailsIter.hasNext()) {
failedMailsBuffer.append(", ");
}
}
inviteMailsString = failedMailsBuffer.toString();
}
/**
* Remove a user from the group.
*
* @param user
* the user to remove
*/
public void removeUser(User user) {
groups.removeUser(user);
}
/**
* Leave a group.
*/
public void leaveGroup() {
groups.leaveGroup();
}
// --------------- getter/setter ---------------
public User getUser() {
return user;
}
public List getGroupUsers() {
return groups.getGroupUsers();
}
public String getInviteMailsString() {
return inviteMailsString;
}
public void setInviteMailsString(String inviteMailsString) {
this.inviteMailsString = inviteMailsString;
}
}
|
java
| 15 | 0.619385 | 121 | 29.578313 | 166 |
starcoderdata
|
// Simple Node.js example program to set up User LED3 to be turned on or off from
// the Linux console.
// Written by for the book "Exploring BeagleBone: Tools and
// Techniques for Building with Embedded Linux" by & Sons, 2014
// ISBN 9781118935125. Please see the file README.md in the repository root
// directory for copyright and GNU GPLv3 license information.
// Ignore the first two arguments (nodejs and the program name)
var myArgs = process.argv.slice(2);
var LED3_PATH = "/sys/class/leds/beaglebone:green:usr3"
function writeLED( filename, value, path ){
var fs = require('fs');
// This call must be syncronous! Otherwise the timer will not work as there are
// three calls to write that happen at the same time for the flash call
try {
fs.writeFileSync(path+filename, value);
}
catch (err) {
console.log("The Write Failed to the File: " + path+filename);
}
}
function removeTrigger(){
writeLED("/trigger", "none", LED3_PATH);
}
console.log("Starting the LED Node.js Program");
if (myArgs[0]==null){
console.log("There is an incorrect number of arguments.");
console.log(" Usage is: nodejs nodejsLED.js command");
console.log(" where command is one of: on, off, flash or status.");
process.exit(2); //exits with the error code 2 (incorrect usage)
}
switch (myArgs[0]) {
case 'on':
console.log("Turning the LED On");
removeTrigger();
writeLED("/brightness", "1", LED3_PATH);
break;
case 'off':
console.log("Turning the LED Off");
removeTrigger();
writeLED("/brightness", "0", LED3_PATH);
break;
case 'flash':
console.log("Making the LED Flash");
writeLED("/trigger", "timer", LED3_PATH);
writeLED("/delay_on", "50", LED3_PATH);
writeLED("/delay_off", "50", LED3_PATH);
break;
case 'status':
console.log("Getting the LED Status");
fs = require('fs');
fs.readFile(LED3_PATH+"/trigger", 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
console.log(data);
});
break;
default:
console.log("Invalid Command");
}
console.log("End of Node.js script");
|
javascript
| 14 | 0.641211 | 81 | 33.046154 | 65 |
starcoderdata
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from ._utils import lib, get_string
from ._utils import codec
def AccumulatedL():
"""(read-only) accummulated failure rate for this branch on downline"""
return lib.PDElements_Get_AccumulatedL()
def Count():
"""(read-only) Number of PD elements (including disabled elements)"""
return lib.PDElements_Get_Count()
def FaultRate(*args):
"""Get/Set Number of failures per year. For LINE elements: Number of failures per unit length per year. """
# Getter
if len(args) == 0:
return lib.PDElements_Get_FaultRate()
# Setter
Value, = args
lib.PDElements_Set_FaultRate(Value)
def First():
"""(read-only) Set the first enabled PD element to be the active element. Returns 0 if none found."""
return lib.PDElements_Get_First()
def FromTerminal():
"""(read-only) Number of the terminal of active PD element that is on the "from" side. This is set after the meter zone is determined."""
return lib.PDElements_Get_FromTerminal()
def IsShunt():
"""(read-only) Variant boolean indicating of PD element should be treated as a shunt element rather than a series element. Applies to Capacitor and Reactor elements in particular."""
return lib.PDElements_Get_IsShunt() != 0
def Lambda():
"""(read-only) Failure rate for this branch. Faults per year including length of line."""
return lib.PDElements_Get_Lambda()
def Name(*args):
"""Get/Set name of active PD Element. Returns null string if active element is not PDElement type."""
# Getter
if len(args) == 0:
return get_string(lib.PDElements_Get_Name())
# Setter
Value, = args
if type(Value) is not bytes:
Value = Value.encode(codec)
lib.PDElements_Set_Name(Value)
def Next():
"""(read-only) Advance to the next PD element in the circuit. Enabled elements only. Returns 0 when no more elements."""
return lib.PDElements_Get_Next()
def NumCustomers():
"""(read-only) Number of customers, this branch"""
return lib.PDElements_Get_Numcustomers()
def ParentPDElement():
"""(read-only) Sets the parent PD element to be the active circuit element. Returns 0 if no more elements upline."""
return lib.PDElements_Get_ParentPDElement()
def RepairTime(*args):
"""Average repair time for this element in hours"""
# Getter
if len(args) == 0:
return lib.PDElements_Get_RepairTime()
# Setter
Value, = args
lib.PDElements_Set_RepairTime(Value)
def SectionID():
"""(read-only) Integer ID of the feeder section that this PDElement branch is part of"""
return lib.PDElements_Get_SectionID()
def TotalMiles():
"""(read-only) Total miles of line from this element to the end of the zone. For recloser siting algorithm."""
return lib.PDElements_Get_TotalMiles()
def TotalCustomers():
"""(read-only) Total number of customers from this branch to the end of the zone"""
return lib.PDElements_Get_Totalcustomers()
def PctPermanent(*args):
"""Get/Set percent of faults that are permanent (require repair). Otherwise, fault is assumed to be transient/temporary."""
# Getter
if len(args) == 0:
return lib.PDElements_Get_pctPermanent()
# Setter
Value, = args
lib.PDElements_Set_pctPermanent(Value)
_columns = [
"AccumulatedL",
"FaultRate",
"FromTerminal",
"IsShunt",
"Lambda",
"Name",
"NumCustomers",
"ParentPDElement",
"RepairTime",
"SectionID",
"TotalMiles",
"TotalCustomers",
"PctPermanent",
]
__all__ = [
"AccumulatedL",
"Count",
"FaultRate",
"First",
"FromTerminal",
"IsShunt",
"Lambda",
"Name",
"Next",
"NumCustomers",
"ParentPDElement",
"RepairTime",
"SectionID",
"TotalMiles",
"TotalCustomers",
"PctPermanent",
]
|
python
| 10 | 0.664955 | 186 | 25.496599 | 147 |
starcoderdata
|
//
// LeapFinger.cpp
// ofxLeapMotion
//
// Created by GL on 6/29/14.
//
//
#include "LeapFinger.h"
void LeapFinger::clear(){
fingerType = (Finger::Type)0;
fingerWidth = 0;
fingerTipPt.zero();
if (bones.size() > 0){
for (int i=0; i<bones.size(); i++){
bones[i].clear();
}
}
bones.clear();
}
|
c++
| 12 | 0.576433 | 37 | 12.125 | 24 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.