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
class SwitchMonitorWidget { static install(signalkClient, container=window.document.body) { return(new SwitchMonitorWidget(signalkClient, container)); } constructor(signalkClient, container) { this.signalkClient = signalkClient; this.switchmonitorwidget = null; this.switchbanks = { "misc": [] }; var switchPaths = new Set(); signalkClient.getAvailablePathsSync("^electrical\.switches\.bank\.(.+)\.(\\d+)\.state$").forEach(path => { path = path.substr(0, (path.length - 6)); var meta = signalkClient.getValueSync(path + ".state.meta", (v) => v); if ((meta) && (meta.shortName)) { var sbmatch = path.match(/^.*\.(.+)\.(\d+)$/); if ((sbmatch) && (sbmatch.length == 3)) { var instance = "" + sbmatch[1]; var index = parseInt(sbmatch[2]); if (!this.switchbanks.hasOwnProperty(instance)) this.switchbanks[instance] = []; this.switchbanks[instance].push({ path: path, meta: meta }); } else { this.switchbanks['misc'].push({ path: path, meta: meta }); } } }); this.switchmonitorwidget = PageUtils.createElement('div', 'switchmonitorwidget', null, null, container); Object.keys(this.switchbanks).forEach(switchbank => { this.switchmonitorwidget.appendChild(this.makeSwitchBank(switchbank, this.switchbanks[switchbank])); }); } makeSwitchBank(instance, channel) { //instance = (Number.isNaN(parseInt(instance, 10)))?instance:parseInt(instance, 10); var switchbankContainer = PageUtils.createElement('div', null, 'switchbank-container' + ((instance == 'misc')?'':'hidden'), null, null); var switchbankTable = PageUtils.createElement('div', null, 'table switchbank-table', null, switchbankContainer); var switchbankTableRow = PageUtils.createElement('div', null, 'switchbank-table-row', null, switchbankTable); var switchbankTableHeader = PageUtils.createElement('div', null, 'table-cell switchbank-table-header', document.createTextNode(instance.toUpperCase()), switchbankTableRow); var switchbankTableChannelContainer = PageUtils.createElement('div', null, 'table-cell switchbank-table-channel-container', null, switchbankTableRow); var switchbankChannelTable = PageUtils.createElement('div', null, 'table switchbank-channel-table', null, switchbankTableChannelContainer); var switchbankChannelTableRow = PageUtils.createElement('div', null, 'table-row switchbank-channel-table-row', null, switchbankChannelTable); channel.forEach(channel => { var switchbankChannelCell = PageUtils.createElement('div', channel.path, 'table-cell switchbank-channel-cell artifact', null, switchbankChannelTableRow); switchbankChannelCell.addEventListener('click', function(e) { this.operateSwitch(e.currentTarget.id.substr(2), e.currentTarget.classList.contains('on')); }.bind(this)); var channelId = (channel.path.includes('.'))?channel.path.slice(channel.path.lastIndexOf('.') + 1):channel.path; var switchbankChannelCellKey = PageUtils.createElement('span', null, 'key hidden', document.createTextNode(channelId), switchbankChannelCell); var switchbankChannelCellName = PageUtils.createElement('span', null, 'name', document.createTextNode(channelId), switchbankChannelCell); if (Number.isNaN(parseInt(instance, 10))) switchbankChannelCell.classList.remove('artifact'); switchbankChannelCell.classList.remove('artifact'); switchbankContainer.classList.remove('hidden'); if (channel.meta.type) switchbankChannelCell.classList.add(channel.meta.type); if (channel.meta.displayName) { switchbankChannelCell.querySelector('.name').innerHTML = channel.meta.displayName; switchbankChannelCell.querySelector('.key').classList.remove('hidden'); } this.signalkClient.onValue(channel.path + ".state", function(sbc,v) { var millis = Date.UTC() - Date.parse(v.timestamp); var timeout = (channel.meta.timeout)?channel.meta.timeout:5000; if (millis > timeout) sbc.classList.add('expired'); else sbc.classList.remove('expired'); if (v.value) { sbc.classList.add('on'); sbc.classList.remove('off'); } else { sbc.classList.add('off'); sbc.classList.remove('on'); } }.bind(this, switchbankChannelCell), (v) => v, false); }); return(switchbankContainer); } operateSwitch(key, state) { var path = "electrical.switches.bank." + key + ".state"; var value = (!state)?3:2; this.signalkClient.putValue(path, value); } }
javascript
24
0.695662
176
58.75
76
starcoderdata
<?php namespace ZablockiBros\Jetpack; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; use ZablockiBros\Jetpack\Events\Running; class JetpackApplicationServiceProvider extends ServiceProvider { /** * Bootstrap any application services. */ public function boot() { $this->routes(); Jetpack::running(function (Running $event) { // auth $this->authorization(); // models Jetpack::models($this->models()); Jetpack::bootModels(); }); // todo: move? Running::dispatch(); } /** * Register any application services. */ public function register() { // } /** * @return void */ protected function routes() { return; } /** * @return void */ protected function authorization() { return; } /** * @return array */ protected function models() { return []; } }
php
17
0.529187
63
15.854839
62
starcoderdata
/* * Copyright 2017-present Open Networking Foundation * * 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 org.onosproject.routing; import com.google.common.collect.Sets; import org.onosproject.net.intf.Interface; import org.onosproject.net.intf.InterfaceEvent; import org.onosproject.net.intf.InterfaceListener; import org.onosproject.net.intf.InterfaceService; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkNotNull; /** * Manages the configuration and provisioning of a single-device router. * It maintains which interfaces are part of the router when the configuration * changes, and handles the provisioning/unprovisioning of interfaces when they * are added/removed. */ public class Router { private final Logger log = LoggerFactory.getLogger(getClass()); private final Consumer provisioner; private final Consumer unprovisioner; private RouterInfo info; private Set provisioned = new HashSet<>(); private InterfaceService interfaceService; private InterfaceListener listener = new InternalInterfaceListener(); private DeviceService deviceService; private AsyncDeviceFetcher asyncDeviceFetcher; /** * Creates a new router interface manager. * * @param info router configuration information * @param interfaceService interface service * @param deviceService device service * @param provisioner consumer that will provision new interfaces * @param unprovisioner consumer that will unprovision old interfaces * @param forceUnprovision force unprovision when the device goes offline */ public Router(RouterInfo info, InterfaceService interfaceService, DeviceService deviceService, Consumer provisioner, Consumer unprovisioner, boolean forceUnprovision) { this.info = checkNotNull(info); this.provisioner = checkNotNull(provisioner); this.unprovisioner = checkNotNull(unprovisioner); this.interfaceService = checkNotNull(interfaceService); this.deviceService = checkNotNull(deviceService); this.asyncDeviceFetcher = AsyncDeviceFetcher.create(deviceService); if (forceUnprovision) { asyncDeviceFetcher.registerCallback(info.deviceId(), this::provision, this::forceUnprovision); } else { asyncDeviceFetcher.registerCallback(info.deviceId(), this::provision, null); } interfaceService.addListener(listener); } /** * Cleans up the router and unprovisions all interfaces. */ public void cleanup() { asyncDeviceFetcher.shutdown(); interfaceService.removeListener(listener); asyncDeviceFetcher.shutdown(); unprovision(); } /** * Retrieves the router configuration information. * * @return router configuration information */ public RouterInfo info() { return info; } /** * Changes the router configuration. * * @param newConfig new configuration * @param forceUnprovision true if we want to force unprovision the device when it goes offline */ public void changeConfiguration(RouterInfo newConfig, boolean forceUnprovision) { if (forceUnprovision) { asyncDeviceFetcher.registerCallback(info.deviceId(), this::provision, this::forceUnprovision); } else { asyncDeviceFetcher.registerCallback(info.deviceId(), this::provision, null); } Set oldConfiguredInterfaces = info.interfaces(); info = newConfig; Set newConfiguredInterfaces = info.interfaces(); if (newConfiguredInterfaces.isEmpty() && !oldConfiguredInterfaces.isEmpty()) { // Reverted to using all interfaces. Provision interfaces that // weren't previously in the configured list getInterfacesForDevice(info.deviceId()) .filter(intf -> !oldConfiguredInterfaces.contains(intf.name())) .forEach(this::provision); } else if (!newConfiguredInterfaces.isEmpty() && oldConfiguredInterfaces.isEmpty()) { // Began using an interface list. Unprovision interfaces that // are not in the new interface list. getInterfacesForDevice(info.deviceId()) .filter(intf -> !newConfiguredInterfaces.contains(intf.name())) .forEach(this::unprovision); } else { // The existing interface list was changed. Set toUnprovision = Sets.difference(oldConfiguredInterfaces, newConfiguredInterfaces); Set toProvision = Sets.difference(newConfiguredInterfaces, oldConfiguredInterfaces); toUnprovision.forEach(name -> getInterfacesForDevice(info.deviceId()) .filter(intf -> intf.name().equals(name)) .findFirst() .ifPresent(this::unprovision) ); toProvision.forEach(name -> getInterfacesForDevice(info.deviceId()) .filter(intf -> intf.name().equals(name)) .findFirst() .ifPresent(this::provision) ); } } private void provision() { getInterfacesForDevice(info.deviceId()) .forEach(this::provision); } private void unprovision() { getInterfacesForDevice(info.deviceId()) .forEach(this::unprovision); } private void forceUnprovision() { getInterfacesForDevice(info.deviceId()) .forEach(this::forceUnprovision); } private void provision(Interface intf) { if (!provisioned.contains(intf) && deviceAvailable(intf) && shouldProvision(intf)) { log.info("Provisioning interface {}", intf); provisioner.accept(InterfaceProvisionRequest.of(info, intf)); provisioned.add(intf); } } private void unprovision(Interface intf) { if (provisioned.contains(intf) && deviceAvailable(intf) && shouldProvision(intf)) { log.info("Unprovisioning interface {}", intf); unprovisioner.accept(InterfaceProvisionRequest.of(info, intf)); provisioned.remove(intf); } } private void forceUnprovision(Interface intf) { // Skip availability check when force unprovisioning an interface if (provisioned.contains(intf) && shouldProvision(intf)) { log.info("Unprovisioning interface {}", intf); unprovisioner.accept(InterfaceProvisionRequest.of(info, intf)); provisioned.remove(intf); } } private boolean deviceAvailable(Interface intf) { return deviceService.isAvailable(intf.connectPoint().deviceId()); } private boolean shouldProvision(Interface intf) { return info.interfaces().isEmpty() || info.interfaces().contains(intf.name()); } private Stream getInterfacesForDevice(DeviceId deviceId) { return interfaceService.getInterfaces().stream() .filter(intf -> intf.connectPoint().deviceId().equals(deviceId)); } private class InternalInterfaceListener implements InterfaceListener { @Override public void event(InterfaceEvent event) { Interface intf = event.subject(); switch (event.type()) { case INTERFACE_ADDED: provision(intf); break; case INTERFACE_UPDATED: // TODO break; case INTERFACE_REMOVED: unprovision(intf); break; default: break; } } } }
java
20
0.652442
106
36.293617
235
starcoderdata
import { makeStyles } from "@material-ui/core/styles"; const useStyles = makeStyles(() => ({ container: { marginTop: "150px", display: "flex", justifyContent: "flex-end", paddingRight: "100px", "@media (width:1024)": { paddingRight: "200px", }, }, content: { width: "100%", paddingLeft: "50%", }, titleContainer: { display: "flex", width: "100%", flexWrap: "wrap", marginBottom: "60px", }, textContent: { marginRight: "10rem", width: "496px", color: "#fff", fontFamily: "Open Sans", fontSize: "16px", lineHeight: "191%", marginBottom: "60px", }, formContent: { width: "600px", height: "200px", }, textFieldInput: { marginBottom: "29px", }, })); export default useStyles;
javascript
14
0.559899
54
17.44186
43
starcoderdata
from tkinter import * from tkinter import ttk, messagebox, filedialog, colorchooser try: from ttkthemes import themed_tk except ModuleNotFoundError: import os os.system('pip install ttkthemes') from ttkthemes import themed_tk try: from halo import Halo except ModuleNotFoundError: import os os.system('pip install halo') from halo import Halo from threading import Thread from time import sleep root = themed_tk.ThemedTk() root.title('Text Editor') root.geometry('1000x890+500+150') supported_files=[ ('Text Supported Files', ('.txt', '.log', '.env', '.py', '.pyi', '.pyt', '.pyw', '.jav', '.java')), ] def __change_theme(): while True: try: a = t.get() root.set_theme(a) sleep(1) except RuntimeError: exit(0) def look_for_themes(): abc = Thread(target=__change_theme) abc.start() def openFile(): def a(): filedname = filedialog.askopenfilename( filetypes=supported_files, defaultextension='.txt') if filedname == None or filedname=='\n': return else: text_editor.delete(1.0, 'end') try: f= open(filedname) text_editor.insert(1.0, f.read()) f.close() root.title('Editing: {}'.format(filedname.split("/")[-1])) lbl.config(text='Editing: {}'.format(filedname.split("/")[-1])) except FileNotFoundError: messagebox.showerror(title='Error', message='No File Chosen!') content = text_editor.get(1.0, 'end') if not content or content == None or content == '' or content =='\n': a() else: if messagebox.askyesno('Warning','All changes will be lost.\nDo you want to still continue?' ,icon='warning'): a() else: return def saveFile(): filename=filedialog.asksaveasfile(filetypes=supported_files ,confirmoverwrite=True, defaultextension='.txt') if filename ==None: return content =text_editor.get(1.0, 'end') filename.write(content) def clear(): lbl.config(text='') text_editor.delete(1.0, 'end') root.title('Text Editor') def Change_Color(): color = colorchooser.askcolor() text_editor.configure(fg=color[1]) lbl = Label(root, font='Vendara 15') text_editor = Text(root,takefocus=True, width=70, height=35, font=['Ubuntu Mono', 10] ,wrap='word') lbl.pack() text_editor.pack() openfile = ttk.Button(root, text='Open File', command=openFile, width=81) savefile = ttk.Button(root, text='Save As', command=saveFile, width=81) clear_all = ttk.Button(root, text='Clear All', command=clear, width=81) change = ttk.Button(root, text='Change Color', command=Change_Color, width=81) val = root.get_themes() t = StringVar(root, value='vista') change_theme = ttk.Combobox(root ,textvariable=t, values=val, state='readonly') change_theme.pack() openfile.pack() savefile.pack() clear_all.pack() change.pack() look_for_themes() def start(): spinner = Halo(text='App is running', placement='right', text_color='green' , color='cyan') spinner.animation t = Thread(target=lambda:spinner.start()) t.start() root.mainloop() while True: if root.quit: spinner.stop() exit(0) start()
python
20
0.617215
118
29.666667
111
starcoderdata
def _validate_target(self, target): """Do some basic validation on the target.""" parsed = urlparse(target) if self._is_local is True: self._target = os.path.abspath(target) if not os.path.isfile(self._target): raise SourceMapExtractorError("uri_or_file is set to be a file, but doesn't seem to exist. check your path.") else: if parsed.scheme == "": raise SourceMapExtractorError("uri_or_file isn't a URI, and --local was not set. set --local?") file, ext = os.path.splitext(parsed.path) self._target = target if ext != '.map' and self._attempt_sourcemap_detection is False: print("WARNING: URI does not have .map extension, and --detect is not flagged.")
python
12
0.592822
125
56.785714
14
inline
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 planbuilder import ( "fmt" "vitess.io/vitess/go/vt/sqlparser" "vitess.io/vitess/go/vt/vtgate/engine" ) var _ logicalPlan = (*subquery)(nil) // subquery is a logicalPlan that wraps a subquery. // This primitive wraps any subquery that results // in something that's not a route. It builds a // 'table' for the subquery allowing higher level // constructs to reference its columns. If a subquery // results in a route primitive, we instead build // a new route that keeps the subquery in the FROM // clause, because a route is more versatile than // a subquery. type subquery struct { logicalPlanCommon resultColumns []*resultColumn esubquery *engine.Subquery } // newSubquery builds a new subquery. func newSubquery(alias sqlparser.TableIdent, plan logicalPlan) (*subquery, *symtab, error) { sq := &subquery{ logicalPlanCommon: newBuilderCommon(plan), esubquery: &engine.Subquery{}, } // Create a 'table' that represents the subquery. t := &table{ alias: sqlparser.TableName{Name: alias}, origin: sq, } // Create column symbols based on the result column names. for _, rc := range plan.ResultColumns() { if _, ok := t.columns[rc.alias.Lowered()]; ok { return nil, nil, fmt.Errorf("duplicate column names in subquery: %s", sqlparser.String(rc.alias)) } t.addColumn(rc.alias, &column{origin: sq}) } t.isAuthoritative = true st := newSymtab() // AddTable will not fail because symtab is empty. _ = st.AddTable(t) return sq, st, nil } // Primitive implements the logicalPlan interface func (sq *subquery) Primitive() engine.Primitive { sq.esubquery.Subquery = sq.input.Primitive() return sq.esubquery } // ResultColumns implements the logicalPlan interface func (sq *subquery) ResultColumns() []*resultColumn { return sq.resultColumns } // SupplyCol implements the logicalPlan interface func (sq *subquery) SupplyCol(col *sqlparser.ColName) (rc *resultColumn, colNumber int) { c := col.Metadata.(*column) for i, rc := range sq.resultColumns { if rc.column == c { return rc, i } } // columns that reference subqueries will have their colNumber set. // Let's use it here. sq.esubquery.Cols = append(sq.esubquery.Cols, c.colNumber) sq.resultColumns = append(sq.resultColumns, &resultColumn{column: c}) return rc, len(sq.resultColumns) - 1 }
go
14
0.735084
100
29.552083
96
starcoderdata
void check_update(struct sockaddr_in network) { struct pkt_RT_UPDATE update_struct; socklen_t addr_len=sizeof(struct sockaddr_in); int i; if (time(0) - last_time_update_sent >= UPDATE_INTERVAL) { last_time_update_sent = time(0); for (i=0; i<num_neighbors; i++) { ConvertTabletoPkt(&update_struct, ID);// Need to set sender_id and send to all neighbors update_struct.dest_id = neighbor_list[i].neighbor; update_struct.sender_id = ID; hton_pkt_RT_UPDATE(&update_struct); sendto(udp_socket, (char*)(&update_struct), sizeof(update_struct), 0, (struct sockaddr*)(&network), addr_len); } } }
c
13
0.664577
116
38.9375
16
inline
<?php \frontend\assets\CompanyAsset::register($this); ?> <div class="ajax_windows_content" style="min-height: 600px"> <div id = "top_block"> <div id = "search"> <input type = "text" placeholder = "search..."> <div id = "button_group"> <input type = "button"value = "Добавить домен"> <div class="text_windows_content" style="min-width: 99%; width:100%"> компании <!-- cert metrica analytics --> <?php foreach($companies as $key => $company):?> <tr class = "select_element" id = "<?= $company->id?>"> $company->title ?> <?php endforeach;?> #top_block{ float: left; } #button_group{ float: right; }
php
6
0.564804
73
21.157895
38
starcoderdata
/** * A function with overloads * * @param {string} a * @return {string} */ /** * A function with overloads * * @param {number} a * @return {number} */ export default function func3 (a) { return }
javascript
3
0.597345
35
11.555556
18
starcoderdata
def __init__(self): super().__init__( "sqlite3", "sqlite> ", prompt_change=None, continuation_prompt=" ...> " ) # This is required to force suppression of command echo. self.child.setecho(False)
python
8
0.480144
64
26.8
10
inline
import React from 'react' import { FooterArea } from './styled' export default () => { return ( ) }
javascript
7
0.621212
44
15.583333
12
starcoderdata
#include #include #include #include #include #include #include #include "opencensus/trace/span.h" #ifdef BAZEL_BUILD #include "proto/foodfinder.grpc.pb.h" #else #include "foodfinder.grpc.pb.h" #endif class SupplierClient { public: SupplierClient(std::shared_ptr channel); foodfinder::VendorResponse RequestVendorList( const foodfinder::SupplyRequest& request, const opencensus::trace::Span& parentSpan); google::protobuf::Empty RegisterVendor(const foodfinder::Vendor& request); private: std::unique_ptr stub_; };
c
9
0.764706
75
23.4
30
starcoderdata
def create_report(self, template, data, tags=''): ''' creates new report and generates pdf based on data from new report ''' data.update({'STATIC_DIR': settings.REPORT_STATIC_DIR}) if isinstance(template, int): template = str(template) if isinstance(template, str): template = Report.objects.get(pk=template) report = self.model(template=template, name=Template(template.title_pattern).render(Context(data)), content=json.dumps(data), auto_tags=Template(template.tags_pattern).render(Context(data)), tags=' '.join(tags.split()), ) report.started = timezone.now() report.generate_pdf() report.finished = timezone.now() report.save() return report
python
13
0.544036
92
46.263158
19
inline
var baudio = require('webaudio'); var observable = require('observable'); var hyperquest = require('hyperquest'); var keycode = require('keycode'); var $ = require('../../polysynth/cheatcode') document.querySelector('#save').addEventListener('submit', onsubmit); function onsubmit (ev) { ev.preventDefault(); var title = this.elements.title.value; var href = location.protocol + '//' + location.host + '/' + encodeURIComponent(title) + '.json' ; var r = hyperquest.post(href); r.on('data', function (buf) { console.log(buf); }); r.end(JSON.stringify({ title: title, code: code.value })); if (window.history.pushState) { window.history.pushState({}, title, '/' + title); } document.querySelector('.history-link').setAttribute( 'href', '/-/history/' + encodeURIComponent(title) ); } var music = function (t) { return 0 }; var ascope = require('amplitude-viewer')(); ascope.appendTo('#ascope'); var work = require('webworkify'); var w = work(require('./fft.js')); var queue = []; w.addEventListener('message', function (ev) { queue.shift()(ev.data); }); var fscope = require('frequency-viewer')({ worker: function (data, cb) { queue.push(cb); w.postMessage(data); } }); fscope.appendTo('#fscope'); var play = document.querySelector('#play'); play.addEventListener('click', togglePlay); ascope.on('click', togglePlay); var paused = false; function togglePlay () { paused = !paused; play.textContent = paused ? 'play' : 'pause'; } window.addEventListener('resize', function (ev) { ascope.resize(); fscope.resize(); }); window.addEventListener('keydown', function (ev) { var name = keycode(ev); if (name === 'page up' || name === 'page down') { ev.preventDefault(); } document.body.scrollTop = 0; }); var code = document.querySelector('#code'); code.addEventListener('keydown', function (ev) { var name = keycode(ev); if (name === 'page up') { var x = code.scrollTop - code.offsetHeight; code.scrollTop = Math.max(0, x); } else if (name === 'page down') { var x = code.scrollTop + code.offsetHeight; code.scrollTop = Math.min(code.scrollHeight, x); } }); var state = {}; $.state = state var shoe = require('shoe'); var stream = shoe('/sock'); var split = require('split'); var through = require('through'); stream.pipe(split()).pipe(through(function (line) { try { var row = JSON.parse(line) } catch (err) { return } if (!row || typeof row !== 'object') return; var keys = Object.keys(row); for (var i = 0; i < keys.length; i++) { var key = keys[i] state[key] = row[key]; } state.updated = true try { music = Function(['$', 'TIME'], code.value)($, time) } catch (err) { return console.log(err) } state.updated = false })); observable.input(code)(function (source) { try { music = Function(['$', 'TIME'], source)($, time) } catch (err) { return console.log(err) } ascope.draw(function (t) { return music(t, state) }); }); setInterval(function f () { if (paused) return; ascope.setTime(time); ascope.draw(function (t) { return music(t, state) }); fscope.draw(data); }, 50); var time = 0; var data = new Float32Array(4000); var dataIx = 0; var b = baudio(function (t) { time = t; if (paused) return 0; var x = music(t, state); data[dataIx++ % data.length] = x; return x; }); b.play();
javascript
17
0.604684
69
25.930769
130
starcoderdata
<?php $month_arr = array('1'=>'มกราคม','2'=>'กุมภาพันธ์','3'=>'มีนาคม','4'=>'เมษายน','5'=>'พฤษภาคม','6'=>'มิถุนายน','7'=>'กรกฎาคม','8'=>'สิงหาคม','9'=>'กันยายน','10'=>'ตุลาคม','11'=>'พฤศจิกายน','12'=>'ธันวาคม'); function U2T($text) { return @iconv("UTF-8", "TIS-620//IGNORE", ($text)); } function num_format($text) { if($text!=''){ return number_format($text,2); }else{ return ''; } } function cal_age($birthday,$type = 'y'){ //รูปแบบการเก็บค่าข้อมูลวันเกิด $birthday = date("Y-m-d",strtotime($birthday)); $today = date("Y-m-d"); //จุดต้องเปลี่ยน list($byear, $bmonth, $bday)= explode("-",$birthday); //จุดต้องเปลี่ยน list($tyear, $tmonth, $tday)= explode("-",$today); //จุดต้องเปลี่ยน $mbirthday = mktime(0, 0, 0, $bmonth, $bday, $byear); $mnow = mktime(0, 0, 0, $tmonth, $tday, $tyear ); $mage = ($mnow - $mbirthday); //echo "วันเกิด $birthday"." //echo "วันที่ปัจจุบัน $today"." //echo "รับค่า $mage"." $u_y=date("Y", $mage)-1970; $u_m=date("m",$mage)-1; $u_d=date("d",$mage)-1; if($type=='y'){ return $u_y; }else if($type=='m'){ return $u_m; }else{ return $u_d; } } $pdf = new FPDI('P','mm', array(180,155)); $pdf->AddPage(); $pdf->AddFont('THSarabunNew', '', 'THSarabunNew.php'); $pdf->SetFont('THSarabunNew', '', 18 ); $pdf->SetMargins(0, 0, 0); $border = 0; $pdf->SetTextColor(0, 0, 0); $pdf->SetAutoPageBreak(false); $y_point = 128; $pdf->SetXY( 40, $y_point ); $pdf->MultiCell(80, 5, U2T($this->center_function->format_account_number($account_id)), $border, 1); $pdf->SetXY( 115, $y_point ); $pdf->MultiCell(40, 5, U2T($row['book_number']), $border, 1); $y_point = 138; $pdf->SetXY( 20, $y_point ); $pdf->MultiCell(100, 5, U2T($row['account_name']), $border, 1); $y_point = 149; $pdf->SetXY( 40, $y_point ); $pdf->MultiCell(45, 5, U2T($row['mem_id']), $border, 1); $pdf->SetXY( 115, $y_point ); $pdf->MultiCell(35, 5, U2T($row_gname['mem_group_name']), $border, 1); $y_point = 160; $pdf->SetXY( 25, $y_point ); $pdf->MultiCell(60, 5, U2T(date("d")." ".($month_arr[date('n')])." ".(date("Y") +543)), $border, 1); $pdf->Output();
php
17
0.564501
205
32.203125
64
starcoderdata
import React, { Component } from 'react'; import Options from './Options.js' import Players from './Players.js' import 'bootstrap/dist/css/bootstrap.min.css' class App extends Component { constructor(props){ super(props); this.defaultState = { startingBalance: 1500, salary: 200, players: [ // Dummy Data { name: " balance: 1500 }, { name: "Player 2", balance: 1500 } ] } this.state = this.defaultState this.addPlayer = this.addPlayer.bind(this) this.reset = this.reset.bind(this) this.setPlayerBalance = this.setPlayerBalance.bind(this) } setPlayerBalance(playerName, newBalance){ let newPlayers = this.state.players.slice() let player = newPlayers.find(function(player){return player.name===playerName}) player.balance = newBalance console.log(player) this.setState({players: newPlayers}) } // Options reset(){ this.setState(this.defaultState) } addPlayer(playerName){ const newPlayer = { name: playerName, balance: this.state.startingBalance } let currentPlayers = this.state.players.slice() currentPlayers.push(newPlayer) this.setState({players: currentPlayers}) } render() { return ( <div className="App"> <div className="container"> <h1 className="text-center display-3">Monopoly Money <Options startingBalance={this.state.startingBalance} addPlayer={this.addPlayer} reset={this.reset}/> <Players players={this.state.players} setPlayerBalance={this.setPlayerBalance}/> ); } } export default App;
javascript
13
0.628959
111
25.38806
67
starcoderdata
<nav class="navbar navbar-expand-lg main-navbar"> <ul class="navbar-nav mr-3"> href="#" data-toggle="sidebar" class="nav-link nav-link-lg"><i class="fas fa-bars"> <a href=" class="navbar-brand sidebar-gone-hide"><?= $this->session->userdata('pos_name'); ?> <!-- <a href=" <img alt="image" src=" class="sidebar-gone-hide mr-1"> --> <div class="nav-collapse"> <form class="form-inline ml-auto"> <ul class="navbar-nav"> <!-- href="#" data-toggle="search" class="nav-link nav-link-lg d-sm-none"><i class="fas fa-search"> --> <ul class="navbar-nav navbar-right"> <li class="dropdown dropdown-list-toggle"> <a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle notification-toggle nav-link-lg nav-link-user"> <div class="d-sm-none d-lg-inline-block">Selamat Datang, <?= $this->session->userdata('nama') ?> &nbsp; <img alt="image" src=" class="rounded-circle mr-1"> <?php if (in_array($this->session->userdata('role_name'), ROLE_ADMIN_CONTROL_NAME_LV1)) { ?> <div class="dropdown-menu dropdown-list dropdown-menu-right"> <div class="dropdown-header"> <div class="text-center"> <img alt="image" src=" class="rounded-circle" style="width: 80px; margin-top: 30px;"> <div class="pt-3" style="font-size: 15px; margin: 0px; padding: 0px; "> <?= $this->session->userdata('nama') ?> <div style="font-size: 12px; margin: 0px; font-weight: normal;"> <?= $this->session->userdata('role_name') ?> <div class="pb-2" style="font-size: 12px; margin: 0px; font-weight: normal; line-height: 0px;"> <div class="dropdown-list-content dropdown-list-icons"> <?php if (in_array($this->session->userdata('role_name'), ROLE_ADMIN_CONTROL_NAME_LV1)) { ?> <a href="<?= base_url('users'); ?>/switch/pusat" class="dropdown-item"> <div class="dropdown-item-icon bg-primary text-white"> <i class="fas fa-clinic-medical"> <div class="dropdown-item-desc"> Posyandu Data Pusat <div class="time text-primary">Pusat <?php } ?> <?php if (count($pos_session) > 0) { foreach ($pos_session as $key => $value) { ?> <a href="<?= base_url('users'); ?>/switch/<?= $value->id;?>" class="dropdown-item"> <div class="dropdown-item-icon bg-primary text-white"> <i class="fas fa-clinic-medical"> <div class="dropdown-item-desc"> Pos <?= $value->nama; ?> <div class="time text-primary">Desa <?= $value->desa; ?> <?php } } ?> <div class="dropdown-footer text-center"> <a href="<?= base_url('login/do_logout');?>" class="btn btn-danger btn-sm" ><i class="fas fa-sign-out-alt"> Logout <?php }else{ ?> <div class="dropdown-menu dropdown-menu-right"> <a href="<?= base_url('login/do_logout');?>" class="dropdown-item has-icon text-danger"> <i class="fas fa-sign-out-alt"> Logout <?php } ?>
php
12
0.463061
168
56.946667
75
starcoderdata
# SPDX-License-Identifier: Apache-2.0 ''' Blender 2.80 Adding a cube (if it doesn't exist) to an existing .blend file ''' import bpy from xrs import tools as xrs argv = xrs.get_command_line_arguments() model_name = xrs.get_filename_no_ext(); working_dir = xrs.get_working_dir(); width_in_mm = int(argv[0]) depth_in_mm = int(argv[1]) height_in_mm = int(argv[2]) print("Add Dimensions Cube to "+model_name+" from directory "+working_dir) print("Dimensions are "+str(width_in_mm)+"mm, "+str(depth_in_mm)+"mm, "+str(height_in_mm)+"mm, ") # Add the cube if it doesn't exist, otherwise select it if "DimensionsCube" in bpy.data.objects: xrs.delete_object_with_name("DimensionsCube") bpy.ops.mesh.primitive_cube_add(size=1,location=(0,0,height_in_mm/2000)) dimensions_cube = bpy.context.active_object; dimensions_cube.name = "DimensionsCube" dimensions_cube.data.name = "DimensionsCube_Mesh" dimensions_cube.scale = (width_in_mm/1000, depth_in_mm/1000, height_in_mm/1000); # Organize Collections if "Reference" in bpy.data.collections: collection = bpy.data.collections["Reference"] else: collection = bpy.data.collections.new("Reference") bpy.context.scene.collection.children.link(collection) bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection.children[-1] if "DimensionsCube" in bpy.context.scene.collection.objects: bpy.context.scene.collection.objects.unlink(dimensions_cube) if "DimensionsCube" not in collection: collection.objects.link(dimensions_cube) xrs.save();
python
12
0.74026
105
34.813953
43
starcoderdata
import sys import typing as T from .typing_compat import OneOrManyTypes __all__ = ( "Listx", "Tuplex", ) class ListxMeta(type): def __getitem__(self, params: OneOrManyTypes) -> T.Type["Listx"]: if not isinstance(params, tuple): params = (params,) if sys.version_info >= (3, 7): xlist_cls = T._GenericAlias(list, params, name="Listx") # type: ignore[attr-defined] else: xlist_cls = type("Listx", (), {"__args__": params, "__origin__": list}) return T.cast(T.Type["Listx"], xlist_cls) class Listx(metaclass=ListxMeta): ... class TuplexMeta(type): def __getitem__(self, params: OneOrManyTypes) -> T.Type["Tuplex"]: if not isinstance(params, tuple): params = (params,) if sys.version_info >= (3, 7): xtuple_cls = T._GenericAlias(tuple, params, name="Tuplex") # type: ignore[attr-defined] else: xtuple_cls = type("Tuplex", (), {"__args__": params, "__origin__": tuple}) return T.cast(T.Type["Tuplex"], xtuple_cls) class Tuplex(metaclass=TuplexMeta): ...
python
15
0.570928
100
24.954545
44
starcoderdata
package com.lzhlyle.poker.terrapin.domain.game; import com.lzhlyle.poker.core.card.PokerCard; import java.util.List; public class HandCardCollection { private int indexWithFirst; private PairCard head, tail; private List cards; private boolean isLock; public HandCardCollection(List cards) { if (cards == null || cards.size() != 4) throw new IllegalArgumentException(); this.cards = cards; this.indexWithFirst = 1; this.isLock = false; PairCard p1 = new PairCard(cards.get(0), cards.get(1)); PairCard p2 = new PairCard(cards.get(2), cards.get(3)); refreshHeadAndTail(p1, p2); } private void refreshHeadAndTail(PairCard p1, PairCard p2) { if (p1.compareTo(p2) > 0) { head = p1; tail = p2; return; } head = p2; tail = p1; } public boolean adjust() { if (isLock) return false; int i = indexWithFirst; this._adjust(i == 3 ? 1 : i + 1); return true; } private void _adjust(int indexWithFirst) { if (this.indexWithFirst == indexWithFirst) return; this.indexWithFirst = indexWithFirst; PairCard p1 = new PairCard(cards.get(0), cards.get(indexWithFirst)); PairCard p2; if (indexWithFirst == 1) { p2 = new PairCard(cards.get(2), cards.get(3)); } else if (indexWithFirst == 2) { p2 = new PairCard(cards.get(1), cards.get(3)); } else if (indexWithFirst == 3) { p2 = new PairCard(cards.get(1), cards.get(2)); } else throw new IllegalArgumentException(); refreshHeadAndTail(p1, p2); } public void lock() { isLock = true; } @Override public String toString() { return head + " " + tail; } public PairCard getHead() { return head; } public PairCard getTail() { return tail; } public boolean isLock() { return isLock; } public boolean isFish() { return head.isFish() && tail.isFish(); } }
java
15
0.552381
85
24.890244
82
starcoderdata
const mongoose = require('./db.js') const TestSchema = require('./testModal') // 定义model 操作数据库 const TestModal = mongoose.model('test', TestSchema) module.exports = TestModal
javascript
6
0.738636
52
24.285714
7
starcoderdata
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DB_project { public partial class Admin : Form { public Admin() { InitializeComponent(); } private void button12_Click(object sender, EventArgs e) { Login l = new Login(); l.Show(); this.Close(); } private void button4_Click(object sender, EventArgs e) { Add_product ad1 = new Add_product(); ad1.Show(); this.Close(); } private void button1_Click(object sender, EventArgs e) { Delete_Product d1 = new Delete_Product(); d1.Show(); this.Close(); } private void button5_Click(object sender, EventArgs e) { Update_Product u1 = new Update_Product(); u1.Show(); this.Close(); } private void button3_Click(object sender, EventArgs e) { Add_Salesman s1 = new Add_Salesman(); s1.Show(); this.Close(); } private void button7_Click(object sender, EventArgs e) { Delete_Salesman d1 = new Delete_Salesman(); d1.Show(); this.Close(); } private void button6_Click(object sender, EventArgs e) { Update_Salesman u1 = new Update_Salesman(); u1.Show(); this.Close(); } private void button2_Click(object sender, EventArgs e) { Add_Supplier s1 = new Add_Supplier(); s1.Show(); this.Close(); } private void button8_Click(object sender, EventArgs e) { Delete_Supplier d1p = new Delete_Supplier(); d1p.Show(); this.Close(); } private void button9_Click(object sender, EventArgs e) { Update_Supplier u1=new Update_Supplier(); u1.Show(); this.Close(); } private void button10_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); this.Close(); } private void button11_Click(object sender, EventArgs e) { view_invoice v1 = new view_invoice(); v1.Show(); this.Close(); } private void button13_Click(object sender, EventArgs e) { Pd_Expiry p = new Pd_Expiry(); p.Show(); this.Close(); } private void Admin_Load(object sender, EventArgs e) { } private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { } } }
c#
13
0.512005
106
23.438017
121
starcoderdata
const{SlashCommandBuilder}=require('@discordjs/builders') const{MessageEmbed}=require('discord.js') const{cpu,mem,os}=require('node-os-utils') module.exports={ data:new SlashCommandBuilder() .setName('info') .setDescription('Shows info about the bot'), async execute(interaction){ const{totalMemMb,usedMemMb}=await mem.info() const statEmbed = new MessageEmbed() .setTitle('Bot statistics') .addFields( {name:'Server OS',value:`${await os.oos()}`,inline:true}, {name:'CPU cores',value:`${cpu.count()}`,inline:true}, {name:'CPU usage',value:`${await cpu.usage()}%`,inline:true}, {name:'RAM usage',value:`${Math.round(usedMemMb)} MB/${Math.round(totalMemMb)} MB`} ) .setColor('#24ABF2') await interaction.reply({embeds:[statEmbed]}) } }
javascript
19
0.621653
95
38.090909
22
starcoderdata
require('dotenv').config({path: '.env'}); const _ = require('lodash'); const path = require('path'); const express = require('express'); const Hubspot = require('hubspot'); const bodyParser = require('body-parser'); const PORT = 3000; const CONTACTS_COUNT = 10; const CLIENT_ID = process.env.HUBSPOT_CLIENT_ID; const CLIENT_SECRET = process.env.HUBSPOT_CLIENT_SECRET; const SCOPES = 'contacts'; const REDIRECT_URI = `http://localhost:${PORT}/oauth-callback`; let tokenStore = {}; const checkEnv = (req, res, next) => { if (_.startsWith(req.url, '/error')) return next(); if (_.isNil(CLIENT_ID)) return res.redirect('/error?msg=Please set HUBSPOT_CLIENT_ID env variable to proceed'); if (_.isNil(CLIENT_SECRET)) return res.redirect('/error?msg=Please set HUBSPOT_CLIENT_SECRET env variable to proceed'); next(); }; const isAuthorized = () => { return !_.isEmpty(tokenStore.refresh_token); }; const isTokenExpired = () => { return Date.now() >= tokenStore.updated_at + tokenStore.expires_in * 1000; }; const prepareContactsContent = (contacts) => { return _.map(contacts, (contact) => { const companyName = _.get(contact, 'properties.company.value') || ''; const name = getFullName(contact.properties); return {vid: contact.vid, name, companyName}; }); }; const getFullName = (contactProperties) => { const firstName = _.get(contactProperties, 'firstname.value') || ''; const lastName = _.get(contactProperties, 'lastname.value') || ''; return `${firstName} ${lastName}` }; const refreshToken = async () => { hubspot = new Hubspot({ clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, redirectUri: REDIRECT_URI, scopes: SCOPES, refreshToken: tokenStore.refresh_token }); tokenStore = await hubspot.refreshAccessToken(); tokenStore.updated_at = Date.now(); console.log('Updated tokens', tokenStore); }; const app = express(); let hubspot = new Hubspot({ clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, redirectUri: REDIRECT_URI, scopes: SCOPES, }); app.use(express.static('public')); app.set('view engine', 'pug'); app.set('views', path.join(__dirname, 'views')); app.use(bodyParser.urlencoded({ limit: '50mb', extended: true, })); app.use(bodyParser.json({ limit: '50mb', extended: true, })); app.use(checkEnv); app.get('/', async (req, res) => { try { if (!isAuthorized()) return res.render('login'); if (isTokenExpired()) await refreshToken(); // Get all contacts // GET /contacts/v1/lists/all/contacts/all // https://developers.hubspot.com/docs/methods/contacts/get_contacts console.log('Calling contacts.get API method. Retrieve all contacts.'); const contactsResponse = await hubspot.contacts.get({count: CONTACTS_COUNT}); console.log('Response from API', contactsResponse); res.render('contacts', { tokenStore, contacts: prepareContactsContent(contactsResponse.contacts) }); } catch (e) { console.error(e); res.redirect(`/error?msg=${e.message}`); } }); app.use('/oauth', async (req, res) => { const authorizationUrlParams = { client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, scopes: SCOPES }; // Use the client to get authorization Url // https://www.npmjs.com/package/hubspot console.log('Creating authorization Url'); const authorizationUrl = hubspot.oauth.getAuthorizationUrl(authorizationUrlParams); console.log('Authorization Url', authorizationUrl); res.redirect(authorizationUrl); }); app.use('/oauth-callback', async (req, res) => { const code = _.get(req, 'query.code'); // Get OAuth 2.0 Access Token and Refresh Tokens // POST /oauth/v1/token // https://developers.hubspot.com/docs/methods/oauth2/get-access-and-refresh-tokens console.log('Retrieving access token by code:', code); tokenStore = await hubspot.oauth.getAccessToken({code}); console.log('Retrieving access token result:', tokenStore); tokenStore.updated_at = Date.now(); // Set token for the // https://www.npmjs.com/package/hubspot hubspot.setAccessToken((tokenStore.access_token)); res.redirect('/'); }); app.get('/login', (req, res) => { tokenStore = {}; res.redirect('/'); }); app.get('/refresh', async (req, res) => { if (isAuthorized()) await refreshToken(); res.redirect('/'); }); app.get('/error', (req, res) => { res.render('error', {error: req.query.msg}); }); app.use((error, req, res, next) => { res.render('error', {error: error.message}); }); app.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`));
javascript
16
0.676483
121
27.331288
163
starcoderdata
 using System; using System.Collections.Generic; using System.Text; using UnityEngine; using Verse; using Verse.AI; using RimWorld; namespace rjw { public class MapCom_Injector : MapComponent { public bool injected_designator = false; public bool triggered_after_load = false; public MapCom_Injector (Map m) : base (m) {} public override void MapComponentUpdate () {} public override void MapComponentTick () {} public override void MapComponentOnGUI () { if (! triggered_after_load) { triggered_after_load = true; if (Genital_Helper.pawns_require_sexualization ()) Genital_Helper.sexualize_everyone (); } var currently_visible = Find.VisibleMap == map; if ((! injected_designator) && currently_visible) { Find.ReverseDesignatorDatabase.AllDesignators.Add (new Designator_ComfortPrisoner ()); injected_designator = true; } else if (injected_designator && (! currently_visible)) injected_designator = false; } public override void ExposeData () {} } }
c#
15
0.68685
90
21.489362
47
starcoderdata
public async Task GetConsumerQuotaLimitRequestObjectAsync() { // Snippet: GetConsumerQuotaLimitAsync(GetConsumerQuotaLimitRequest, CallSettings) // Additional: GetConsumerQuotaLimitAsync(GetConsumerQuotaLimitRequest, CancellationToken) // Create client ServiceUsageClient serviceUsageClient = await ServiceUsageClient.CreateAsync(); // Initialize request argument(s) GetConsumerQuotaLimitRequest request = new GetConsumerQuotaLimitRequest { Name = "", View = QuotaView.Unspecified, }; // Make the request ConsumerQuotaLimit response = await serviceUsageClient.GetConsumerQuotaLimitAsync(request); // End snippet }
c#
12
0.650694
103
48.625
16
inline
import common lines = common.read_file('2015/18/data.txt').splitlines() initial_state = [] for line in lines: row = [] for c in line: val = 1 if c == '#' else 0 row.append(val) initial_state.append(row) w = len(initial_state[0]) h = len(initial_state) current = initial_state steps = 100 def run_step(current): def at(x, y): if x < 0 or x >= w or y < 0 or y >= h: return 0 return current[y][x] result = [] for y in range(h): row = [] for x in range(w): neighbors = sum([ at(x, y-1), at(x+1, y-1), at(x+1, y), at(x+1, y+1), at(x, y+1), at(x-1, y+1), at(x-1, y), at(x-1, y-1) ]) me = current[y][x] if me == 1 and (neighbors == 2 or neighbors == 3): row.append(1) elif me == 0 and neighbors == 3: row.append(1) else: row.append(0) result.append(row) return result # part 1 for i in range(steps): current = run_step(current) on_num = sum(map(sum, current)) print(on_num) # part 2 current = initial_state def update_corners(): current[0][0] = 1 current[0][-1] = 1 current[-1][0] = 1 current[-1][-1] = 1 update_corners() for i in range(steps): current = run_step(current) update_corners() on_num = sum(map(sum, current)) print(on_num)
python
15
0.473927
62
19.753425
73
starcoderdata
$(function(){ $('.delete_link, .sonata-ba-form-actions .btn-danger').magnificPopup({ type: 'ajax', closeBtnInside: true, mainClass: 'mfp-fade' }); });
javascript
12
0.60479
71
23
7
starcoderdata
from bpfilter_bme590hrm import butter_bandpass from bpfilter_bme590hrm import butter_bandpass_filter from num_beats_bme590hrm import n_beats from beat_times_bme590hrm import beat_times from mean_bpm_bme590hrm import mean_bpm from duration_bme590hrm import duration_hrm from readCSV_bme590hrm import load_CSV from new_readCSV_bme590hrm import new_load_CSV from volt_extremes_bme590hrm import volt_extremes from dictionary_bme590hrm import hrm_dictionary def main(): """Run all of the functions to find the mean heart rate, voltage extremes, duration, number of beats, and beat times for an imported ECG signal """ try: time, voltage, filename, df = load_CSV() except FileNotFoundError: filename = input("Input filename ") time, voltage, df = new_load_CSV(filename) fs = 1000.0 lowcut = 0.5 highcut = 150.0 butter_bandpass(lowcut, highcut, fs, order=5) filtdat = butter_bandpass_filter(voltage, lowcut, highcut, fs, order=5) voltage_extremes = volt_extremes(filtdat) loc, dif, num_beats = n_beats(time, filtdat) beats = beat_times(time, loc, dif) duration = duration_hrm(time) try: mean_hr_bpm = mean_bpm(inmin=None, num_beats, duration) except TypeError: mean_hr_bpm = mean_bpm(inmin=None, num_beats, duration) hrm_dictionary(beats, num_beats, duration, voltage_extremes, mean_hr_bpm, filename) if __name__ == "__main__": main()
python
11
0.697548
75
34.804878
41
starcoderdata
info = ''' #==============================================================================# title :numbers_nance.py description :numbers assignment... author : date :2022-03-13 version :1.0 usage :python numbers_nance.py notes : python_version :3.10 #==============================================================================# ''' ## MODULES import sys ## VARIABLES numberOfArgs = len(sys.argv) ## MAIN SCRIPT print("\nNumbering Systems with Python\n", info) print("Total arguments passed: " + str(numberOfArgs)) for arg in range(numberOfArgs): # List all arguments passed. print("Argument", str(arg+1)+':', sys.argv[arg]) # Arguement #: def convertNumbers(): numberAsAString = '' numberAsAnInt = 0 numberAsHex = hex(0) print() try: numberAsAString = sys.argv[1] numberAsAnInt = int(numberAsAString, base=10) numberAsHex = hex(numberAsAnInt) print("Input: " + numberAsAString) print("Hex: " + numberAsHex) print("Number: " + str(numberAsAnInt)) except ValueError as error: print('[ERROR]: The 2nd argument MUST be an integer.') if numberOfArgs == 2: convertNumbers() elif numberOfArgs == 1: print("You must pass an additional INTEGER argument...") else: print("Too many arguments passed, only using the 2nd one...") convertNumbers()
python
11
0.545703
80
28.918367
49
starcoderdata
<?php declare(strict_types=1); namespace GacelaTest\Feature\Framework\BindingInterfacesWithInnerDependencies\LocalConfig; use Gacela\Framework\AbstractFactory; use GacelaTest\Feature\Framework\BindingInterfacesWithInnerDependencies\LocalConfig\Domain\GreeterGeneratorInterface; use GacelaTest\Feature\Framework\BindingInterfacesWithInnerDependencies\LocalConfig\Domain\GreeterService; final class Factory extends AbstractFactory { private GreeterGeneratorInterface $greeterGenerator; public function __construct(GreeterGeneratorInterface $greeterGenerator) { $this->greeterGenerator = $greeterGenerator; } public function createGreeterService(): GreeterService { return new GreeterService($this->greeterGenerator); } }
php
11
0.822171
117
33.64
25
starcoderdata
const rules = require('../configs/rules.config') const { aliases } = require('../configs/aliases.config') module.exports = ({ config }) => { config.module.rules = rules config.resolve.alias = aliases; config.resolve.extensions.push(".ts", ".tsx") return config; }
javascript
9
0.675
56
31
10
starcoderdata
/** * Tailwind CSS configuration file * * docs: https://tailwindcss.com/docs/configuration * default: https://github.com/tailwindcss/tailwindcss/blob/master/stubs/defaultConfig.stub.js */ module.exports = { mode: 'jit', theme: {}, purge: [ './assets/*.js', './assets/!(style).css', './layout/*.liquid', './sections/*.liquid', './snippets/*.liquid', './templates/*.liquid' ] }
javascript
7
0.610169
94
20.789474
19
starcoderdata
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class UpdateDtMerchants extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::table('merchants')->join('franchises', 'merchants.id', '=', 'franchises.merchant_id') ->where('merchants.vendor', 'detroit_trading') ->update(array('franchises.is_used_car_leads' => '1')); } /** * Reverse the migrations. * * @return void */ public function down() { DB::table('merchants')->join('franchises', 'merchants.id', '=', 'franchises.merchant_id') ->where('merchants.vendor', 'detroit_trading') ->update(array('franchises.is_used_car_leads' => '0')); } }
php
13
0.621192
91
22.59375
32
starcoderdata
def fast_stickers_get(link, found): url_stickers = 'https://t.me/addstickers/' + link # getting data from link r_stickers = requests.get(url_stickers, stream=True) soup_stickers = bs4.BeautifulSoup(r_stickers.text, "lxml", ) type_link = str(soup_stickers.find_all('div', class_="tgme_page_description")).replace(u'\xa0', ' ').replace(';', ':') if re.search('Sticker Set', type_link): # check for channel return found else: found += 's,' return found
python
15
0.51634
117
54.727273
11
inline
package ru.otus.l62.b1.command2; /** * */ public class AuthorizationService { public boolean auth(String login, String pass) { System.out.println("invoke auth service()"); return (login.equals("admin") && pass.equals(" } }
java
11
0.636364
68
23
11
starcoderdata
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { //Console.WriteLine("Hello World!"); ConsoleApp1.Building[] buildings = new ConsoleApp1.Building[20]; ConsoleApp1.House Casa1= new ConsoleApp1.House(150000); ConsoleApp1.Apartment apartament1 = new ConsoleApp1.Apartment(35000); ConsoleApp1.StudioApartment garsoniera1 = new ConsoleApp1.StudioApartment(15000); buildings[0] = Casa1; buildings[1] = apartament1; buildings[2] = garsoniera1; Console.WriteLine(buildings[0].get_price()); } } }
c#
16
0.611607
93
32.6
20
starcoderdata
private void show(String windowTitle) { stage = new Stage(); Parent root; try { root = FXMLLoader.load(MOTDDialog.class.getResource("MOTDDialog.fxml"), bundle); scene = new Scene(root); stage.getIcons().add(new Image(new URL(motd.getImage().getUrl()).openStream())); // scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); // Set the window title stage.setTitle(windowTitle); stage.setMinWidth(scene.getRoot().minWidth(0) + 70); stage.setMinHeight(scene.getRoot().minHeight(0) + 70); stage.setScene(scene); stage.show(); } catch (IOException e) { FOKLogger.log(MOTDDialog.class.getName(), Level.SEVERE, FOKLogger.DEFAULT_ERROR_TEXT, e); } }
java
16
0.587135
102
37.909091
22
inline
package ie.gmit.sw.repositories; import ie.gmit.sw.chess.game.Player; import org.springframework.data.repository.CrudRepository; public interface PlayerRepository extends CrudRepository<Player, Integer> { /** * @param name the name of the player you're looking for * @return the player going by that name. */ default Player findByName(String name) { Iterable allPlayers = findAll(); for (Player player : allPlayers) { if (player.getName().equalsIgnoreCase(name)) { return player; } } return null; } }
java
10
0.660793
75
29.954545
22
starcoderdata
from more_itertools import windowed, first_true data = map(int, open('d9.txt')) windowed_data = windowed(data, 26) def sum2(window, target): return all(e1 + e2 != target for e1 in window for e2 in window) def pred(datum): *window, target = datum return sum2(window, target) print(first_true(windowed_data, pred=pred)[-1])
python
8
0.705706
67
36.111111
9
starcoderdata
<?php namespace LetsEncryptDNSClient; /** Account info interface */ interface AccountInfoInterface { /** * Get account contact E-mails * * @return string[] Account contact E-mails * @throws LetsEncryptDNSClientException */ public function getAccountContactEmails(); /** * Get private key * * @return string|null Private key if there's an existing account. Null to create a new account. * @throws LetsEncryptDNSClientException */ public function getPrivateKey(); /** * Save private key * * @param string $privateKey Private key * * @throws LetsEncryptDNSClientException */ public function savePrivateKey($privateKey); }
php
7
0.718608
97
19.65625
32
starcoderdata
BOOL CSessionSocket::TransactionLog( LPSTR lpstrOperation, LPSTR lpstrTarget, LPSTR lpstrParameters, STRMPOSITION cbBytesSent, DWORD cbBytesRecvd, DWORD dwProtocol, DWORD dwWin32, BOOL fInBound ) { INETLOG_INFORMATION request; CHAR ourIP[32]; CHAR theirIP[32]; CHAR pszError[MAX_ERROR_MESSAGE_LEN] = ""; DWORD cchError= MAX_ERROR_MESSAGE_LEN; LPSTR lpUserName; LPSTR lpNull = ""; static char szNntpVersion[]="NNTP"; DWORD err; IN_ADDR addr; FILETIME now; ULARGE_INTEGER liStart; ULARGE_INTEGER liNow; ENTER("TransactionLog") // // see if we are only logging errors. // if (m_context.m_pInstance->GetCommandLogMask() & eErrorsOnly) { // make sure that this is an error (dwProtocol >= 400 and < 600) if (!(NNTPRET_IS_ERROR(dwProtocol))) return TRUE; } // // Fill out client information // ZeroMemory( &request, sizeof(request)); addr.s_addr = m_remoteIpAddress; lstrcpy(theirIP, inet_ntoa( addr )); request.pszClientHostName = theirIP; request.cbClientHostName = strlen(theirIP); // // user logged on as? // if( fInBound ) { if( lpUserName = GetUserName() ) { request.pszClientUserName = lpUserName; } else { request.pszClientUserName = "<user>"; } } else { request.pszClientUserName = "<feed>" ; } // // Who are we ? // addr.s_addr = m_localIpAddress; lstrcpy(ourIP,inet_ntoa( addr )); request.pszServerAddress = ourIP; // // How long were we processing this? // GetSystemTimeAsFileTime( &now ); LI_FROM_FILETIME( &liNow, &now ); LI_FROM_FILETIME( &liStart, &m_startTime ); // // Get the difference of start and now. This will give // us total 100 ns elapsed since the start. Convert to ms. // liNow.QuadPart -= liStart.QuadPart; liNow.QuadPart /= (ULONGLONG)( 10 * 1000 ); request.msTimeForProcessing = liNow.LowPart; // // Bytes sent/received // //CopyMemory( &request.liBytesSent, &cbBytesSent, sizeof(cbBytesSent) ); request.dwBytesSent = (DWORD)(LOW(cbBytesSent)); request.dwBytesRecvd = cbBytesRecvd ; // // status // request.dwWin32Status = dwWin32; request.dwProtocolStatus = dwProtocol ; if( lpstrOperation ) { request.pszOperation = lpstrOperation ; request.cbOperation = strlen(lpstrOperation); } else { request.pszOperation = lpNull; request.cbOperation = 0; } if( lpstrTarget ) { request.pszTarget = lpstrTarget ; request.cbTarget = strlen(lpstrTarget) ; } else { request.pszTarget = lpNull; request.cbTarget = 0; } if( lpstrParameters ) { request.pszParameters = lpstrParameters ; } else { request.pszParameters = lpNull; } request.cbHTTPHeaderSize = 0 ; request.pszHTTPHeader = NULL ; request.dwPort = m_nntpPort; request.pszVersion = szNntpVersion; // // Do the actual logging // err = ((m_context.m_pInstance)->m_Logging).LogInformation( &request ); if ( err != NO_ERROR ) { ErrorTrace(0,"Error %d Logging information!\n",GetLastError()); return(FALSE); } return(TRUE); }
c++
11
0.612845
74
21.314685
143
inline
/* References: * https://lists.samba.org/archive/samba-technical/2009-February/063079.html * http://stackoverflow.com/questions/4139405/#4139811 * https://github.com/steve-o/openpgm/blob/master/openpgm/pgm/getifaddrs.c */ #include <string.h> #include <stdlib.h> #include <unistd.h> #include <net/if.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/sockio.h> #include "ifaddrs.h" #define MAX(x,y) ((x)>(y)?(x):(y)) #define SIZE(p) MAX((p).ss_len,sizeof(p)) static struct sockaddr * sa_dup (struct sockaddr_storage *sa1) { struct sockaddr *sa2; size_t sz = sizeof(struct sockaddr_storage); sa2 = (struct sockaddr *) calloc(1,sz); memcpy(sa2,sa1,sz); return(sa2); } void freeifaddrs (struct ifaddrs *ifp) { if (NULL == ifp) return; free(ifp->ifa_name); free(ifp->ifa_addr); free(ifp->ifa_netmask); free(ifp->ifa_dstaddr); freeifaddrs(ifp->ifa_next); free(ifp); } int getifaddrs (struct ifaddrs **ifap) { int sd = -1; char *ccp, *ecp; struct lifconf ifc; struct lifreq *ifr; struct lifnum lifn; struct ifaddrs *cifa = NULL; /* current */ struct ifaddrs *pifa = NULL; /* previous */ const size_t IFREQSZ = sizeof(struct lifreq); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) goto error; ifc.lifc_buf = NULL; *ifap = NULL; /* find how much memory to allocate for the SIOCGLIFCONF call */ lifn.lifn_family = AF_UNSPEC; lifn.lifn_flags = 0; if (ioctl(sd, SIOCGLIFNUM, &lifn) < 0) goto error; /* Sun and Apple code likes to pad the interface count here in case interfaces * are coming up between calls */ lifn.lifn_count += 4; ifc.lifc_family = AF_UNSPEC; ifc.lifc_len = lifn.lifn_count * sizeof(struct lifreq); ifc.lifc_buf = calloc(1, ifc.lifc_len); if (ioctl(sd, SIOCGLIFCONF, &ifc) < 0) goto error; ccp = (char *)ifc.lifc_req; ecp = ccp + ifc.lifc_len; while (ccp < ecp) { ifr = (struct lifreq *) ccp; cifa = (struct ifaddrs *) calloc(1, sizeof(struct ifaddrs)); cifa->ifa_next = NULL; cifa->ifa_name = strdup(ifr->lifr_name); if (pifa == NULL) *ifap = cifa; /* first one */ else pifa->ifa_next = cifa; if (ioctl(sd, SIOCGLIFADDR, ifr, IFREQSZ) < 0) goto error; cifa->ifa_addr = sa_dup(&ifr->lifr_addr); if (ioctl(sd, SIOCGLIFNETMASK, ifr, IFREQSZ) < 0) goto error; cifa->ifa_netmask = sa_dup(&ifr->lifr_addr); cifa->ifa_flags = 0; cifa->ifa_dstaddr = NULL; if (0 == ioctl(sd, SIOCGLIFFLAGS, ifr)) /* optional */ cifa->ifa_flags = ifr->lifr_flags; if (ioctl(sd, SIOCGLIFDSTADDR, ifr, IFREQSZ) < 0) { if (0 == ioctl(sd, SIOCGLIFBRDADDR, ifr, IFREQSZ)) cifa->ifa_dstaddr = sa_dup(&ifr->lifr_addr); } else cifa->ifa_dstaddr = sa_dup(&ifr->lifr_addr); pifa = cifa; ccp += IFREQSZ; } free(ifc.lifc_buf); close(sd); return 0; error: if (ifc.lifc_buf != NULL) free(ifc.lifc_buf); if (sd != -1) close(sd); freeifaddrs(*ifap); return (-1); }
c
14
0.587585
82
25.032
125
research_code
<?php namespace app\models; use config\Config; use yii\base\Model; use yii\base\ModelEvent; use yii\db\ActiveRecord; use yii\db\BaseActiveRecord; use yiidreamteam\upload\ImageUploadBehavior; class MapImage extends ActiveRecord { /** @var string */ public $image; /** @var boolean */ public $image_remove = 0; public $isNewRecord = true; public static function tableName() { return '{{%config}}'; } public function __construct(array $config = []) { parent::__construct($config); $record = Config::findOne(['key' => 'map_image']); if (!is_null($record)) { $this->image = $record->value; } } public function behaviors() { return [ 'image' => [ 'class' => ImageUploadBehavior::className(), 'attribute' => 'image', 'filePath' => '@webroot/uploads/map/[[filename]].[[extension]]', 'fileUrl' => '/uploads/map/[[filename]].[[extension]]', ], ]; } public function rules() { return [ [['image'], 'trim'], [['image_remove'], 'boolean'] ]; } public function attributeLabels() { return [ 'image' => 'Изображение карты феста' ]; } public function save($runValidation = true, $attributeNames = null) { if ($this->image_remove) { $this->getBehavior('image')->cleanFiles(); $this->image = ''; $record = Config::findOne(['key' => 'map_image']); if (is_null($record)) { $record = new Config(); $record->key = 'map_image'; } $record->value = $this->image; $record->save(); return; } $this->beforeValidate(); $this->trigger(BaseActiveRecord::EVENT_BEFORE_INSERT, new ModelEvent()); if ($this->image == '') { // case when there is old image $this->refresh(); return; } $record = Config::findOne(['key' => 'map_image']); if (is_null($record)) { $record = new Config(); $record->key = 'map_image'; } $record->value = $this->image; $record->save(); $this->trigger(BaseActiveRecord::EVENT_AFTER_INSERT, new ModelEvent()); } public function refresh() { $record = Config::findOne(['key' => 'map_image']); if (!is_null($record)) { $this->image = $record->value; } } }
php
15
0.487122
84
22.103448
116
starcoderdata
#include <bits/stdc++.h> using namespace std; char f(int t){if(t==0){return 'z';} if(t==1){return 'a';} if(t==2){return 'b';} if(t==3){return 'c';} if(t==4){return 'd';} if(t==5){return 'e';} if(t==6){return 'f';} if(t==7){return 'g';} if(t==8){return 'h';} if(t==9){return 'i';} if(t==10){return 'j';} if(t==11){return 'k';} if(t==12){return 'l';} if(t==13){return 'm';} if(t==14){return 'n';} if(t==15){return 'o';} if(t==16){return 'p';} if(t==17){return 'q';} if(t==18){return 'r';} if(t==19){return 's';} if(t==20){return 't';} if(t==21){return 'u';} if(t==22){return 'v';} if(t==23){return 'w';} if(t==24){return 'x';} if(t==25){return 'y';} } int main() { long long n; cin>>n; vector<long long> kotae; while(n!=0){kotae.push_back(n%26);n=(n-1)/26;} long long a=kotae.size(); for(long long i=0;i<a;i++){cout<<f(kotae.at(a-i-1));} }
c++
13
0.384294
53
28.95
40
codenet
<?php declare(strict_types=1); namespace OpenTelemetry\Tests\Unit\SDK\Common\Attribute; use OpenTelemetry\SDK\Common\Attribute\Attributes; use PHPUnit\Framework\TestCase; /** * @covers \OpenTelemetry\SDK\Common\Attribute\Attributes * @covers \OpenTelemetry\SDK\Common\Attribute\AttributesBuilder * @covers \OpenTelemetry\SDK\Common\Attribute\AttributesFactory */ class AttributesTest extends TestCase { public function test_has_attribute(): void { $attributes = Attributes::create([ 'foo' => 'foo', ]); $this->assertFalse($attributes->has('bar')); $attributes = Attributes::create([ 'foo' => 'foo', 'bar' => 'bar', ]); $this->assertTrue($attributes->has('bar')); } /** Test numeric attribute key is not cast to integer value */ public function test_numeric_attribute_name(): void { $attributes = Attributes::create(['1' => '2']); $this->assertCount(1, $attributes); foreach ($attributes as $key => $value) { $this->assertIsString($key); $this->assertIsString($value); } } /** * @psalm-suppress PossiblyNullReference */ public function test_attribute_limits(): void { $intValue = 42; $floatValue = 3.14; $shortStringValue = '0123'; $longStringValue = '0123456789abcdefghijklmnopqrstuvwxyz'; $longStringTrimmed = '0123456789abcdef'; $attributes = Attributes::factory(6, 16)->builder([ 'bool' => true, 'int' => $intValue, 'float' => $floatValue, 'short_string' => $shortStringValue, 'long_string' => $longStringValue, 'array' => [ $shortStringValue, $longStringValue, true, ], 'ignored_key' => 'ignored_value', ])->build(); $this->assertTrue($attributes->get('bool')); $this->assertEquals($intValue, $attributes->get('int')); $this->assertEquals($floatValue, $attributes->get('float')); $this->assertEquals($shortStringValue, $attributes->get('short_string')); $this->assertEquals($longStringTrimmed, $attributes->get('long_string')); $this->assertEquals([$shortStringValue, $longStringTrimmed, true], $attributes->get('array')); $this->assertEquals(6, $attributes->count()); $this->assertNull($attributes->get('ignored_key')); } /** * @psalm-suppress PossiblyNullReference */ public function test_apply_limits(): void { $attributes = Attributes::create([ 'short' => '123', 'long' => '1234567890', 'dropped' => true, ]); $limitedAttributes = Attributes::factory(2, 5)->builder($attributes)->build(); $this->assertCount(2, $limitedAttributes); $this->assertEquals('123', $limitedAttributes->get('short')); $this->assertEquals('12345', $limitedAttributes->get('long')); $this->assertNull($limitedAttributes->get('dropped')); $this->assertGreaterThan(0, $limitedAttributes->getDroppedAttributesCount()); } public function test_null_attribute_removes_existing(): void { $attributesBuilder = Attributes::factory()->builder([ 'foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz', ]); $this->assertCount(3, $attributesBuilder->build()); $attributesBuilder['foo'] = null; $this->assertCount(2, $attributesBuilder->build()); } public function test_null_missing_attribute_does_nothing(): void { $attributesBuilder = Attributes::factory()->builder([ 'foo' => 'foo', ]); $this->assertCount(1, $attributesBuilder->build()); $attributesBuilder['bar'] = null; $this->assertCount(1, $attributesBuilder->build()); } public function test_to_array(): void { $values = [ 'foo' => 'foo', 'bar' => 'bar', ]; $attributes = Attributes::create($values); $this->assertSame($values, $attributes->toArray()); } public function test_get_dropped_attributes_count(): void { $attributesBuilder = Attributes::factory()->builder([ 'foo' => 'foo', 'bar' => 'bar', ]); $this->assertEquals(0, $attributesBuilder->build()->getDroppedAttributesCount()); $attributesBuilder['baz'] = 'baz'; $this->assertEquals(0, $attributesBuilder->build()->getDroppedAttributesCount()); } public function test_unset_get_dropped_attributes_count(): void { $attributesBuilder = Attributes::factory()->builder([ 'foo' => 'foo', 'bar' => 'bar', ]); $this->assertEquals(0, $attributesBuilder->build()->getDroppedAttributesCount()); $attributesBuilder->offsetUnset('foo'); $this->assertEquals(0, $attributesBuilder->build()->getDroppedAttributesCount()); } public function test_limit_get_dropped_attributes_count(): void { $attributesBuilder = Attributes::factory(1)->builder([ 'foo' => 'foo', 'bar' => 'bar', ]); $this->assertEquals(1, $attributesBuilder->build()->getDroppedAttributesCount()); $attributesBuilder['baz'] = 'baz'; $this->assertEquals(2, $attributesBuilder->build()->getDroppedAttributesCount()); } public function test_replace_attribute_does_not_increase_dropped_attributes_count(): void { $attributesBuilder = Attributes::factory(2)->builder([ 'foo' => 'foo', ]); $attributesBuilder['foo'] = 'bar'; $this->assertEquals(0, $attributesBuilder->build()->getDroppedAttributesCount()); } }
php
16
0.578317
102
32.609195
174
starcoderdata
private ClassDeclarationSyntax GenerateRecordDeclarations(ClassDeclarationSyntax classDeclaration, Block block) { foreach (var typeDefinition in block.Types.Where(x => x is RecordTypeDefinition)) { var recordType = (RecordTypeDefinition) typeDefinition; classDeclaration = classDeclaration.AddMembers(GenerateRecordType(recordType)); } // add anonymous variables foreach (var typeDefinition in block.Declarations.Where(x => x.Type is RecordTypeDefinition)) { var recordType = (RecordTypeDefinition) typeDefinition.Type; if (string.IsNullOrEmpty(recordType.Name)) // anonymous type... // Name is updated with call to GenerateRecordType { classDeclaration = classDeclaration.AddMembers(GenerateRecordType(recordType)); } } return classDeclaration; }
c#
16
0.603736
111
45.272727
22
inline
<?php declare(strict_types=1); namespace Clapi\Authentication; class EscherCredential extends Credential { /** * @var string */ private $scope; public function __construct(string $key, string $secret, string $scope) { parent::__construct($key, $secret); $this->scope = $scope; } public function getScope(): string { return $this->scope; } }
php
10
0.610092
75
17.956522
23
starcoderdata
// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ #include #include #include using namespace vw; TEST(ErodeView, basic_test) { ImageView > test(3,3); EXPECT_EQ( PixelMask test(0,0) ); EXPECT_FALSE( is_valid(test(0,0)) ); test(1,1) = PixelMask EXPECT_TRUE( is_valid(test(1,1)) ); BlobIndexThreaded bindex( test, 100 ); EXPECT_EQ( 1u, bindex.num_blobs() ); ImageViewRef > erode_ref = ErodeView > >( test, bindex ); EXPECT_FALSE( is_valid(erode_ref(1,1)) ); EXPECT_FALSE( is_valid(erode_ref(0,0)) ); ImageView > eroded = erode_ref; EXPECT_FALSE( is_valid(eroded(0,0) ) ); EXPECT_FALSE( is_valid(eroded(1,1) ) ); EXPECT_EQ( 0, eroded(1,1).child() ); } TEST(ErodeView, larger_test) { ImageView > test(5,5); /* Set up this image: X X . X . . . X X . X . . . X X X . X X X . . X X */ test(0,0) = PixelMask test(0,1) = PixelMask test(0,3) = PixelMask test(1,2) = PixelMask test(1,3) = PixelMask test(2,0) = PixelMask test(2,4) = PixelMask test(3,0) = PixelMask test(3,1) = PixelMask test(3,3) = PixelMask test(3,4) = PixelMask test(4,0) = PixelMask test(4,3) = PixelMask test(4,4) = PixelMask /* Set up this erosion mask: . . . . . . . X . . . . . . . . X . X X . . . . . */ ImageView > blobs(5,5); blobs(1,2) = PixelMask blobs(3,1) = PixelMask blobs(3,3) = PixelMask blobs(3,4) = PixelMask // Process blobs BlobIndexThreaded bindex( blobs, 100, 100 ); EXPECT_EQ( 3u, bindex.num_blobs() ); // Set up blobs as erosion mask on image ImageViewRef > erode_ref = ErodeView > >( test, bindex ); EXPECT_FALSE( is_valid(erode_ref(1,0)) ); EXPECT_FALSE( is_valid(erode_ref(1,2)) ); EXPECT_TRUE ( is_valid(erode_ref(4,4) ) ); ImageView > eroded = erode_ref; EXPECT_FALSE( is_valid(eroded(3,2) ) ); EXPECT_FALSE( is_valid(eroded(3,4) ) ); EXPECT_TRUE ( is_valid(eroded(4,3) ) ); }
c++
15
0.638648
76
30
104
starcoderdata
public static DateTimeValue parse(Calendar cal, DateTimeType type) { int sYear = 0; int sMonthDay = 0; int sTime = 0; int sFractionalSecs = 0; boolean sPresenceTimezone = false; int sTimezone; switch (type) { case gYear: // gYear Year, [Time-Zone] case gYearMonth: // gYearMonth Year, MonthDay, [TimeZone] case date: // date Year, MonthDay, [TimeZone] sYear = cal.get(Calendar.YEAR); sMonthDay = getMonthDay(cal); break; case dateTime: // dateTime Year, MonthDay, Time, [FractionalSecs], // [TimeZone] sYear = cal.get(Calendar.YEAR); sMonthDay = getMonthDay(cal); // Note: *no* break; case time: // time Time, [FractionalSecs], [TimeZone] sTime = getTime(cal); sFractionalSecs = cal.get(Calendar.MILLISECOND); break; case gMonth: // gMonth MonthDay, [TimeZone] case gMonthDay: // gMonthDay MonthDay, [TimeZone] case gDay: // gDay MonthDay, [TimeZone] sMonthDay = getMonthDay(cal); break; default: throw new UnsupportedOperationException(); } // [TimeZone] sTimezone = getTimeZoneInMinutesOffset(cal); if (sTimezone != 0) { sPresenceTimezone = true; } return new DateTimeValue(type, sYear, sMonthDay, sTime, sFractionalSecs, sPresenceTimezone, sTimezone); }
java
11
0.6872
68
28.785714
42
inline
public void toMenuPlot() { currentState = WorldState.MENU; InputHandler.setMenu(MenuUI.PLOT); // run a method that creates all the menu buttons // so 4 possible menu's that we can go to, or is it 5? InputHandler.clearMenuButtons(); Player currentPlayer = getPlayer(gameState); if (currentPlayer != null) { switch (currentPlayer.getState()) { case PLOT: InputHandler.LoadPlotPlotMenu(); break; case BUY: case END: InputHandler.LoadPlotBuyMenu(); break; case PLACE: InputHandler.LoadPlotPlaceMenu(); break; } } }
java
11
0.685413
56
24.909091
22
inline
def load_data(database_filepath): ''' This function loads data from a database table Return x = sentence, y = categories ''' # load data from database database = str('sqlite:///'+ database_filepath) engine = create_engine(database) sqlquery = 'SELECT * FROM disaster_clean' df = pd.read_sql_query(sqlquery,con=engine) # extract message column from dataframe X = df['message'].values # drop unnecessary columns from dataframe df.drop(['id','message','original','genre'],axis=1, inplace=True) # extract 36 categories y = df[list(df.columns)].values return X, y, df.columns
python
10
0.638847
69
29
22
inline
import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import intl from 'react-intl-universal'; import { SingleSelectFormatter } from 'dtable-ui-component'; import DetailDuplicationDialog from './detail-duplication-dialog'; import styles from '../css/plugin-layout.module.css'; const EMPTY_CELL_CONTENT = intl.get('Empty'); class TableView extends React.Component { constructor(props) { super(props); this.state = { expandRowIndex: -1, }; } componentDidUpdate(prevProps) { const prevDuplicationRows = prevProps.duplicationRows || []; const currDuplicationRows = this.props.duplicationRows || []; if (currDuplicationRows.length !== prevDuplicationRows.length) { this.setState({expandRowIndex: -1}); } } renderHeader = () => { const { allDeDuplicationColumns } = this.props; if (!allDeDuplicationColumns) return; return ( {allDeDuplicationColumns.map((column) => { const { key, name } = column; return <th key={`head-${key}`}>{name} })} ); } renderBody = () => { const { duplicationRows, allDeDuplicationColumns } = this.props; return Array.isArray(duplicationRows) && duplicationRows.map((duplicationRow, rowIndex) => { const { cells, count } = duplicationRow; return ( <tr key={`line-${rowIndex}`}> {allDeDuplicationColumns.map((column) => { const { key, type, data } = column; let cellValue = cells[key]; if ((cellValue === 'null' || cellValue === 'undefined') && cellValue !== 0) { cellValue = EMPTY_CELL_CONTENT; } // for 'single-select' if (type === 'single-select' && cellValue && typeof cellValue === 'string') { let options = data && data.options ? data.options : []; let option = options.find(option => option.id === cellValue); cellValue = option ? <SingleSelectFormatter options={options} value={cellValue} /> : ''; } return ( <td key={`cell-${key}`}> {cellValue} ); })} <td onClick={this.onExpandDuplicationRow.bind(this, rowIndex)} className={styles['value-cell']} > ); }); } onExpandDuplicationRow = (rowIndex) => { this.setState({expandRowIndex: rowIndex}); } getExpandRowItem = () => { const { expandRowIndex } = this.state; const duplicationRow = this.props.duplicationRows[expandRowIndex]; const { rows = [], count = 0 } = duplicationRow || {}; const rowsSelected = rows.map(item => false); return { rows, rowsSelected, value: count, isAllSelected: false, }; } onHideExpandRow = () => { this.setState({expandRowIndex: -1}); } render() { const { expandRowIndex } = this.state; const { duplicationRows, configSettings } = this.props; if (!Array.isArray(duplicationRows) || duplicationRows.length === 0) { return <div className={styles['error-description']}>{intl.get('No_duplication')} } else { return ( {this.renderHeader()} {this.renderBody()} {expandRowIndex > -1 && ( <DetailDuplicationDialog selectedItem={this.getExpandRowItem()} configSettings={configSettings} collaborators={this.props.collaborators} dtable={this.props.dtable} onDeleteRow={this.props.onDeleteRow} onDeleteSelectedRows={this.props.onDeleteSelectedRows} onHideExpandRow={this.onHideExpandRow} /> )} ); } } } TableView.propTypes = { duplicationRows: PropTypes.array, allDeDuplicationColumns: PropTypes.array, configSettings: PropTypes.array, collaborators: PropTypes.array, dtable: PropTypes.object, onDeleteRow: PropTypes.func, onDeleteSelectedRows: PropTypes.func, }; export default TableView;
javascript
29
0.574758
102
29.307692
143
starcoderdata
@Override public int[] label(Dataset D) { if (! (D instanceof CompositionDataset)) throw new Error("Dataset must be a CompositionDataset."); int[] output = new int[D.NEntries()]; CompositionDataset Ptr = (CompositionDataset) D; // Get a list of integers describing each element group List<List<Integer>> ElementIndices = new LinkedList<>(); for (String[] ElementGroup : ElementGroups) { ElementIndices.add(getElementIndices(Arrays.asList(ElementGroup), Ptr)); } // Sort the entries for (int e=0; e<D.NEntries(); e++) { CompositionEntry E = Ptr.getEntry(e); boolean wasAssigned = false; for (int g=0; g < ElementGroups.size(); g++) for (int el=0; el<ElementIndices.get(g).size(); el++) if (E.getElementFraction(ElementIndices.get(g).get(el)) > 0) { wasAssigned = true; output[e] = g; break; } if (! wasAssigned) output[e] = ElementGroups.size(); } return output; }
java
15
0.546256
84
45.375
24
inline
int ospf_lsa_maxage_walker_remover (struct ospf *ospf, struct ospf_lsa *lsa) { #ifdef HAVE_NSSA /* Stay away from any Local Translated Type-7 LSAs */ if (CHECK_FLAG (lsa->flags, OSPF_LSA_LOCAL_XLT)) return 0; #endif /* HAVE_NSSA */ if (IS_LSA_MAXAGE (lsa)) /* Self-originated LSAs should NOT time-out instead, they're flushed and submitted to the max_age list explicitly. */ if (!ospf_lsa_is_self_originated (ospf, lsa)) { if (IS_DEBUG_OSPF (lsa, LSA_FLOODING)) zlog_info("LSA[%s]: is MaxAge", dump_lsa_key (lsa)); switch (lsa->data->type) { #ifdef HAVE_OPAQUE_LSA case OSPF_OPAQUE_LINK_LSA: case OSPF_OPAQUE_AREA_LSA: case OSPF_OPAQUE_AS_LSA: /* * As a general rule, whenever network topology has changed * (due to an LSA removal in this case), routing recalculation * should be triggered. However, this is not true for opaque * LSAs. Even if an opaque LSA instance is going to be removed * from the routing domain, it does not mean a change in network * topology, and thus, routing recalculation is not needed here. */ break; #endif /* HAVE_OPAQUE_LSA */ case OSPF_AS_EXTERNAL_LSA: #ifdef HAVE_NSSA case OSPF_AS_NSSA_LSA: #endif /* HAVE_NSSA */ ospf_ase_incremental_update (ospf, lsa); break; default: ospf_spf_calculate_schedule (ospf); break; } ospf_lsa_maxage (ospf, lsa); } return 0; }
c
12
0.596558
76
31.040816
49
inline
import { Container, Row, Col, Button } from 'react-bootstrap' import { MdEmail } from 'react-icons/md'; import { AiOutlineGithub, AiOutlineNumber } from "react-icons/ai"; import '../styles/ContactMe.css' export default function ContactMe() { return ( <Container fluid id = "Contact"> <Col lg={1}> <Col lg={11} className="mainText"> <Row id = "header">Contact Me <Row id = "subheader">Lets Have A Chat! <Col id = "ContactSubHeader"> <MdEmail /> <a href="mailto: id = "ContactHeader"> <AiOutlineGithub /> <a href = "https://github.com/jguiro09"><h3 id = "ContactHeader">Jguiro09 <AiOutlineNumber /> <h3 id = "ContactHeader">732-857-7444 ) }
javascript
11
0.477041
102
34.84375
32
starcoderdata
import time import cv2 # TODO: Clear frame buffer if in live mode class Webcam: def __init__(self, source, frame_rate): self.camera = cv2.VideoCapture(source) self.frame_rate = frame_rate self.live = True if type(source) is str: self.live = False def get_image(self): ret, frame = self.camera.read() if self.live is False: time.sleep(1 / self.frame_rate) return frame def cleanup(self): self.camera.release()
python
12
0.586408
46
21.391304
23
starcoderdata
var Product = require('../models/product'); //导入 product model var Size = require('../models/size'); var mongoose = require('mongoose'); //mongoose.disconnect(); mongoose.connect('localhost:27017/shopping'); //console.log(mongoose.connect('localhost:27017/shopping')); //console.log(mongoose.connection.db); var seeder = require('mongoose-seeder'), data = require('./data.json'); //console.log(data); seeder.seed(data, {dropDatabase: false, dropCollections: false}, function(err, dbData) { //var foo = dbData.users.foo; }); function exit() { mongoose.disconnect(); }
javascript
6
0.701724
88
33.176471
17
starcoderdata
import persistReducer from 'redux-persist/lib/persistReducer'; import storage from 'redux-persist/lib/storage'; import * as types from './login.actionType'; const persistConfig = { key: 'Login', storage, whitelist: [ /* keys to be persisted */ ], }; const initialState = {}; function Login(state = initialState, action) { // NOSONAR switch (action.type) { // eslint-disable-line case types.LOGIN_TEST: return { ...state, loading: true }; case types.LOGIN_TEST_SUCCESS: return { ...state, loading: false, success: true }; default: return state; } } export default persistReducer(persistConfig, Login);
javascript
6
0.62117
62
18.944444
36
starcoderdata
@Test public void backfillsEventsWhenEmittedEventsSatisfyingCriteria() { var emittedPaymentEvent = anEmittedEventEntity().withResourceExternalId(chargeEntity.getExternalId()).build(); var emittedRefundEvent = anEmittedEventEntity().withResourceType("refund").withId(2L) .withEventDate(ZonedDateTime.parse("2019-09-20T09:00Z")) .withResourceExternalId(refundEntity.getExternalId()) .build(); var refundHistory = RefundHistoryEntityFixture .aValidRefundHistoryEntity() .withExternalId(refundEntity.getExternalId()) .withChargeExternalId(chargeEntity.getExternalId()) .build(); when(emittedEventDao.findNotEmittedEventsOlderThan(any(ZonedDateTime.class), anyInt(), eq(0L), eq(maxId), any())).thenReturn(List.of(emittedPaymentEvent, emittedRefundEvent)); doReturn(chargeEntity).when(chargeService).findChargeByExternalId(chargeEntity.getExternalId()); when(refundDao.findByExternalId(refundEntity.getExternalId())).thenReturn(Optional.of(refundEntity)); when(refundDao.getRefundHistoryByRefundExternalId(refundEntity.getExternalId())).thenReturn(List.of(refundHistory)); doReturn(Optional.of(Charge.from(chargeEntity))).when(chargeService).findCharge(chargeEntity.getExternalId()); emittedEventsBackfillService.backfillNotEmittedEvents(); verify(emittedEventDao, times(1)).findNotEmittedEventsOlderThan(any(ZonedDateTime.class), anyInt(), eq(0L), eq(maxId), any()); // 2 events emitted for payment event and refund event verify(stateTransitionService, times(2)).offerStateTransition(any(), any(), isNull()); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is("Processing not emitted events [lastProcessedId=0, no.of.events=2, oldestDate=2019-09-20T09:00Z]")); assertThat(loggingEvents.get(1).getFormattedMessage(), is("Finished processing not emitted events [lastProcessedId=2, maxId=2]")); }
java
12
0.729337
183
77.678571
28
inline
from JumpScale import j import statsd import sys import time import json import os import psutil from JumpScale.lib.perftesttools import InfluxDumper class MonitorClient(): def __init__(self): luapath = "/opt/code/github/jumpscale7/jumpscale_core7/lib/JumpScale/lib/perftesttools/stat.lua" lua = j.system.fs.fileGetContents(luapath) self._sha = self.redis.script_load(lua) # def reset(self): # import ipdb # ipdb.set_trace() # self.redis.delete("stats") # self.redis.delete("queues:stats") def measure(self,key,measurement,tags,value,type="A",aggrkey=""): """ @param tags node:kds dim:iops location:elgouna """ now=int(time.time()*1000) res = self.redis.evalsha(self._sha,1,key,measurement,value,str(now),type,tags,self.nodename) #LETS NOT DO TOTAL FOR NOW # if aggrkey!="": # tags=j.core.tags.getObject(tags) # try: # tags.tagDelete("node") # except: # pass # try: # tags.tagDelete("disk") # except: # pass # tags.tagSet("node","total") # res= self.redis.evalsha(self._sha,1,aggrkey,measurement,value,str(now),type,tags,"total") print "%s %s"%(key,res) return res def measureDiff(self,key,measurement,tags,value,aggrkey=""): return self.measure(key,measurement,tags,value,type="D",aggrkey=aggrkey) class MonitorTools(MonitorClient): def __init__(self,redis,nodename,tags=""): self.redis=redis self.nodename=nodename self.tags=tags MonitorClient.__init__(self) def diskstat(self,dev="sda"): """ read I/Os requests number of read I/Os processed (512 bytes) read merges requests number of read I/Os merged with in-queue I/O read sectors sectors number of sectors read read ticks milliseconds total wait time for read requests write I/Os requests number of write I/Os processed write merges requests number of write I/Os merged with in-queue I/O write sectors sectors number of sectors written write ticks milliseconds total wait time for write requests in_flight requests number of I/Os currently in flight io_ticks milliseconds total time this block device has been active time_in_queue milliseconds total wait time for all requests """ path="/sys/block/%s/stat"%dev lines = open(path, 'r').readlines() split=lines[0].split() columns=["readios","readmerges","readsectors","readticks","writeios","writemerges","writesectors","writeticks","inflight","ioticks","timeinqueue"] data = dict(zip(columns, split)) print data tags="disk:%s node:%s %s"%(dev,self.nodename,self.tags) measurement=["readios","iops_r"] key="%s.%s.%s"%(self.nodename,dev,measurement[1]) val=int(int(data[measurement[0]])/8) readiops=self.measureDiff(key,measurement[1],tags,val,aggrkey=measurement[1]) measurement=["writeios","iops_w"] key="%s.%s.%s"%(self.nodename,dev,measurement[1]) val=int(int(data[measurement[0]])/8) writeiops=self.measureDiff(key,measurement[1],tags,val,aggrkey=measurement[1]) measurement="kbsec_w" key="%s.%s.%s"%(self.nodename,dev,measurement) kbsecw=int(int(data["writeios"])*4/1024) kbsecw=self.measureDiff(key,measurement,tags,kbsecw,aggrkey=measurement) measurement="kbsec_r" key="%s.%s.%s"%(self.nodename,dev,measurement) kbsecr=int(int(data["readios"])*4/1024) kbsecr=self.measureDiff(key,measurement,tags,kbsecr,aggrkey=measurement) measurement="kbsec" key="%s.%s.%s"%(self.nodename,dev,measurement) kbsec=int(int(data["readios"])*512/1024)+int(int(data["writeios"])*512/1024) kbsec=self.measureDiff(key,measurement,tags,kbsec,aggrkey=measurement) measurement="iops" key="%s.%s.%s"%(self.nodename,dev,measurement) iops=int(int(data["readios"])/8)+int(int(data["writeios"])/8) iops=self.measureDiff(key,measurement,tags,iops,aggrkey=measurement) measurement=["readticks","readticks"] key="%s.%s.%s"%(self.nodename,dev,measurement[1]) val=int(data[measurement[0]]) readticks=self.measureDiff(key,measurement[1],tags,val,aggrkey=measurement[1]) measurement=["writeticks","writeticks"] key="%s.%s.%s"%(self.nodename,dev,measurement[1]) val=int(data[measurement[0]]) writeticks=self.measureDiff(key,measurement[1],tags,val,aggrkey=measurement[1]) measurement=["inflight","inflight"] key="%s.%s.%s"%(self.nodename,dev,measurement[1]) val=int(data[measurement[0]]) inflight=self.measureDiff(key,measurement[1],tags,val,aggrkey=measurement[1]) print "%s: iops:%s mb/sec:%s (R:%s/W:%s)"%(dev,iops,round(kbsec/1024,1),round(kbsecr/1024,1),round(kbsecw/1024,1)) def cpustat(self): tags="node:%s %s"%(self.nodename,self.tags) val=int(psutil.cpu_percent()) measurement="cpu_perc" key="%s.%s"%(self.nodename,measurement) self.measure(key,measurement,tags,val,aggrkey=measurement) val=int(psutil.avail_phymem()/1024/1024) measurement="mem_free_mb" key="%s.%s"%(self.nodename,measurement) self.measure(key,measurement,tags,val,aggrkey=measurement) val=int(psutil.virtmem_usage()[3]) measurement="mem_virt_perc" key="%s.%s"%(self.nodename,measurement) self.measure(key,measurement,tags,val,aggrkey=measurement) val=int(psutil.phymem_usage()[2]) measurement="mem_phy_perc" key="%s.%s"%(self.nodename,measurement) self.measure(key,measurement,tags,val,aggrkey=measurement) res=psutil.cpu_times_percent() names=["cputimeperc_user","cputimeperc_nice","cputimeperc_system","cputimeperc_idle","cputimeperc_iowait","cputimeperc_irq","cputimeperc_softirq","steal","guest","guest_nice"] for i in range(len(names)): if names[i].startswith("cputime"): val=int(res[i]) measurement=names[i] key="%s.%s"%(self.nodename,measurement) self.measure(key,measurement,tags,val,aggrkey=measurement) def netstat(self): tags="node:%s %s"%(self.nodename,self.tags) names=["kbsend","kbrecv","psent","precv","errin","errout","dropin","dropout"] res=psutil.net_io_counters() for i in range(len(names)): if names[i] in ["kbsend","kbrecv"]: val=int(res[i])/1024 else: val=int(res[i]) measurement=names[i] key="%s.%s"%(self.nodename,measurement) self.measureDiff(key,measurement,tags,val,aggrkey=measurement) def startMonitorLocal(self,disks=[],cpu=False,network=False): count=6 while True: # cmd="iostat -m" # j.do.executeInteractive(cmd) if disks!=[]: for dev in disks: self.diskstat(dev) if cpu: self.cpustat() if network: if count>5: self.netstat() count=0 else: count+=1 time.sleep(2)
python
16
0.601571
183
37.2
200
starcoderdata
const app = require('@/test/setup/feathers') const device = require('@/server/services/device/service') app.set('deviceId', '123456') app.configure(device) describe('\'Device\' service', () => { it('Service created', () => { expect(app.service('/api/device')).toBeTruthy() }) it('Update device informations', async () => { await app.service('/api/device').updateDevice() const infos = await app.service('/api/device').find() expect(infos).toBeTruthy() }) })
javascript
16
0.656977
58
27.666667
18
starcoderdata
package com.zte.mao.common.controller.response; import com.zte.mao.common.response.CommonResponse; public class EntityResponse extends CommonResponse { private static final long serialVersionUID = 1L; private Object userEntity; public EntityResponse(byte status, String message, Object userEntity) { super(status, message); this.userEntity = userEntity; } public Object getUserEntity() { return userEntity; } public void setUserEntity(Object userEntity) { this.userEntity = userEntity; } }
java
6
0.757053
101
25.782609
23
starcoderdata
#include // [[Rcpp::depends(RcppArmadillo)]] using namespace Rcpp; std::vector grp_siz(std::vector group) { std::vector temp; temp = group; //std::sort(temp.begin(),temp.end()); temp.erase( std::unique( temp.begin(), temp.end() ), temp.end() ); int tempsize = 0; tempsize = temp.size(); std::vector gsize(tempsize); for(unsigned int i = 0;i<group.size();i++) { for(unsigned int k=0;k<temp.size();k++) { if(group[i]==temp[k]) gsize[k]++; } } return gsize; } // [[Rcpp::export]] arma::Mat nonmissing_per_grp(arma::mat mtr,std::vector group) { std::vector nvec; nvec = grp_siz(group); std::vector cpy; std::vector non_missing; int count = 0; arma::Mat final(mtr.n_rows,nvec.size()); arma::Row row; std::vector temp; for(unsigned int z = 0; z <mtr.n_rows;z++) { cpy = arma::conv_to< std::vector >::from(mtr.row(z)); for (unsigned int i = 0, j = 0; i < nvec.size(); i++) { for (unsigned int k = 0; k < nvec[j]; k++) { if(ISNAN(cpy[k])) continue; else count++; } non_missing.push_back(count); cpy.erase(cpy.begin(),cpy.begin()+nvec[j]); count = 0; j++; } row = arma::conv_to >::from(non_missing); final.row(z)=row; non_missing.clear(); row.clear(); cpy.clear(); } return final; }
c++
17
0.52534
80
17.597701
87
starcoderdata
void onInit() override { nh_ = getMTPrivateNodeHandle(); image_transport::ImageTransport it(nh_); int sub_rate = 1; int pub_rate = 1; nh_.getParam("sub_rate", sub_rate); nh_.getParam("pub_rate", pub_rate); nh_.param("blue_scale", config_.blue_scale, 0.90); nh_.param("red_scale", config_.red_scale, 0.80); nh_.param("otsu_threshold", config_.otsu_threshold, 5); nh_.param("min_confidence", config_.min_confidence, 0.30); drw_.init(nh_, config_); bool no_depth = false; nh_.getParam("no_depth", no_depth); distance_from_terabee_ = -1; camera_info_valid_ = false; if (!no_depth) { ROS_INFO("starting goal detection using ZED"); frame_sub_ = std::make_unique<image_transport::SubscriberFilter>(it, "/zed_goal/left/image_rect_color", sub_rate); depth_sub_ = std::make_unique<image_transport::SubscriberFilter>(it, "/zed_goal/depth/depth_registered", sub_rate); // ApproximateTime takes a queue size as its constructor argument, hence SyncPolicy(xxx) rgbd_sync_ = std::make_unique<message_filters::Synchronizer<RGBDSyncPolicy>>(RGBDSyncPolicy(10), *frame_sub_, *depth_sub_); rgbd_sync_->registerCallback(boost::bind(&GoalDetect::callback, this, _1, _2)); camera_info_sub_ = nh_.subscribe("/zed_goal/left/camera_info", sub_rate, &GoalDetect::camera_info_callback, this); } else { ROS_INFO("starting goal detection using webcam"); rgb_sub_ = std::make_unique<image_transport::Subscriber>(it.subscribe("/c920_camera/image_raw", sub_rate, &GoalDetect::callback_no_depth, this)); terabee_sub_ = nh_.subscribe("/multiflex_1/ranges_raw", 1, &GoalDetect::multiflexCB, this); } // Set up publisher pub_ = nh_.advertise<field_obj::Detection>("goal_detect_msg", pub_rate); pub_debug_image_ = it.advertise("debug_image", 2); }
c++
16
0.656852
150
41.477273
44
inline
package model.explosives; import model.GameSettings; import model.map.MapModel; import model.player.Player; import util.VisibleType; import util.Vec2; public class Mine extends Explosive { /** * Place une bombe sur la carte * @param m * @param position * @param owner */ public Mine(MapModel m, Vec2 position, Player owner){ super(VisibleType.MINE, m, position, owner, GameSettings.getInstance().getMineDamage()); } }
java
6
0.717391
95
26.6
20
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class RpcResponseController extends Controller { const JSON_RPC_VERSION = '2.0'; public static function success($result, string $id = null) { return [ 'jsonrpc' => self::JSON_RPC_VERSION, 'result' => $result, 'id' => $id, ]; } public static function error($error) { return [ 'jsonrpc' => self::JSON_RPC_VERSION, 'error' => $error, 'id' => null, ]; } }
php
10
0.504394
62
18.62069
29
starcoderdata
def _forward_alg(self, feats): ''' this also called alpha-recursion or forward recursion, to calculate log_prob of all barX ''' # T = self.max_seq_length T = feats.shape[1] batch_size = feats.shape[0] # alpha_recursion,forward, alpha(zt)=p(zt,bar_x_1:t) log_alpha = torch.Tensor(batch_size, 1, self.num_labels).fill_(-10000.).to(self.device) # normal_alpha_0 : alpha[0]=Ot[0]*self.PIs # self.start_label has all of the score. it is log,0 is p=1 log_alpha[:, 0, self.start_label_id] = 0 # feats: sentances -> word embedding -> lstm -> MLP -> feats # feats is the probability of emission, feat.shape=(1,tag_size) for t in range(1, T): log_alpha = (log_sum_exp_batch(self.transitions + log_alpha, axis=-1) + feats[:, t]).unsqueeze(1) # log_prob of all barX log_prob_all_barX = log_sum_exp_batch(log_alpha) return log_prob_all_barX
python
15
0.563353
109
42.695652
23
inline
def main(): load_dotenv() # Authenticate with YouTube API KEY = os.environ.get('YOUTUBE_API_KEY') query = 'stocks' driver_path = "C:/WebDriver/bin/chromedriver.exe" csv_path = "data/youtube_comments.csv" video_list = scrape_videos(query, KEY, driver_path=driver_path, maxResults=1) # Filter out duplicate videos based on DB urls_titles_filtered = filter_urls(video_list) # Scrape comments based on filtered video list scrape_comments(urls_titles_filtered, driver_path=driver_path, csv_path=csv_path) # Process youtube data into youtube_comments_clean.csv process_data() # Upload data to DB upload_data()
python
8
0.662375
85
28.166667
24
inline
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Filiere; class FiliereController extends Controller { public function create() { return view('admin.filiere.create'); } public function store(Request $request) { $request->validate([ 'name' => 'required' ]); Filiere::create(['filiere' => $request['name']]); $request->session()->flash('success', 'filiere' . $request['name'] . 'created!'); return redirect(route('users.index')); } public function show(Filiere $filiere) { return view('admin.filiere.show', compact('filiere')); } }
php
13
0.595588
89
20.935484
31
starcoderdata
def vpc_cleanup(vpcid): """Cleanup VPC""" print('Removing VPC ({}) from AWS'.format(vpcid)) ec2 = boto3.resource('ec2') ec2_client = ec2.meta.client vpc = ec2.Vpc(vpcid) # detach default dhcp_options if associated with the vpc dhcp_options_default = ec2.DhcpOptions('default') if dhcp_options_default: dhcp_options_default.associate_with_vpc( VpcId=vpc.id ) # detach and delete all gateways associated with the vpc for gw in vpc.internet_gateways.all(): vpc.detach_internet_gateway(InternetGatewayId=gw.id) gw.delete() # delete all route table associations for rt in vpc.route_tables.all(): if not rt.associations: rt.delete() else: for rta in rt.associations: if not rta.main: rta.delete() # delete any instances for subnet in vpc.subnets.all(): for instance in subnet.instances.all(): instance.terminate() # delete our endpoints for ep in ec2_client.describe_vpc_endpoints( Filters=[{ 'Name': 'vpc-id', 'Values': [vpcid] }])['VpcEndpoints']: ec2_client.delete_vpc_endpoints(VpcEndpointIds=[ep['VpcEndpointId']]) # delete our security groups for sg in vpc.security_groups.all(): if sg.group_name != 'default': sg.delete() # delete any vpc peering connections for vpcpeer in ec2_client.describe_vpc_peering_connections( Filters=[{ 'Name': 'requester-vpc-info.vpc-id', 'Values': [vpcid] }])['VpcPeeringConnections']: ec2.VpcPeeringConnection(vpcpeer['VpcPeeringConnectionId']).delete() # delete non-default network acls for netacl in vpc.network_acls.all(): if not netacl.is_default: netacl.delete() # delete network interfaces for subnet in vpc.subnets.all(): for interface in subnet.network_interfaces.all(): interface.delete() subnet.delete() # finally, delete the vpc ec2_client.delete_vpc(VpcId=vpcid)
python
15
0.601679
77
35.982759
58
inline
def getDisabled(self): ''' :return: a list of schedules that are currently disabled ''' disableList = [] for schedule in self.schedule: if not schedule.isEnabled(): fmw = schedule.getFMWName() repo = schedule.getRepository() schedName = schedule.getScheduleName() disableList.append([schedName, repo, fmw]) # sort by the fmw name disableList.sort(key=lambda x: x[0]) return disableList
python
11
0.542593
64
34.133333
15
inline
private async Task<SearchResult> SearchIncludes( string resourceId, PartialDateTime since, IReadOnlyList<string> types, CancellationToken cancellationToken) { using IScoped<ISearchService> search = _searchServiceFactory(); var searchResultEntries = new List<SearchResultEntry>(); // Build search parameters var searchParameters = new List<Tuple<string, string>> { Tuple.Create(SearchParameterNames.Id, resourceId), }; searchParameters.AddRange(_includes.Select(include => Tuple.Create(SearchParameterNames.Include, $"{ResourceType.Patient}:{include}"))); // Search SearchOptions searchOptions = _searchOptionsFactory.Create(ResourceType.Patient.ToString(), searchParameters); SearchResult searchResult = await search.Value.SearchAsync(searchOptions, cancellationToken); searchResultEntries.AddRange(searchResult.Results.Select(x => new SearchResultEntry(x.Resource))); // Filter results by _type if (types.Any()) { searchResultEntries = searchResultEntries.Where(s => types.Contains(s.Resource.ResourceTypeName)).ToList(); } // Filter results by _since if (since != null) { var sinceDateTimeOffset = since.ToDateTimeOffset( defaultMonth: 1, defaultDaySelector: (year, month) => 1, defaultHour: 0, defaultMinute: 0, defaultSecond: 0, defaultFraction: 0.0000000m, defaultUtcOffset: TimeSpan.Zero); searchResultEntries = searchResultEntries.Where(s => s.Resource.LastModified.CompareTo(sinceDateTimeOffset) >= 0).ToList(); } return new SearchResult(searchResultEntries, searchResult.ContinuationToken, searchResult.SortOrder, searchResult.UnsupportedSearchParameters); }
c#
19
0.608842
155
46.318182
44
inline
"use strict"; const defs={ API_URL:"api.nexx.cloud", API_VERSION:"3.1", API_KIND_MEDIA:'media', API_KIND_DOMAIN:'domain', API_KIND_MANAGE:'manage', API_KIND_SESSION:'session', API_KIND_SYSTEM:'system', API_KIND_STATISTICS:'statistics', API_KIND_PROCESSING:'processing', VERB_GET:"GET", VERB_POST:"POST", VERB_PUT:"PUT", VERB_DELETE:"DELETE", MAX_RESULT_LIMIT:100, MAX_RESULT_LIMIT_STATISTICS:100000 }; function getAllVerbs(){ return([defs.VERB_GET,defs.VERB_POST,defs.VERB_PUT,defs.VERB_DELETE]); } module.exports=defs; module.exports.getAllVerbs=getAllVerbs;
javascript
7
0.666134
74
23.115385
26
starcoderdata
@Test public void shouldImportInitialContentForAllWorkspaceConfigurations() throws Exception { startRepositoryWithConfiguration(getClass().getClassLoader().getResourceAsStream( "config/repo-config-initial-content.json")); //preconfigured ws String ws1 = "ws1"; assertCarsWithMixins(ws1); //preconfigured ws String ws2 = "ws2"; assertFilesAndFolders(ws2); //default ws String defaultWs = "default"; assertCarsWithoutNamespace(defaultWs); //create a new ws that has been configured with an empty import String ws4 = "ws4"; session.getWorkspace().createWorkspace(ws4); JcrSession ws4Session = repository.login(ws4); NodeIterator rootIterator = ws4Session.getNode("/").getNodes(); assertEquals("Expected an empty workspace", 1, rootIterator.getSize()); //create a new ws that has been configured the same as ws2 String ws5 = "ws5"; session.getWorkspace().createWorkspace(ws5); assertFilesAndFolders(ws5); //create a new ws that doesn't have a dedicated config, but should fall back to default String ws6 = "ws6"; session.getWorkspace().createWorkspace(ws6); assertCarsWithMixins(ws6); }
java
10
0.65848
95
38.515152
33
inline
class LPParser extends Parser { get_attributes(obj) { var A = []; A.push(...this.parse_attributes(obj, [ {text:"Time", extract:this.path_extract(["time"]), formatters:[this.f2]}, {text:"Status", extract:this.path_extract(["status"])}, {text:"#Iterations", extract:this.path_extract(["simplex_iterations"])}, {text:"Incumbent", extract:this.path_extract(["incumbent_value"]), formatters:[this.f2]}, {text:"#Variables", extract:this.path_extract(["variable_count"])}, {text:"#Constraints", extract:this.path_extract(["constraint_count"])} ])); return A; } detail_view_rows(obj) { var rows = []; if (obj.screen_output && obj.screen_output != "") this.add_path_row(rows, "Screen output", obj, ["screen_output"], [this.textarea]); this.add_table_row(rows, ["Time", "Status", "#Iterations", "Incumbent value","#Variables", "#Constraints"], [ [obj.time, obj.status, obj.simplex_iterations, obj.incumbent_value, obj.variable_count, obj.constraint_count] ]); this.add_path_row(rows, "Duals", obj, ["duals"], [this.jsonify, this.textinput]); return rows; } } kd.add_parser("lp", new LPParser());
javascript
16
0.628003
115
37.935484
31
starcoderdata
public double calcularTotal() { double total = 0; for (int a = 0; a < this.contadorProductos; a++) { total += this.productos[a].getPrecio();//Simplficado en una linea de código // Forma extensa // Producto producto = this.productos[a]; // total += productos[a].getPrecio(); } return total; }
java
10
0.530184
87
36.3
10
inline
void free() override { long _start = m_startP.m_value.load(std::memory_order_relaxed); long offset = normaliseNotPowerOfTwo(SystemConf::getInstance().BATCH_SIZE + _start); long index = normaliseNotPowerOfTwo(_start); long bytes; /* Measurements */ if (offset <= index) bytes = (long) (m_capacity - index + offset + 1); else bytes = offset - index + 1; m_bytesProcessed.fetch_add(bytes, std::memory_order_relaxed); m_tuplesProcessed.fetch_add((bytes / (size_t) m_tupleSize), std::memory_order_relaxed); m_tasksProcessed.fetch_add(1, std::memory_order_relaxed); /* Set new start pointer */ m_startP.m_value.store(_start + bytes, std::memory_order_relaxed); }
c
10
0.6625
91
39.055556
18
inline
#!/usr/bin/env python """ Finish cookiecutter build. """ import subprocess from pathlib import Path # noqa:F401 from typing import Optional # noqa:F401 import sh from pudb import set_trace as bp # noqa:F401 def run(COMMAND: str, OUTPUT: bool = False) -> Optional[str]: if OUTPUT: return subprocess.check_output(COMMAND, shell=True).decode("utf-8").split("\n")[0] else: subprocess.run(COMMAND, shell=True) def main() -> None: run("poetry update && poetry install") run("poetry add pudb click ruamel.yaml") run( "poetry add --dev pudb flake8 flake8-bugbear mypy black isort pre-commit" " pytest pytest-sugar pytest-cov Sphinx pydata-sphinx-theme sphinx-autoapi" " twine" ) run("poetry run mypy --install-types --non-interactive") sh.git.init(".") sh.git.add(".") sh.git.branch("-M", "main") run("poetry run pre-commit install") run("poetry run git commit -m \"feat: initial commit\"") if __name__ == "__main__": main()
python
14
0.648649
90
23.386364
44
starcoderdata
// base-react // var React = require('react'); var Main = require('main'); //---------------------------- React.renderComponent(Main({} ), document.getElementById('app')); //----------------------------
javascript
7
0.470852
35
17.666667
12
starcoderdata
static int set_difference_update_internal(PySetObject *so, PyObject *other) { if (PySet_GET_SIZE(so) == 0) { return 0; } if ((PyObject *)so == other) return set_clear_internal(so); if (PyAnySet_Check(other)) { setentry *entry; Py_ssize_t pos = 0; while (set_next((PySetObject *)other, &pos, &entry)) if (set_discard_entry(so, entry->key, entry->hash) < 0) return -1; } else { PyObject *key, *it; it = PyObject_GetIter(other); if (it == NULL) return -1; while ((key = PyIter_Next(it)) != NULL) { if (set_discard_key(so, key) < 0) { Py_DECREF(it); Py_DECREF(key); return -1; } Py_DECREF(key); } Py_DECREF(it); if (PyErr_Occurred()) return -1; } /* If more than 1/4th are dummies, then resize them away. */ if ((size_t)(so->fill - so->used) <= (size_t)so->mask / 4) return 0; return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); }
c
13
0.488
74
27.15
40
inline
package uiamsdk import ( "time" uiammodel "github.com/uiam-net/uiam-sdk-go/models" ) // TokenCreateRequest TokenCreateRequest type TokenCreateRequest struct { BaseRequest JTI string `json:"jti,omitempty"` Audience string `json:"aud,omitempty"` Issuer string `json:"iss,omitempty"` NotBefore int64 `json:"nbf,omitempty"` Subject string `json:"sub,omitempty"` Duration time.Duration `json:"duration"` // ExpriedAt 有效时长 // Custom RealmID uint64 `json:"realm_id,omitempty"` RealmSlug string `json:"realm_slug,omitempty"` MerchantID uint64 `json:"merchant_id,omitempty"` MerchantSlug string `json:"merchant_slug,omitempty"` IdentityType uiammodel.IdentityTypeEnum `json:"identity_type,omitempty"` Scheme uiammodel.AuthSchemeEnum `json:"scheme,omitempty"` // 签名方式 UID string `json:"uid,omitempty"` // Audience 区别 Device string `json:"device,omitempty"` // 每个 device 会有一个相对固定 session Description string `json:"description,omitempty"` // device 介绍 SessionID string `json:"sid,omitempty"` // 使用哪个 session 进行签名 Sign string `json:"sig,omitempty"` // ? SignAlg string `json:"sal,omitempty"` // ? Extra string `json:"extra,omitempty"` // 签名时,会把这部分也签进去 }
go
9
0.574132
101
44.285714
35
starcoderdata
OBJMASK * phObjmaskCopy(const OBJMASK *sv, /* OBJMASK to be copied */ float fdr, float fdc /* shift by this much */ ) { OBJMASK *new; int dr, dc; if(sv == NULL) { return(NULL); } new = phObjmaskNew(sv->nspan); dr = (fdr < 0) ? -(-fdr + 0.5) : fdr + 0.5; dc = (fdc < 0) ? -(-fdc + 0.5) : fdc + 0.5; new->nspan = sv->nspan; new->row0 = sv->row0; new->col0 = sv->col0; new->npix = sv->npix; if(dr == 0 && dc == 0) { memcpy(new->s,sv->s,sv->nspan*sizeof(SPAN)); new->cmin = sv->cmin; new->rmin = sv->rmin; new->cmax = sv->cmax; new->rmax = sv->rmax; } else { int i, n = sv->nspan; SPAN *const snew = new->s, *s = sv->s; for(i = 0;i < n;i++) { snew[i].y = s[i].y + dr; snew[i].x1 = s[i].x1 + dc; snew[i].x2 = s[i].x2 + dc; } new->cmin = sv->cmin + dc; new->rmin = sv->rmin + dr; new->cmax = sv->cmax + dc; new->rmax = sv->rmax + dr; } return new; }
c
13
0.464606
59
21.818182
44
inline
<?php /** * Created by PhpStorm. * User: luckly * Date: 17/9/4 * Time: 上午8:26 */ namespace app\admin\controller; use think\Controller; class Picture extends Controller { public function picture_add(){ return $this->fetch(); } public function picture_list(){ return $this->fetch(); } public function picture_show(){ return $this->fetch(); } }
php
8
0.649895
79
18.916667
24
starcoderdata
""" Rankings web app section. """ from typing import Dict, List import pandas as pd import streamlit as st import college_football_rankings as cfr import ui def comparison(rankings: Dict[str, List[str]], teams: Dict[str, cfr.Team], length: int): """ Create rankings comparison table. """ # Select ranks to show. options = list(rankings.keys()) selected_names = st.multiselect( "Select rankings to compare", options=options, default=options ) selected = {name: rankings[name] for name in selected_names} # Create index column index = [f"#{i}" for i in range(1, length + 1)] selected = {key: val[:length] for key, val in selected.items()} if not selected: return selected = { key: val + [None] * (length - len(val)) for key, val in selected.items() } # Transform data into a dataframe and show it. data_frame = pd.DataFrame(selected, index=index) data_frame = data_frame.apply(ui.add_logos_and_records, args=(teams,)) html_table = data_frame.to_html(escape=False) html_table = ui.format_html_table(html_table) st.write(html_table, unsafe_allow_html=True)
python
13
0.66264
88
29.5
38
starcoderdata
package com.ayang818.kugga.starter.enums; /** * @author 杨丰畅 * @description TODO * @date 2020/1/18 12:00 **/ public interface Status { String OK = "200"; String UN_AUTHORIZED = "401"; String PAGE_NOT_FOUND = "404"; String SERVER_ERROR = "500"; String REJECT = "403"; }
java
6
0.641509
41
20.2
15
starcoderdata
/* * _______ _____ _____ _____ * |__ __| | __ \ / ____| __ \ * | | __ _ _ __ ___ ___ ___| | | | (___ | |__) | * | |/ _` | '__/ __|/ _ \/ __| | | |\___ \| ___/ * | | (_| | | \__ \ (_) \__ \ |__| |____) | | * |_|\__,_|_| |___/\___/|___/_____/|_____/|_| * * ------------------------------------------------------------- * * TarsosDSP is developed by at IPEM, University Ghent * * ------------------------------------------------------------- * * Info: http://0110.be/tag/TarsosDSP * Github: https://github.com/JorenSix/TarsosDSP * Releases: http://0110.be/releases/TarsosDSP/ * * TarsosDSP includes modified source code by various authors, * for credits and info, see README. * */ package be.tarsos.dsp.ui.layers; import java.awt.Color; import java.awt.Graphics2D; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import javax.sound.sampled.UnsupportedAudioFileException; import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.StopAudioProcessor; import be.tarsos.dsp.io.jvm.AudioDispatcherFactory; import be.tarsos.dsp.pitch.GeneralizedGoertzel; import be.tarsos.dsp.pitch.Goertzel.FrequenciesDetectedHandler; import be.tarsos.dsp.ui.Axis; import be.tarsos.dsp.ui.CoordinateSystem; import be.tarsos.dsp.util.PitchConverter; public class GeneralizedGoertzelLayer implements Layer{ private TreeMap<Double, double[]> features; private final CoordinateSystem cs; private final File audioFile; private double maxSpectralEnergy = 0; private double minSpectralEnergy = 100000; private float[] binStartingPointsInCents; private float binWith;// in seconds private float binHeight;// in cents public GeneralizedGoertzelLayer(CoordinateSystem cs, File audioFile, int binHeightInCents) { this.cs = cs; this.audioFile = audioFile; } public void draw(Graphics2D graphics) { calculateFeatures(); if(features != null){ Map<Double, double[]> spectralInfoSubMap = features.subMap( cs.getMin(Axis.X) / 1000.0, cs.getMax(Axis.X) / 1000.0); for (Map.Entry<Double, double[]> column : spectralInfoSubMap.entrySet()) { double timeStart = column.getKey();// in seconds double[] spectralEnergy = column.getValue();// in cents // draw the pixels for (int i = 0; i < spectralEnergy.length; i++) { Color color = Color.black; float centsStartingPoint = binStartingPointsInCents[i]; // only draw the visible frequency range if (centsStartingPoint >= cs.getMin(Axis.Y) && centsStartingPoint <= cs.getMax(Axis.Y)) { double factor = spectralEnergy[i] / maxSpectralEnergy; int greyValue = 255 - (int) (factor * 255) ; greyValue = Math.max(0, greyValue); color = new Color(greyValue, greyValue, greyValue); graphics.setColor(color); graphics.fillRect((int) Math.round(timeStart * 1000), Math.round(centsStartingPoint), (int) Math.round(binWith * 1000), (int) Math.ceil(binHeight)); } } } } } public void calculateFeatures() { try { //maxSpectralEnergy = 0; //minSpectralEnergy = 100000; int blockSize = 8000; int overlap = 7500; AudioDispatcher adp = AudioDispatcherFactory.fromFile(audioFile, blockSize,overlap); adp.skip(Math.max(0, cs.getMin(Axis.X)/1000.0)); adp.addAudioProcessor(new StopAudioProcessor(cs.getMax(Axis.X)/1000.0)); final float sampleRate = adp.getFormat().getFrameRate(); double lowFrequencyInCents = cs.getMin(Axis.Y); double highFrequencyInCents = cs.getMax(Axis.Y); int steps = 50; // 100 steps; double stepInCents = (highFrequencyInCents - lowFrequencyInCents) / (float) steps; binWith = (blockSize - overlap) / sampleRate; binHeight = (float) stepInCents; double[] frequencies = new double[steps]; binStartingPointsInCents = new float[steps]; for(int i = 0 ; i< steps ; i++){ double valueInCents = i * stepInCents + lowFrequencyInCents; frequencies[i] = PitchConverter.absoluteCentToHertz(valueInCents); binStartingPointsInCents[i]=(float)valueInCents; } final TreeMap<Double, double[]> fe = new TreeMap<Double, double[]>(); FrequenciesDetectedHandler handler= new FrequenciesDetectedHandler(){ int i = 0; @Override public void handleDetectedFrequencies(double[] frequencies, double[] powers, double[] allFrequencies, double[] allPowers) { double timeStamp = (Math.max(0, cs.getMin(Axis.X)/1000.0)) + i * binWith; i++; fe.put(timeStamp,allPowers.clone()); }}; final GeneralizedGoertzel goertzel = new GeneralizedGoertzel(sampleRate,blockSize,frequencies,handler); adp.addAudioProcessor(goertzel); adp.run(); for (double[] magnitudes : fe.values()) { for (int i = 0; i < magnitudes.length; i++) { if(magnitudes[i]==0){ magnitudes[i] = 1.0/(float)1e10; } //to dB magnitudes[i] = 20 * Math.log(1+Math.abs(magnitudes[i]))/Math.log(10); maxSpectralEnergy = Math.max(magnitudes[i],maxSpectralEnergy); minSpectralEnergy = Math.min(magnitudes[i],minSpectralEnergy); } } minSpectralEnergy = Math.abs(minSpectralEnergy); this.features = fe; } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e2){ e2.printStackTrace(); } } @Override public String getName() { return "Generalized Goertzel Layer"; } }
java
23
0.626719
106
30.27933
179
starcoderdata
package notjoe.pointersmod.common.item; import net.minecraft.item.Item; import notjoe.pointersmod.api.actions.*; import notjoe.pointersmod.common.Config; /** * The items defined within this mod. */ public class ModItems { public static Item pointer_inv; public static Item pointer_world; public static Item pointer_redstone; public static Item pointer_teleport; public static Item pointer_fluid; public static Item component; public static void preInit() { if (Config.enablePointerInventory) pointer_inv = new ItemPointerBase("pointer_inv", new PointerActionInventory()); if (Config.enablePointerWorld) pointer_world = new ItemPointerBase("pointer_world", new PointerActionWorld()); if (Config.enablePointerRedstone) pointer_redstone = new ItemPointerBase("pointer_redstone", new PointerActionRedstone()); if (Config.enablePointerTeleport) pointer_teleport = new ItemPointerBase("pointer_teleport", new PointerActionTeleport()); if (Config.enablePointerFluid) pointer_fluid = new ItemPointerBase("pointer_fluid", new PointerActionFluid()); if (Config.addCraftingRecipes) component = new ItemComponent(); } }
java
12
0.710329
100
37.171429
35
starcoderdata
INT64 MethodDesc::CallDescr(const BYTE *pTarget, Module *pModule, MetaSig* pMetaSig, BOOL fIsStatic, const __int64 *pArguments) { THROWSCOMPLUSEXCEPTION(); BYTE callingconvention = pMetaSig->GetCallingConvention(); if (!isCallConv(callingconvention, IMAGE_CEE_CS_CALLCONV_DEFAULT)) { _ASSERTE(!"This calling convention is not supported."); COMPlusThrow(kInvalidProgramException); } #ifdef DEBUGGING_SUPPORTED if (CORDebuggerTraceCall()) g_pDebugInterface->TraceCall(pTarget); #endif // DEBUGGING_SUPPORTED DWORD NumArguments = pMetaSig->NumFixedArgs(); DWORD arg = 0; UINT nActualStackBytes = pMetaSig->SizeOfActualFixedArgStack(fIsStatic); // Create a fake FramedMethodFrame on the stack. LPBYTE pAlloc = (LPBYTE)_alloca(FramedMethodFrame::GetNegSpaceSize() + sizeof(FramedMethodFrame) + nActualStackBytes); LPBYTE pFrameBase = pAlloc + FramedMethodFrame::GetNegSpaceSize(); if (!fIsStatic) { *((void**)(pFrameBase + FramedMethodFrame::GetOffsetOfThis())) = *((void **)&pArguments[arg++]); } UINT nVirtualStackBytes = pMetaSig->SizeOfVirtualFixedArgStack(fIsStatic); arg += NumArguments; ArgIterator argit(pFrameBase, pMetaSig, fIsStatic); if (pMetaSig->HasRetBuffArg()) { _ASSERTE(!"NYI"); } BYTE typ; UINT32 structSize; int ofs; while (0 != (ofs = argit.GetNextOffsetFaster(&typ, &structSize))) { arg--; switch (StackElemSize(structSize)) { case 4: *((INT32*)(pFrameBase + ofs)) = *((INT32*)&pArguments[arg]); break; case 8: *((INT64*)(pFrameBase + ofs)) = pArguments[arg]; break; default: { // Not defined how to spread a valueclass into 64-bit buckets! _ASSERTE(!"NYI"); } } } INT64 retval; #ifdef _DEBUG // Save a copy of dangerousObjRefs in table. Thread* curThread = 0; unsigned ObjRefTable[OBJREF_TABSIZE]; if (GetThread) curThread = GetThread(); if (curThread) memcpy(ObjRefTable, curThread->dangerousObjRefs, sizeof(curThread->dangerousObjRefs)); #endif INSTALL_COMPLUS_EXCEPTION_HANDLER(); retval = CallDescrWorker(pFrameBase + sizeof(FramedMethodFrame) + nActualStackBytes, nActualStackBytes / STACK_ELEM_SIZE, (ArgumentRegisters*)(pFrameBase + FramedMethodFrame::GetOffsetOfArgumentRegisters()), (LPVOID)pTarget); UNINSTALL_COMPLUS_EXCEPTION_HANDLER(); #ifdef _DEBUG // Restore dangerousObjRefs when we return back to EE after call if (curThread) memcpy(curThread->dangerousObjRefs, ObjRefTable, sizeof(curThread->dangerousObjRefs)); #endif getFPReturn(pMetaSig->GetFPReturnSize(), retval); return retval; }
c++
16
0.610092
127
31.56044
91
inline
import json import os.path import shlex import subprocess import sys import Tkinter as tk import tkFileDialog from Tkconstants import * CFG_FILE = "config.txt" _WIDTH = 60 class ConfigWindow: def __init__(self, cfg_file=CFG_FILE, parts=("EAFL", "CSV", "HTML"), defaults=None): self.tkroot = tk.Tk() self.tkroot.title("Configuration Settings") self.cfg_file = cfg_file self.labels = {} self.entries = {} self.variables = {} self.buttons = {} self.indices = [] if defaults is None: defaults = {} # Make container frame self.frame = tk.Frame(self.tkroot, relief=RIDGE, borderwidth=2) self.frame.grid(column=0, row=0, sticky=(N, W, E, S)) self.frame.columnconfigure(0, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.pack(fill=BOTH, expand=1) # Load previous configuration settings if os.path.exists(cfg_file): cfgstr = ''.join(list(open(cfg_file))) if cfgstr is not '': self.cfg = json.loads(cfgstr) else: self.cfg = {} else: self.cfg = {} self.tkroot.protocol("WM_DELETE_WINDOW", self._destroy_root) self.tkroot.protocol(" self._destroy_root) updir = os.path.dirname(os.getcwd()) old_eafs = os.path.join(updir, "corpus-data-versions") if "MAIN" in parts: self.mk_menu_row("LANGUAGE", defaults.get("LANGUAGE", "Raramuri"), "Language template:") if "EAFL" in parts: self.mk_label_row("Variables used in creating EAFL file") init_lift = self.cfg.get("LIFT", os.path.join(updir, "FLEx.lift")) self.mk_choice_row("LIFT", init_lift, "Input LIFT File:") init_dir = self.cfg.get("EAFL_DIR", updir) self.mk_choice_row("EAFL_DIR", init_dir, "Output EAFL Directory:", isdir=True) if "CSV" in parts or "HTML" in parts: self.mk_label_row("Variables used in both CSV and HTML export steps") init_dir = self.cfg.get("FILE_DIR", updir) self.mk_choice_row("FILE_DIR", init_dir, "Working File Directory:", isdir=True) out_dir = os.path.join(old_eafs, "auto") if not os.path.exists(out_dir): out_dir = init_dir # init_csv = self.cfg.get("CSV", os.path.join(out_dir, "data.csv")) # self.mk_choice_row("CSV", init_csv, "Output CSV File:", issave=True) exp_fields = self.cfg.get("EXP_FIELDS", # List of fields to include ", ".join(["Phonetic", "Spanish", "English", "Note"])) self.mk_text_row("EXP_FIELDS", exp_fields, "List of Fields to Export:") init_eafs = self.cfg.get("OLD_EAFS", old_eafs) self.mk_choice_row("OLD_EAFS", init_eafs, "Directory of Input EAFs:", isdir=True) # self.mk_choice_row("NEW_EAFS", os.path.join(init_eafs, "auto"), "Directory for Output EAFs:", isdir=True) if "HTML" in parts: self.mk_label_row("Variables used for exporting CSV to HTML") init_meta = self.cfg.get("META", os.path.join(updir, "metadata.csv")) self.mk_choice_row("META", init_meta, "WAV Session Metadata (optional):") init_wav = self.cfg.get("WAV", os.path.join(updir, "wav")) self.mk_choice_row("WAV", init_wav, "WAV Input Directory:", isdir=True) init_www = self.cfg.get("WWW", os.path.join(updir, "www")) self.mk_choice_row("WWW", init_www, "Web Files Output Directory:", isdir=True) # init_clips = self.cfg.get("CLIPS", os.path.join(updir, "audio", "www", "clips")) # self.mk_choice_row("CLIPS", init_clips, "WAV Clips Output Directory:", isdir=True) self.mk_text_row("PG_TITLE", "Kwaras Corpus", "HTML Page Title:") nav_bar = """<div align="right"> <a href="index.html">Corpus - <a href="dict.xhtml">Dictionary nav_bar = self.cfg.get("NAV_BAR", nav_bar) self.mk_text_box("NAV_BAR", nav_bar, "HTML div for Navigation", rowspan=4) self.buttons["Okay"] = tk.Button(self.frame, text="Okay", command=self._destroy_root) self.buttons["Okay"].grid(row=100, column=3, sticky=E) self._focus() self.tkroot.mainloop() def _focus(self): self.tkroot.attributes("-topmost", True) if sys.platform == "darwin": # MacOS doesn't let tk manipulate window order, so use an applescript command command = """ /usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' """ try: subprocess.check_call(shlex.split(command)) except subprocess.CalledProcessError as e: print("Warning: Unable to bring Kwaras window to front.") print(e.message) self.tkroot.focus_force() self.tkroot.attributes("-topmost", False) def _destroy_root(self): """Store config settings on close""" self.tkroot.destroy() for varname in self.variables: self.cfg[varname] = self.variables[varname].get() # print "Setting", varname, self.variables[varname].get() # print "Writing settings to", self.cfg_file with open(self.cfg_file, "w") as cfg_fs: json.dump(self.cfg, cfg_fs, indent=3, separators=(',', ': ')) def _insert_index(self, idx): self.indices += [idx] self.indices.sort() def mk_label_row(self, text, idx=-1): """Make Subheading Labels""" idx = idx if idx > 0 and idx not in self.indices else max(self.indices + [0]) + 1 self._insert_index(idx) tk.Label(self.frame, text=text, font=("Helvetica", 12)).grid(row=idx, column=1, columnspan=3, sticky=(E, W)) def mk_text_row(self, var, default, text, idx=-1): """Make single-line Entry row""" idx = idx if idx > 0 and idx not in self.indices else max(self.indices + [0]) + 1 self._insert_index(idx) self.labels[var] = tk.Label(self.frame, text=text) self.labels[var].grid(row=idx, column=1, sticky=E) self.variables[var] = tk.StringVar(value=self.cfg.get(var, default)) self.entries[var] = tk.Entry(self.frame, textvariable=self.variables[var], width=_WIDTH) self.entries[var].grid(row=idx, column=2, sticky=W) def mk_text_box(self, var, default, text, rowspan=2, idx=-1): """Make a multi-line Text Box field""" idx = idx if idx > 0 and idx not in self.indices else max(self.indices + [0]) + 1 self._insert_index(idx) self.labels[var] = tk.Label(self.frame, text=text) self.labels[var].grid(row=idx, column=1, sticky=E) self.variables[var] = tk.StringVar(value=self.cfg.get(var, default)) self.entries[var] = MyText(self.frame, self.variables[var], width=_WIDTH, height=rowspan, font=("Helvetica", 12)) self.entries[var].grid(row=idx, column=2, columnspan=1, sticky=W) def mk_menu_row(self, var, default, text, idx=-1): """Make Option Menu rows""" idx = idx if idx > 0 and idx not in self.indices else max(self.indices + [0]) + 1 self._insert_index(idx) self.labels[var] = tk.Label(self.frame, text=text) self.labels[var].grid(row=idx, column=1, sticky=E) self.variables[var] = tk.StringVar(value=self.cfg.get(var, default)) self.entries[var] = tk.OptionMenu(self.frame, self.variables[var], "Raramuri", "Kumiai", "Mixtec", "Other") self.entries[var].grid(row=idx, column=2, sticky=W) def mk_choice_row(self, var, default, text, isdir=False, issave=False, idx=-1): """Make a row for a File/Directory selector""" idx = idx if idx > 0 and idx not in self.indices else max(self.indices + [0]) + 1 self._insert_index(idx) self.labels[var] = tk.Label(self.frame, text=text) self.labels[var].grid(row=idx, column=1, sticky=E) self.variables[var] = tk.StringVar(value=self.cfg.get(var, default)) self.entries[var] = tk.Entry(self.frame, textvariable=self.variables[var], width=_WIDTH) self.entries[var].grid(row=idx, column=2, sticky=W) def callback(): options = { 'initialdir': self.variables[var].get(), 'parent': self.tkroot, 'title': "Choose " + text } if not os.path.exists(options['initialdir']): options['initialdir'] = '' if isdir: dvar = tkFileDialog.askdirectory(**options) elif issave: dvar = tkFileDialog.asksaveasfilename(**options) else: dvar = tkFileDialog.askopenfilename(**options) self.variables[var].set(dvar) self.buttons[var] = tk.Button(self.frame, text="Choose", command=callback) self.buttons[var].grid(row=idx, column=3, sticky=E) # Text Entry Boxes class MyText(tk.Text): def __init__(self, master=None, textvar=None, *options, **kw): tk.Text.__init__(self, master, *options, **kw) if textvar is not None: self.textvar = textvar else: self.textvar = tk.StringVar() self.insert("1.0", self.textvar.get()) def destroy(self): self.textvar.set(self.get("1.0", END)) tk.Text.destroy(self) if __name__ == "__main__": ConfigWindow(CFG_FILE)
python
15
0.581056
119
43.516129
217
starcoderdata
#ifndef _INCLUDE_TEXT_H #define _INCLUDE_TEXT_H #include "drawable.h" #include "tiny_string.h" #include "vector.h" class Text : public Drawable { public: Text(const char* str, int lineWidth = 0, bool transparentBackground = false); virtual int16_t width() const; virtual int16_t height() const; virtual void draw(char* target, int16_t targetWidth, int16_t targetHeight, int16_t x, int16_t y) const; private: tnd::vector m_text; int16_t m_width; int16_t m_height; bool m_transparentBackground; }; #endif
c
11
0.697464
107
21.12
25
starcoderdata
import axios from "axios"; import config from "../../config"; export const TABLES_FILTER_LOAD = "tables/filter/load"; export const TABLES_FILTER_SET_ACTIVE = "tables/filter/set/active"; export const TABLES_FILTER_CLEAR = "tables/filter/clear"; export const TABLES_FILTER_ERROR = "tables/filter/error"; export const TABLES_FILTER_SEARCH_VALUE = "tables/filter/search/value"; export const TABLES_FILTER_SEARCH_OPTION = "tables/filter/search/option"; export const TABLES_COLUMN_SET_ORDER = "tables/column/set/order"; export const TABLES_ROW_SET_ORDER = "tables/row/set/order"; export const TABLES_PAGINATION = "tables/pagination"; export const TABLES_PAGINATION_SELECT_PAGE_SIZE = "tables/pagination/page/size"; export function filterAdd(table, filter) { return { type: TABLES_FILTER_SET_ACTIVE, table, filter, active:true }; } export function filterRemove(table, filter) { return { type: TABLES_FILTER_SET_ACTIVE, table, filter, active:false }; } export function filterLoad(table) { return function (dispatch) { dispatch({ type: TABLES_FILTER_CLEAR, table }); axios.get(config.api.url + "/" + table + "/filters") .then((data) => { dispatch({ type: TABLES_FILTER_LOAD, table, payload: data.data.data?data.data.data:data.data }); }).catch((error)=> { dispatch({ type: TABLES_FILTER_ERROR, table, payload: error }); }); }; } export function filterSearchValue(table,filter,value) { return { type: TABLES_FILTER_SEARCH_VALUE, table, filter, value }; } export function filterSearchOption(table,filter,option) { return { type: TABLES_FILTER_SEARCH_OPTION, table, filter, option }; } export function tableColumnOrderSet(table,columns) { return { type: TABLES_COLUMN_SET_ORDER, table, columns }; } export function tableRowOrderSet(table,column) { return { type: TABLES_ROW_SET_ORDER, table, rowSortKey:column }; } export function userTablePagination(table, value) { return { type: TABLES_PAGINATION, table, value }; } export function userTablePaginationSelectPageSize(table, pageSize, pageNumber, numberOfPages, numberOfElements) { return { type: TABLES_PAGINATION_SELECT_PAGE_SIZE, table, pageSize, pageNumber, numberOfPages, numberOfElements }; }
javascript
20
0.596043
113
24.504587
109
starcoderdata
/*- * Copyright (c) 2016, 1&1 Internet SE * Copyright (c) 2016, * All rights reserved * * Use of this source code is governed by a 2-clause BSD license * that can be found in the LICENSE file. */ package proto type Grant struct { ID string `json:"id"` RecipientType string `json:"recipientType"` RecipientID string `json:"recipientId"` PermissionID string `json:"permissionId"` Category string `json:"category"` ObjectType string `json:"objectType"` ObjectID string `json:"objectId"` Details *DetailsCreation `json:"details,omitempty"` } func (g *Grant) Clone() Grant { clone := Grant{ ID: g.ID, RecipientType: g.RecipientType, RecipientID: g.RecipientID, PermissionID: g.PermissionID, Category: g.Category, ObjectType: g.ObjectType, ObjectID: g.ObjectID, } if g.Details != nil { clone.Details = g.Details.Clone() } return clone } type GrantFilter struct { RecipientType string `json:"recipientType"` RecipientID string `json:"recipientId"` PermissionID string `json:"permissionId"` Category string `json:"category"` ObjectType string `json:"objectType"` ObjectID string `json:"objectId"` } func NewGrantRequest() Request { return Request{ Flags: &Flags{}, Grant: &Grant{}, } } func NewGrantFilter() Request { return Request{ Filter: &Filter{ Grant: &GrantFilter{}, }, } } func NewGrantResult() Result { return Result{ Errors: &[]string{}, Grants: &[]Grant{}, } } // vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
go
17
0.635701
64
22.528571
70
starcoderdata
fn main() { //since we `use game::GameState` above we can just create a new GameState //new is a function of GameState, check in the game.rs file let mut my_game = GameState::new(); //this function contains the main game loop, main just goes into there, //and then doesn't come back here till the game is exited. my_game.main_loop(); //just a message for when the program finally exits println!("Thanks for playing?") }
rust
6
0.682119
77
36.833333
12
inline
double Ray::getIntersectionDistance(const Sphere &sphere) const { // Reference: Lecture 16, starting at slide 5 Vector center(sphere.position[0], sphere.position[1], sphere.position[2]); Vector dist = origin - center; double r = sphere.radius; double b = 2 * direction.dot(dist); double c = dist.dot(dist) - pow(r, 2); double disc = pow(b, 2) - 4 * c; // Imaginary number if(disc < 0) { return -1.0; } // Calculate both quadratic results double t0 = (-b + sqrt(disc)) / 2.0; double t1 = (-b - sqrt(disc)) / 2.0; double t; if (t0 < effective_zero && t1 < effective_zero) { return -1.0; } else if (t0 < effective_zero) { t = t1; } else if (t1 < effective_zero) { t = t0; } else { t = std::min(t0, t1); } return t; }
c++
14
0.553699
78
25.21875
32
inline
import java.util.Arrays; import java.util.List; import javax.management.InvalidAttributeValueException; import org.apache.commons.csv.CSVRecord; public class PatientBase implements Comparable { private static final String[] FIELD_NAMES = { " " "address", "medical record id", "diagnosis" }; public static List getFieldNames() { return Arrays.asList( FIELD_NAMES ); } public PatientBase( String firstName, String lastName, String address, String medicalRecordID, String diagnosis ) throws InvalidAttributeValueException { this.firstName = firstName; this.lastName = lastName; this.address = address; this.medicalRecordID = medicalRecordID; this.diagnosis = diagnosis; validateFields(); } public PatientBase( CSVRecord csvLine ) throws InvalidAttributeValueException { this.firstName = csvLine.get( FIELD_NAMES[0] ); this.lastName = csvLine.get( FIELD_NAMES[1] ); this.address = csvLine.get( FIELD_NAMES[2] ); this.medicalRecordID = csvLine.get( FIELD_NAMES[3] ); this.diagnosis = csvLine.get( FIELD_NAMES[4] ); validateFields(); } protected String firstName; protected String lastName; protected String address; protected String medicalRecordID; protected String diagnosis; protected boolean firstNameValid( String firstName ) { return firstName.matches( "[A-Z][a-z]*" ); } protected boolean lastNameValid( String lastName ) { return lastName.matches( "[A-Z][a-z]*" ); } protected boolean addressValid( String address ) { return address.matches( "\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ); } protected boolean medicalRecordIdValid( String medicalRecordID ) { return medicalRecordID.matches( "[0-9]+" ); } protected boolean diagnosisValid( String diagnosis ) { return !diagnosis.isEmpty(); } protected boolean fieldValid( int fieldId ) { switch ( fieldId ) { case 0: return firstNameValid( this.firstName ); case 1: return lastNameValid( this.lastName ); case 2: return addressValid( this.address ); case 3: return medicalRecordIdValid( this.medicalRecordID ); case 4: return diagnosisValid( this.diagnosis ); default: return false; } } public void validateFields() throws InvalidAttributeValueException { for ( int fieldId = 0; fieldId < FIELD_NAMES.length; ++fieldId ) { if ( !fieldValid( fieldId ) ) { throw new InvalidAttributeValueException( FIELD_NAMES[fieldId] + " is not valid." ); } } } public int compareTo( PatientBase otherPatient ) { return lastName.compareTo( otherPatient.lastName ); } public String toString() { return String.format( "Name: %s %s, Address: %s, Medical record ID: %s, Diagnosis: %s", firstName, lastName, address, medicalRecordID, diagnosis ); } }
java
14
0.560996
100
25.601563
128
starcoderdata
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package test import ( "bytes" "fmt" "math" "sort" "testing" "github.com/m3db/m3/src/query/block" "github.com/m3db/m3/src/query/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // EqualsWithNans helps compare float slices which have NaNs in them func EqualsWithNans(t *testing.T, expected interface{}, actual interface{}) { EqualsWithNansWithDelta(t, expected, actual, 0) } // EqualsWithNansWithDelta helps compare float slices which have NaNs in them // allowing a delta for float comparisons. func EqualsWithNansWithDelta(t *testing.T, expected interface{}, actual interface{}, delta float64) { debugMsg := fmt.Sprintf("expected: %v, actual: %v", expected, actual) switch v := expected.(type) { case [][]float64: actualV, ok := actual.([][]float64) require.True(t, ok, "actual should be of type [][]float64, found: %T", actual) require.Equal(t, len(v), len(actualV), fmt.Sprintf("expected length: %v, actual length: %v\nfor expected: %v, actual: %v", len(v), len(actualV), expected, actual)) for i, vals := range v { debugMsg = fmt.Sprintf("on index %d, expected: %v, actual: %v", i, vals, actualV[i]) equalsWithNans(t, vals, actualV[i], delta, debugMsg) } case []float64: actualV, ok := actual.([]float64) require.True(t, ok, "actual should be of type []float64, found: %T", actual) require.Equal(t, len(v), len(actualV), fmt.Sprintf("expected length: %v, actual length: %v\nfor expected: %v, actual: %v", len(v), len(actualV), expected, actual)) equalsWithNans(t, v, actualV, delta, debugMsg) case float64: actualV, ok := actual.(float64) require.True(t, ok, "actual should be of type float64, found: %T", actual) equalsWithDelta(t, v, actualV, delta, debugMsg) default: require.Fail(t, "unknown type: %T", v) } } func equalsWithNans(t *testing.T, expected []float64, actual []float64, delta float64, debugMsg string) { require.Equal(t, len(expected), len(actual)) for i, v := range expected { if math.IsNaN(v) { require.True(t, math.IsNaN(actual[i]), debugMsg) } else { equalsWithDelta(t, v, actual[i], delta, debugMsg) } } } func equalsWithDelta(t *testing.T, expected, actual, delta float64, debugMsg string) { if math.IsNaN(expected) { require.True(t, math.IsNaN(actual), debugMsg) return } if math.IsInf(expected, 0) { require.Equal(t, expected, actual, debugMsg) return } if delta == 0 { require.Equal(t, expected, actual, debugMsg) } else { diff := math.Abs(expected - actual) require.True(t, delta > diff, debugMsg) } } type match struct { indices []int seriesTags []models.Tag name []byte values []float64 } type matches []match func (m matches) Len() int { return len(m) } func (m matches) Swap(i, j int) { m[i], m[j] = m[j], m[i] } func (m matches) Less(i, j int) bool { return bytes.Compare( models.NewTags(0, nil).AddTags(m[i].seriesTags).ID(), models.NewTags(0, nil).AddTags(m[j].seriesTags).ID(), ) == -1 } // CompareLists compares series meta / index pairs func CompareLists(t *testing.T, meta, exMeta []block.SeriesMeta, index, exIndex [][]int) { require.Equal(t, len(exIndex), len(exMeta)) require.Equal(t, len(exMeta), len(meta)) require.Equal(t, len(exIndex), len(index)) ex := make(matches, len(meta)) actual := make(matches, len(meta)) // build matchers for i := range meta { ex[i] = match{exIndex[i], exMeta[i].Tags.Tags, exMeta[i].Name, []float64{}} actual[i] = match{index[i], meta[i].Tags.Tags, meta[i].Name, []float64{}} } sort.Sort(ex) sort.Sort(actual) assert.Equal(t, ex, actual) } // CompareValues compares series meta / value pairs func CompareValues(t *testing.T, meta, exMeta []block.SeriesMeta, vals, exVals [][]float64) { require.Equal(t, len(exVals), len(exMeta)) require.Equal(t, len(exMeta), len(meta), "Meta is", meta, "ExMeta is", exMeta) require.Equal(t, len(exVals), len(vals), "Vals is", meta, "ExVals is", exMeta) ex := make(matches, len(meta)) actual := make(matches, len(meta)) // build matchers for i := range meta { ex[i] = match{[]int{}, exMeta[i].Tags.Tags, exMeta[i].Name, exVals[i]} actual[i] = match{[]int{}, meta[i].Tags.Tags, exMeta[i].Name, vals[i]} } sort.Sort(ex) sort.Sort(actual) for i := range ex { assert.Equal(t, ex[i].name, actual[i].name) assert.Equal(t, ex[i].seriesTags, actual[i].seriesTags) EqualsWithNansWithDelta(t, ex[i].values, actual[i].values, 0.00001) } }
go
14
0.690626
93
33.018293
164
starcoderdata
package org.webbitserver.netty; import org.webbitserver.WebServer; import org.webbitserver.WebSocket; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.Executors; public class WssClientTest extends WebSocketClientVerification { @Override protected WebServer createServer() throws IOException { NettyWebServer webServer = new NettyWebServer(Executors.newSingleThreadExecutor(), new InetSocketAddress(9988), URI.create("https://localhost:9988")); webServer.setupSsl(getClass().getResourceAsStream("/ssl/keystore"), "webbit"); return webServer; } @Override protected void configure(WebSocket ws) { ws.setupSsl(getClass().getResourceAsStream("/ssl/keystore"), "webbit"); } }
java
12
0.751576
158
33.478261
23
starcoderdata
const { body, check } = require('express-validator'); const msg = require('../errorMessages'); const User = require('../models/User'); const { checkPassword } = require('../utils'); const debug = require('debug')('app:validation'); module.exports = (request) => { switch (request) { case 'login': return [ check('email', msg.NO_EMAIL_PROVIDED) .exists() .isEmail() .normalizeEmail() .bail() .custom(async (value, { req }) => { const user = await User.query().findOne({ email: value, }); if (!user) { throw new Error('No account is associated with that email.'); } // storing this here to prevent multiple db calls req.user = user; }), check('password', msg.NO_PASSWORD_PROVIDED) .exists() .not() .isEmpty() .bail() .custom(async (value, { req }) => { const user = req.user ? req.user : await User.query().findOne({ email: req.body.email }); // TODO: error handling in the event that this fails for any reason if (user) { const correctPassword = await checkPassword(user.password, value); if (!correctPassword) { throw new Error('Invalid Credentials'); } } }), ]; case 'register': return [ check('firstName', 'First name is required').exists().not().isEmpty(), check('lastName', 'Last name is required').exists().not().isEmpty(), check('email', msg.NO_EMAIL_PROVIDED) .exists() .isEmail() .normalizeEmail() .custom(async (value, { req }) => { const user = await User.query().findOne({ email: value, }); if (user) { throw new Error('That email is already in use.'); } }), check('password', msg.NO_PASSWORD_PROVIDED).exists().not().isEmpty(), check('passwordConfirmation').custom((value, { req }) => { if (value !== req.body.password) { throw new Error('Password confirmation does not match password'); } return true; }), ]; default: return []; } };
javascript
24
0.493088
80
29.602564
78
starcoderdata