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
<?php class Proposal extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Proposal_model'); $this->load->model('Admin_model'); $this->load->library('form_validation'); } public function index() { $data['proposals'] = $this->Proposal_model->getAllProposal(); $this->load->view('templates/header'); $this->load->view('proposal/index', $data); $this->load->view('templates/footer'); } public function add() { $this->form_validation->set_rules('title', 'Title', 'required'); $this->form_validation->set_rules('end_date', 'End date', 'required'); $this->form_validation->set_rules('user_addr', 'User address', 'required'); $this->form_validation->set_rules('choices[]', 'Choices', 'required'); if ($this->form_validation->run() == false) { $this->load->view('templates/header'); $this->load->view('proposal/add'); $this->load->view('templates/footer'); } else { $this->Proposal_model->add(); $this->session->set_flashdata('flash', 'added'); redirect('proposal'); } } public function detail($id) { if ($this->Proposal_model->getProposalById($id) == null) { show_404(); } else { $data['proposal'] = $this->Proposal_model->getProposalById($id); $data['options'] = $this->Proposal_model->getOptionsByProposalId($id); $votes = $this->Proposal_model->getAllVotes($id); $data['votes'] = $votes; date_default_timezone_set('Asia/Jakarta'); $now = new DateTime(); $end_date = new DateTime($data['proposal']['end_date']); if (count($votes) > 0) { $votingPoints = $this->Proposal_model->calculateVotingPoints($id); $data['votingPoints'] = $votingPoints; } if ($now > $end_date) { $data['is_close'] = true; } else { $data['is_close'] = false; } // ================================================================ $this->form_validation->set_rules('flexRadioDefault', 'Choice', 'required'); $this->form_validation->set_rules('user_addr', 'User address', 'required'); if ($this->form_validation->run() == false) { $this->load->view('templates/header'); $this->load->view('proposal/detail', $data); $this->load->view('templates/footer'); } else { $this->Proposal_model->vote(); $this->session->set_flashdata('flash', 'voted'); redirect('proposal'); } } } public function is_already_vote($proposalId, $userAddr) { if ($this->Proposal_model->isAlreadyVote($proposalId, $userAddr) == NULL) { echo 0; } else { echo 1; } } }
php
16
0.500326
88
32.391304
92
starcoderdata
import React from "react"; const GlobalContext = React.createContext({ userObject: {}, setUserObject: function () {}, token: "", setToken: function () {} }); export default GlobalContext;
javascript
9
0.641148
43
18
11
starcoderdata
package metrics import ( "github.com/prometheus/client_golang/prometheus" ) // Controller related metrics var ( RunnerPoolSecretRetryCount *prometheus.CounterVec runnerPoolReplicas *prometheus.GaugeVec runnerOnlineVec *prometheus.GaugeVec runnerBusyVec *prometheus.GaugeVec runnerLabelSet = map[string]map[string]struct{}{} ) func InitControllerMetrics(registry prometheus.Registerer) { RunnerPoolSecretRetryCount = prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: metricsNamespace, Subsystem: runnerPoolSubsystem, Name: "secret_retry_count", Help: "The number of times meows retried continuously to get github token", }, []string{"runnerpool"}, ) runnerPoolReplicas = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: metricsNamespace, Subsystem: runnerPoolSubsystem, Name: "replicas", Help: "the number of the RunnerPool replicas", }, []string{"runnerpool"}, ) runnerOnlineVec = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: metricsNamespace, Subsystem: runnerSubsystem, Name: "online", Help: "1 if the runner is online", }, []string{"runnerpool", "runner"}, ) runnerBusyVec = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: metricsNamespace, Subsystem: runnerSubsystem, Name: "busy", Help: "1 if the runner is busy", }, []string{"runnerpool", "runner"}, ) runnerLabelSet = map[string]map[string]struct{}{} registry.MustRegister( RunnerPoolSecretRetryCount, runnerPoolReplicas, runnerOnlineVec, runnerBusyVec, ) } func UpdateRunnerPoolMetrics(runnerpool string, replicas int) { runnerPoolReplicas.WithLabelValues(runnerpool).Set(float64(replicas)) } func DeleteRunnerPoolMetrics(runnerpool string) { runnerPoolReplicas.DeleteLabelValues(runnerpool) } func UpdateRunnerMetrics(runnerpool, runner string, online, busy bool) { if _, ok := runnerLabelSet[runnerpool]; !ok { runnerLabelSet[runnerpool] = map[string]struct{}{} } runnerLabelSet[runnerpool][runner] = struct{}{} var val1 float64 if online { val1 = 1.0 } runnerOnlineVec.WithLabelValues(runnerpool, runner).Set(val1) var val2 float64 if busy { val2 = 1.0 } runnerBusyVec.WithLabelValues(runnerpool, runner).Set(val2) } func DeleteRunnerMetrics(runnerpool string, runners ...string) { labelSet, ok := runnerLabelSet[runnerpool] if !ok { return } for _, r := range runners { runnerOnlineVec.DeleteLabelValues(runnerpool, r) runnerBusyVec.DeleteLabelValues(runnerpool, r) delete(labelSet, r) } if len(labelSet) == 0 { delete(runnerLabelSet, runnerpool) } } func DeleteAllRunnerMetrics(runnerpool string) { labelSet, ok := runnerLabelSet[runnerpool] if !ok { return } runners := make([]string, 0, len(labelSet)) for r := range labelSet { runners = append(runners, r) } DeleteRunnerMetrics(runnerpool, runners...) }
go
12
0.721978
83
23.815126
119
starcoderdata
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.storm.trident.windowing; import org.apache.storm.coordination.BatchOutputCollector; import org.apache.storm.trident.operation.Aggregator; import org.apache.storm.trident.spout.IBatchID; import org.apache.storm.trident.tuple.TridentTuple; import org.apache.storm.trident.tuple.TridentTupleView; import org.apache.storm.trident.windowing.config.WindowConfig; import org.apache.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * This window manager uses {@code WindowsStore} for storing tuples and other trigger related information. It maintains * tuples cache of {@code maxCachedTuplesSize} without accessing store for getting them. * */ public class StoreBasedTridentWindowManager extends AbstractTridentWindowManager { private static final Logger LOG = LoggerFactory.getLogger(StoreBasedTridentWindowManager.class); private static final String TUPLE_PREFIX = "tu" + WindowsStore.KEY_SEPARATOR; private final String windowTupleTaskId; private final TridentTupleView.FreshOutputFactory freshOutputFactory; private Long maxCachedTuplesSize; private final Fields inputFields; private AtomicLong currentCachedTuplesSize = new AtomicLong(); public StoreBasedTridentWindowManager(WindowConfig windowConfig, String windowTaskId, WindowsStore windowStore, Aggregator aggregator, BatchOutputCollector delegateCollector, Long maxTuplesCacheSize, Fields inputFields) { super(windowConfig, windowTaskId, windowStore, aggregator, delegateCollector); this.maxCachedTuplesSize = maxTuplesCacheSize; this.inputFields = inputFields; freshOutputFactory = new TridentTupleView.FreshOutputFactory(inputFields); windowTupleTaskId = TUPLE_PREFIX + windowTaskId; } protected void initialize() { // get existing tuples and pending/unsuccessful triggers for this operator-component/task and add them to WindowManager String windowTriggerInprocessId = WindowTridentProcessor.getWindowTriggerInprocessIdPrefix(windowTaskId); String windowTriggerTaskId = WindowTridentProcessor.getWindowTriggerTaskPrefix(windowTaskId); List attemptedTriggerKeys = new ArrayList<>(); List triggerKeys = new ArrayList<>(); Iterable allEntriesIterable = windowStore.getAllKeys(); for (String key : allEntriesIterable) { if (key.startsWith(windowTupleTaskId)) { int tupleIndexValue = lastPart(key); String batchId = secondLastPart(key); LOG.debug("Received tuple with batch [{}] and tuple index [{}]", batchId, tupleIndexValue); windowManager.add(new TridentBatchTuple(batchId, System.currentTimeMillis(), tupleIndexValue)); } else if (key.startsWith(windowTriggerTaskId)) { triggerKeys.add(key); LOG.debug("Received trigger with key [{}]", key); } else if(key.startsWith(windowTriggerInprocessId)) { attemptedTriggerKeys.add(key); LOG.debug("Received earlier unsuccessful trigger [{}] from windows store [{}]", key); } } // these triggers will be retried as part of batch retries Set triggersToBeIgnored = new HashSet<>(); Iterable attemptedTriggers = windowStore.get(attemptedTriggerKeys); for (Object attemptedTrigger : attemptedTriggers) { triggersToBeIgnored.addAll((List attemptedTrigger); } // get trigger values only if they have more than zero Iterable triggerObjects = windowStore.get(triggerKeys); int i=0; for (Object triggerObject : triggerObjects) { int id = lastPart(triggerKeys.get(i++)); if(!triggersToBeIgnored.contains(id)) { LOG.info("Adding pending trigger value [{}]", triggerObject); pendingTriggers.add(new TriggerResult(id, (List triggerObject)); } } } private int lastPart(String key) { int lastSepIndex = key.lastIndexOf(WindowsStore.KEY_SEPARATOR); if (lastSepIndex < 0) { throw new IllegalArgumentException("primaryKey does not have key separator '" + WindowsStore.KEY_SEPARATOR + "'"); } return Integer.parseInt(key.substring(lastSepIndex+1)); } private String secondLastPart(String key) { int lastSepIndex = key.lastIndexOf(WindowsStore.KEY_SEPARATOR); if (lastSepIndex < 0) { throw new IllegalArgumentException("key "+key+" does not have key separator '" + WindowsStore.KEY_SEPARATOR + "'"); } String trimKey = key.substring(0, lastSepIndex); int secondLastSepIndex = trimKey.lastIndexOf(WindowsStore.KEY_SEPARATOR); if (secondLastSepIndex < 0) { throw new IllegalArgumentException("key "+key+" does not have second key separator '" + WindowsStore.KEY_SEPARATOR + "'"); } return key.substring(secondLastSepIndex+1, lastSepIndex); } public void addTuplesBatch(Object batchId, List tuples) { LOG.debug("Adding tuples to window-manager for batch: [{}]", batchId); List entries = new ArrayList<>(); for (int i = 0; i < tuples.size(); i++) { String key = keyOf(batchId); TridentTuple tridentTuple = tuples.get(i); entries.add(new WindowsStore.Entry(key+i, tridentTuple.select(inputFields))); } // tuples should be available in store before they are added to window manager windowStore.putAll(entries); for (int i = 0; i < tuples.size(); i++) { String key = keyOf(batchId); TridentTuple tridentTuple = tuples.get(i); addToWindowManager(i, key, tridentTuple); } } private void addToWindowManager(int tupleIndex, String effectiveBatchId, TridentTuple tridentTuple) { TridentTuple actualTuple = null; if (maxCachedTuplesSize == null || currentCachedTuplesSize.get() < maxCachedTuplesSize) { actualTuple = tridentTuple; } currentCachedTuplesSize.incrementAndGet(); windowManager.add(new TridentBatchTuple(effectiveBatchId, System.currentTimeMillis(), tupleIndex, actualTuple)); } public String getBatchTxnId(Object batchId) { if (!(batchId instanceof IBatchID)) { throw new IllegalArgumentException("argument should be an IBatchId instance"); } return ((IBatchID) batchId).getId().toString(); } public String keyOf(Object batchId) { return windowTupleTaskId + getBatchTxnId(batchId) + WindowsStore.KEY_SEPARATOR; } public List getTridentTuples(List tridentBatchTuples) { List resultTuples = new ArrayList<>(); List keys = new ArrayList<>(); for (TridentBatchTuple tridentBatchTuple : tridentBatchTuples) { TridentTuple tuple = collectTridentTupleOrKey(tridentBatchTuple, keys); if(tuple != null) { resultTuples.add(tuple); } } if(keys.size() > 0) { Iterable storedTupleValues = windowStore.get(keys); for (Object storedTupleValue : storedTupleValues) { TridentTuple tridentTuple = freshOutputFactory.create((List storedTupleValue); resultTuples.add(tridentTuple); } } return resultTuples; } public TridentTuple collectTridentTupleOrKey(TridentBatchTuple tridentBatchTuple, List keys) { if (tridentBatchTuple.tridentTuple != null) { return tridentBatchTuple.tridentTuple; } keys.add(tupleKey(tridentBatchTuple)); return null; } public void onTuplesExpired(List expiredTuples) { if (maxCachedTuplesSize != null) { currentCachedTuplesSize.addAndGet(-expiredTuples.size()); } List keys = new ArrayList<>(); for (TridentBatchTuple expiredTuple : expiredTuples) { keys.add(tupleKey(expiredTuple)); } windowStore.removeAll(keys); } private String tupleKey(TridentBatchTuple tridentBatchTuple) { return tridentBatchTuple.effectiveBatchId + tridentBatchTuple.tupleIndex; } }
java
17
0.685684
138
42.738532
218
starcoderdata
<?php define("_BG_COLOR_","#95afff"); define("_BG_COLOR_DARK_","#555555"); define("_BG_GROUP_","wall"); define("_PICTURES_NUM_",10); ?>
php
6
0.595588
36
18.571429
7
starcoderdata
using Emgu.CV; using Emgu.CV.Structure; using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Windows.Forms; namespace RobotRuntime.Utils { public static class BitmapUtility { public unsafe static Bitmap Clone32BPPBitmap(Bitmap srcBitmap, Bitmap result) { Rectangle bmpBounds = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height); BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat); BitmapData resData = result.LockBits(bmpBounds, ImageLockMode.WriteOnly, result.PixelFormat); int* srcScan0 = (int*)srcData.Scan0; int* resScan0 = (int*)resData.Scan0; int numPixels = srcData.Stride / 4 * srcData.Height; try { for (int p = 0; p < numPixels; p++) { resScan0[p] = srcScan0[p]; } } finally { srcBitmap.UnlockBits(srcData); result.UnlockBits(resData); } return result; } /// /// Not tested to work /// public static Bitmap Copy32BPPBitmapSafe(Bitmap srcBitmap, Bitmap result) { //Bitmap result = new Bitmap(srcBitmap.Width, srcBitmap.Height, PixelFormat.Format32bppArgb); Rectangle bmpBounds = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height); BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat); BitmapData resData = result.LockBits(bmpBounds, ImageLockMode.WriteOnly, result.PixelFormat); Int64 srcScan0 = srcData.Scan0.ToInt64(); Int64 resScan0 = resData.Scan0.ToInt64(); int srcStride = srcData.Stride; int resStride = resData.Stride; int rowLength = Math.Abs(srcData.Stride); try { byte[] buffer = new byte[rowLength]; for (int y = 0; y < srcData.Height; y++) { Marshal.Copy(new IntPtr(srcScan0 + y * srcStride), buffer, 0, rowLength); Marshal.Copy(buffer, 0, new IntPtr(resScan0 + y * resStride), rowLength); } } finally { srcBitmap.UnlockBits(srcData); result.UnlockBits(resData); } return result; } public static Image<Bgr, byte> ToImage(this Bitmap bmp) { return new Image<Bgr, byte>(bmp); } public static Bitmap TakeScreenshotOfSpecificRect(Point p1, Point p2) { var topLeft = new Point(p1.X < p2.X ? p1.X : p2.X, p1.Y < p2.Y ? p1.Y : p2.Y); var botRight = new Point(p1.X >= p2.X ? p1.X : p2.X, p1.Y >= p2.Y ? p1.Y : p2.Y); var rect = new Rectangle(0, 0, botRight.X - topLeft.X, botRight.Y - topLeft.Y); return TakeScreenshotOfSpecificRect(topLeft, rect.Size); } public static Bitmap TakeScreenshotOfSpecificRect(Point upperLeftPoint, Size size) { var screen = Screen.PrimaryScreen; var bmp = new Bitmap(size.Width, size.Height); using (var graphics = System.Drawing.Graphics.FromImage(bmp)) { graphics.CopyFromScreen(upperLeftPoint, new Point(0, 0), size); } return bmp; } public static Bitmap TakeScreenshot() { var screen = Screen.PrimaryScreen; return TakeScreenshotOfSpecificRect(new Point(screen.Bounds.Left, screen.Bounds.Top), screen.Bounds.Size); } public static void TakeScreenshot(Bitmap dest) { var screen = Screen.PrimaryScreen; using (var graphics = System.Drawing.Graphics.FromImage(dest)) { graphics.CopyFromScreen(new Point(screen.Bounds.Left, screen.Bounds.Top), new Point(0, 0), screen.Bounds.Size); } } public static Bitmap CropImageFromPoint(Bitmap source, Point center, int size) { return CropImageFromPoint(source, new Point(center.X - size / 2, center.Y - size / 2), new Point(center.X + size / 2, center.Y + size / 2)); } public static Bitmap CropImageFromPoint(Bitmap source, Point from, Point to) { var topLeft = new Point(from.X < to.X ? from.X : to.X, from.Y < to.Y ? from.Y : to.Y); var botRight = new Point(from.X >= to.X ? from.X : to.X, from.Y >= to.Y ? from.Y : to.Y); var rect = new Rectangle(0, 0, botRight.X - topLeft.X, botRight.Y - topLeft.Y); var bmp = new Bitmap(rect.Width, rect.Height, source.PixelFormat); for (int x = 0; x < rect.Width; ++x) for (int y = 0; y < rect.Height; ++y) bmp.SetPixel(x, y, source.GetPixel(topLeft.X + x, topLeft.Y + y)); return bmp; } public static Bitmap ResizeBitmap(Bitmap bmp, Rectangle rect) { var newBmp = new Bitmap(rect.Width, rect.Height); using (var g = System.Drawing.Graphics.FromImage(newBmp)) { g.DrawImage(bmp, new Rectangle(0, 0, newBmp.Width, newBmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel); } return newBmp; } public static Rectangle GetRect(Point p1, Point p2) { var topLeft = new Point(p1.X < p2.X ? p1.X : p2.X, p1.Y < p2.Y ? p1.Y : p2.Y); var botRight = new Point(p1.X >= p2.X ? p1.X : p2.X, p1.Y >= p2.Y ? p1.Y : p2.Y); var rect = new Rectangle(0, 0, botRight.X - topLeft.X, botRight.Y - topLeft.Y); rect.Location = topLeft; return rect; } // Those Might be way faster than taking screenshot and getting pixels // while you can take pixels from screen directly without taking screenshot [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr GetWindowDC(IntPtr window); [DllImport("gdi32.dll", SetLastError = true)] public static extern uint GetPixel(IntPtr dc, int x, int y); [DllImport("user32.dll", SetLastError = true)] public static extern int ReleaseDC(IntPtr window, IntPtr dc); public static Color GetColorAt(int x, int y) { IntPtr desk = GetDesktopWindow(); IntPtr dc = GetWindowDC(desk); int a = (int)GetPixel(dc, x, y); ReleaseDC(desk, dc); return Color.FromArgb(255, (a >> 0) & 0xff, (a >> 8) & 0xff, (a >> 16) & 0xff); } public static Rectangle Bounds(this Bitmap bmp) { return new Rectangle(0, 0, bmp.Width, bmp.Height); } } }
c#
20
0.564905
132
38.859551
178
starcoderdata
using System; using System.Linq; using System.Threading.Tasks; using BaGet.Protocol.Internal; using Xunit; namespace BaGet.Protocol.Tests { public class CatalogClientTests : IClassFixture { private readonly CatalogClient _target; public CatalogClientTests(ProtocolFixture fixture) { _target = fixture.CatalogClient; } [Fact] public async Task GetsCatalogIndex() { var result = await _target.GetIndexAsync(); Assert.NotNull(result); Assert.True(result.Count > 0); Assert.NotEmpty(result.Items); } [Fact] public async Task GetsCatalogLeaf() { var index = await _target.GetIndexAsync(); var pageItem = index.Items.First(); var page = await _target.GetPageAsync(pageItem.CatalogPageUrl); var leafItem = page.Items.First(); CatalogLeaf result; switch (leafItem.Type) { case CatalogLeafType.PackageDelete: result = await _target.GetPackageDeleteLeafAsync(leafItem.CatalogLeafUrl); break; case CatalogLeafType.PackageDetails: result = await _target.GetPackageDetailsLeafAsync(leafItem.CatalogLeafUrl); break; default: throw new NotSupportedException($"Unknown leaf type '{leafItem.Type}'"); } Assert.NotNull(result.PackageId); } } }
c#
17
0.582145
95
27.803571
56
starcoderdata
/* * Copyright (c) 2018. Real Time Genomics Limited. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rtg.variant.sv.bndeval; import junit.framework.TestCase; /** */ public class BreakpointGeometryTest extends TestCase { public void testConstructor() { final AbstractBreakpointGeometry bc = new BreakpointGeometry(Orientation.UU, "a", "b", 42, 151, 256, 365, 298, 407); bc.integrity(); assertEquals(Orientation.UU, bc.getOrientation()); assertEquals(42, bc.getXLo()); assertEquals(256, bc.getYLo()); assertEquals(/* 42 + 109 */151, bc.getXHi()); assertEquals(/* 256 + 109 */ 365, bc.getYHi()); assertEquals(298, bc.getRLo()); assertEquals(407, bc.getRHi()); } public void testConstructor2() { final AbstractBreakpointGeometry bc = new BreakpointGeometry(Orientation.UD, "a", "b", 42, 151, 256, 147, -214, -105); bc.integrity(); assertEquals(Orientation.UD, bc.getOrientation()); assertEquals(42, bc.getXLo()); assertEquals(256, bc.getYLo()); assertEquals(/* 42 + 109 */151, bc.getXHi()); assertEquals(/* 256 - 109 */ 147, bc.getYHi()); assertEquals(-214, bc.getRLo()); assertEquals(-105, bc.getRHi()); } public void testConstructor3() { final AbstractBreakpointGeometry bc = new BreakpointGeometry(Orientation.DD, "a", "b", 42, -67, 256, 147, -298, -189); bc.integrity(); assertEquals(Orientation.DD, bc.getOrientation()); assertEquals(42, bc.getXLo()); assertEquals(256, bc.getYLo()); assertEquals(/* 42 - 109 */ -67, bc.getXHi()); assertEquals(/* 256 - 109 */ 147, bc.getYHi()); assertEquals(-298, bc.getRLo()); assertEquals(-189, bc.getRHi()); } public void testConstructor4() { final AbstractBreakpointGeometry bc = new BreakpointGeometry(Orientation.DU, "a", "b", 256, 147, 42, 151, -214, -105); bc.integrity(); assertEquals(Orientation.DU, bc.getOrientation()); assertEquals("a", bc.getXName()); assertEquals("b", bc.getYName()); assertEquals(256, bc.getXLo()); assertEquals(42, bc.getYLo()); assertEquals(/* 256 - 109 */ 147, bc.getXHi()); assertEquals(/* 42 + 109 */151, bc.getYHi()); assertEquals(-214, bc.getRLo()); assertEquals(-105, bc.getRHi()); final String exp = "Break-point constraint:DU x=256,147:a y=42,151:b r=-214,-105"; assertEquals(exp, bc.toString()); final AbstractBreakpointGeometry fl = bc.flip(); fl.integrity(); assertEquals(Orientation.UD, fl.getOrientation()); assertEquals("b", fl.getXName()); assertEquals("a", fl.getYName()); assertEquals(42, fl.getXLo()); assertEquals(256, fl.getYLo()); assertEquals(/* 42 + 109 */151, fl.getXHi()); assertEquals(/* 256 - 109 */ 147, fl.getYHi()); assertEquals(-214, fl.getRLo()); assertEquals(-105, fl.getRHi()); } public void testMakeGeometry1() { //see testConstructor4 final BreakpointGeometry bg = BreakpointGeometry.makeGeometry("a", 256, 147, "b", 42, 151, -214, -105); final String exp = "Break-point constraint:DU x=256,147:a y=42,151:b r=-214,-105"; assertEquals(exp, bg.toString()); } public void testMakeGeometry2() { //see testConstructor4 final BreakpointGeometry bg = BreakpointGeometry.makeGeometry("a", 147, 256, "b", 151, 42, 105, 214); final String exp = "Break-point constraint:UD x=147,256:a y=151,42:b r=105,214"; assertEquals(exp, bg.toString()); } // public void testUnionBug() { // final AbstractBreakpointGeometry bg = new BreakpointGeometry(Orientation.UU, "a", "a", 52875, 53251, 49976, 50352, 102877, 103227); // bg.globalIntegrity(); // //System.err.println("bg"); // System.err.println(bg.gnuPlot()); // // final AbstractBreakpointGeometry bu = new BreakpointGeometry(Orientation.UU, "a", "a", 49913, 50362, 52815, 53232, 102774, 103218).flip(); // bu.globalIntegrity(); // //System.err.println("bu"); // System.err.println(bu.gnuPlot()); // // //System.err.println("in"); // System.err.println(bg.intersect(bu).gnuPlot()); // // //System.err.println("un"); // System.err.println(bg.union(bu).gnuPlot()); // } }
java
8
0.675194
146
36.506757
148
starcoderdata
inline const INT CSemaphore::CAvail() const { // read the current state of the semaphore const CSemaphoreState stateCur = (CSemaphoreState&) State(); // return the available count return stateCur.FNoWait() ? stateCur.CAvail() : 0; }
c++
8
0.6917
64
24.4
10
inline
<?php use App\Http\Lumberjack; // Create the Application Container $app = require_once('bootstrap/app.php'); // Bootstrap Lumberjack from the Container $lumberjack = $app->make(Lumberjack::class); $lumberjack->bootstrap(); // Import our routes file require_once('routes.php'); // Set global params in the Timber context add_filter('timber_context', [$lumberjack, 'addToContext']); if (function_exists('acf_add_options_page')) { acf_add_options_page(array( 'page_title' => 'General Options', 'menu_title' => 'Options', 'menu_slug' => 'general-options', 'capability' => 'edit_posts', 'redirect' => false )); } add_filter('timber/context', 'add_to_context'); function add_to_context($context) { $context['options'] = get_fields('option'); return $context; }
php
10
0.648649
60
23.666667
36
starcoderdata
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.indexing.common.actions; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Preconditions; import org.apache.druid.indexing.common.task.Task; import org.apache.druid.indexing.overlord.DataSourceMetadata; import javax.annotation.Nullable; public class CheckPointDataSourceMetadataAction implements TaskAction { private final String supervisorId; @Nullable private final Integer taskGroupId; @Deprecated private final String baseSequenceName; private final DataSourceMetadata previousCheckPoint; private final DataSourceMetadata currentCheckPoint; public CheckPointDataSourceMetadataAction( @JsonProperty("supervisorId") String supervisorId, @JsonProperty("taskGroupId") @Nullable Integer taskGroupId, // nullable for backward compatibility, @JsonProperty("sequenceName") @Deprecated String baseSequenceName, // old version would use this @JsonProperty("previousCheckPoint") DataSourceMetadata previousCheckPoint, @JsonProperty("currentCheckPoint") DataSourceMetadata currentCheckPoint ) { this.supervisorId = Preconditions.checkNotNull(supervisorId, "supervisorId"); this.taskGroupId = taskGroupId; this.baseSequenceName = Preconditions.checkNotNull(baseSequenceName, "sequenceName"); this.previousCheckPoint = Preconditions.checkNotNull(previousCheckPoint, "previousCheckPoint"); this.currentCheckPoint = Preconditions.checkNotNull(currentCheckPoint, "currentCheckPoint"); } @JsonProperty public String getSupervisorId() { return supervisorId; } @Deprecated @JsonProperty("sequenceName") public String getBaseSequenceName() { return baseSequenceName; } @Nullable @JsonProperty public Integer getTaskGroupId() { return taskGroupId; } @JsonProperty public DataSourceMetadata getPreviousCheckPoint() { return previousCheckPoint; } @JsonProperty public DataSourceMetadata getCurrentCheckPoint() { return currentCheckPoint; } @Override public TypeReference getReturnTypeReference() { return new TypeReference { }; } @Override public Boolean perform( Task task, TaskActionToolbox toolbox ) { return toolbox.getSupervisorManager().checkPointDataSourceMetadata( supervisorId, taskGroupId, baseSequenceName, previousCheckPoint, currentCheckPoint ); } @Override public boolean isAudited() { return true; } @Override public String toString() { return "CheckPointDataSourceMetadataAction{" + "supervisorId='" + supervisorId + '\'' + ", baseSequenceName='" + baseSequenceName + '\'' + ", taskGroupId='" + taskGroupId + '\'' + ", previousCheckPoint=" + previousCheckPoint + ", currentCheckPoint=" + currentCheckPoint + '}'; } }
java
21
0.740788
147
29.984252
127
starcoderdata
package mbaracus; import mbaracus.enumerators.HouseType; import mbaracus.query2.model.HouseTypeMean; import mbaracus.query3.model.DepartmentStat; import mbaracus.query4.model.Department; import mbaracus.query5.model.DepartmentCount; import mbaracus.utils.QueryPrinters; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import static org.junit.Assert.assertEquals; public class QueryPrintersTest { // private static final String PREFIX = "../client/src/test/resources/"; // private static final Path QUERY_1_OUTPUT = Paths.get(PREFIX + "query1Output.txt"); // private static final Path QUERY_2_OUTPUT = Paths.get(PREFIX + "query2Output.txt"); // private static final Path QUERY_3_OUTPUT = Paths.get(PREFIX + "query3Output.txt"); // private static final Path QUERY_4_OUTPUT = Paths.get(PREFIX + "query4Output.txt"); // private static final Path QUERY_5_OUTPUT = Paths.get(PREFIX + "query5Output.txt"); // // @Before // public void setUp() { // } // // @Test // public void query1Test() throws IOException { // QueryPrinters.printResultQuery1(QUERY_1_OUTPUT, 25376, 64160, 10464); // // String[] lines = Files.lines(QUERY_1_OUTPUT).toArray(String[]::new); // assertEquals("0-14 = 25376", lines[0]); // assertEquals("15-64 = 64160", lines[1]); // assertEquals("65-? = 10464", lines[2]); // } // // @Test // public void query2Test() throws IOException { // Map<HouseType, HouseTypeMean> map = new HashMap<>(); // map.put(HouseType.from(0), new HouseTypeMean(15.16f)); // map.put(HouseType.from(1), new HouseTypeMean(3.42f)); // map.put(HouseType.from(2), new HouseTypeMean(3.97f)); // map.put(HouseType.from(3), new HouseTypeMean(3.92f)); // map.put(HouseType.from(4), new HouseTypeMean(2.39f)); // map.put(HouseType.from(5), new HouseTypeMean(2.48f)); // map.put(HouseType.from(6), new HouseTypeMean(1.79f)); // map.put(HouseType.from(7), new HouseTypeMean(2.47f)); // map.put(HouseType.from(8), new HouseTypeMean(3.0f)); // map.put(HouseType.from(9), new HouseTypeMean(1.67f)); // // QueryPrinters.printResultQuery2(QUERY_2_OUTPUT, map); // // String[] lines = Files.lines(QUERY_2_OUTPUT).toArray(String[]::new); // assertEquals("0 = 15,16", lines[0]); // assertEquals("1 = 3,42", lines[1]); // assertEquals("2 = 3,97", lines[2]); // assertEquals("3 = 3,92", lines[3]); // assertEquals("4 = 2,39", lines[4]); // assertEquals("5 = 2,48", lines[5]); // assertEquals("6 = 1,79", lines[6]); // assertEquals("7 = 2,47", lines[7]); // assertEquals("8 = 3,00", lines[8]); // assertEquals("9 = 1,67", lines[9]); // } // // @Test // public void query3Test() throws IOException { // List list = new ArrayList<>(5); // list.add(new DepartmentStat(4, 10, " // list.add(new DepartmentStat(25, 100, "Telsen")); // list.add(new DepartmentStat(2, 10, "Rinconada")); // list.add(new DepartmentStat(18, 100, "San Blas de los Sauces")); // list.add(new DepartmentStat(17, 100, "Tehuelches")); // // QueryPrinters.printResultQuery3(QUERY_3_OUTPUT, list); // // String[] lines = Files.lines(QUERY_3_OUTPUT).toArray(String[]::new); // assertEquals(" = 0,40", lines[0]); // assertEquals("Telsen = 0,25", lines[1]); // assertEquals("Rinconada = 0,20", lines[2]); // assertEquals("San Blas de los Sauces = 0,18", lines[3]); // assertEquals("Tehuelches = 0,17", lines[4]); // } // // @Test // public void query4Test() throws IOException { // List list = new ArrayList<>(5); // list.add(new Department("San Fernando", 972)); // list.add(new Department(" 312)); // list.add(new Department("General Güemes", 190)); // list.add(new Department("Libertador General San Martín", 156)); // list.add(new Department(" 137)); // // QueryPrinters.printResultQuery4(QUERY_4_OUTPUT, list); // // String[] lines = Files.lines(QUERY_4_OUTPUT).toArray(String[]::new); // assertEquals("San Fernando = 972", lines[0]); // assertEquals("Comandante Fernández = 312", lines[1]); // assertEquals("General Güemes = 190", lines[2]); // assertEquals("Libertador General San Martín = 156", lines[3]); // assertEquals(" = 137", lines[4]); // } // // @Test // public void query5Test() throws IOException { // Map<String, DepartmentCount> map = new HashMap<>(); // map.put("Quilmes", new DepartmentCount("Quilmes", "Buenos Aires", 1327)); // map.put("San Fernando", new DepartmentCount("San Fernando", "Buenos Aires", 1328)); // map.put("Almirante Brown", new DepartmentCount("Almirante Brown", "Buenos Aires", 1399)); // map.put("Merlo", new DepartmentCount("Merlo", "Buenos Aires", 1415)); // map.put("General San Martín", new DepartmentCount("General San Martín", "Buenos Aires", 1417)); // // QueryPrinters.printResultQuery5(QUERY_5_OUTPUT, map); // // String[] lines = Files.lines(QUERY_5_OUTPUT).toArray(String[]::new); // assertEquals("1300", lines[0]); // assertEquals("San Fernando (Buenos Aires) + Quilmes (Buenos Aires)", lines[1]); // assertEquals("San Fernando (Buenos Aires) + Almirante Brown (Buenos Aires)", lines[2]); // assertEquals("Quilmes (Buenos Aires) + Almirante Brown (Buenos Aires)", lines[3]); // assertEquals("", lines[4]); // assertEquals("1400", lines[5]); // assertEquals("General San Martín (Buenos Aires) + Merlo (Buenos Aires)", lines[6]); // } }
java
5
0.621916
105
44.55814
129
starcoderdata
using System; using Mellis.Core.Entities; using Mellis.Core.Exceptions; using Mellis.Lang.Python3.Entities; using Mellis.Lang.Python3.Instructions; using Mellis.Lang.Python3.Resources; using Mellis.Lang.Python3.VM; using Mellis.Resources; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Mellis.Lang.Python3.Tests.Processor { [TestClass] public class CallNonCallableTests { [TestMethod] public void CallNoValueTest() { // Arrange var processor = new PyProcessor( new Call(SourceReference.ClrSource, 0, 1) ); // Act processor.WalkInstruction(); // warmup var ex = Assert.ThrowsException { processor.WalkInstruction(); }); // Assert Assert.That.ErrorFormatArgsEqual(ex, nameof(Localized_Python3_Interpreter.Ex_ValueStack_PopEmpty) ); } [TestMethod] public void CallIntegerTest() { // Arrange var processor = new PyProcessor( new Call(SourceReference.ClrSource, 0, 1) ); var value = new PyInteger(processor, 0); processor.PushValue(value); // Act processor.WalkInstruction(); // warmup var ex = Assert.ThrowsException { processor.WalkInstruction(); }); // Assert Assert.That.ErrorFormatArgsEqual(ex, nameof(Localized_Base_Entities.Ex_Base_Invoke), value.GetTypeName() ); } } }
c#
19
0.599051
106
28.086207
58
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using WebApi.Entities; using WebApi.Helpers; using WebApi.Dtos; namespace WebApi.Services { public interface IToolService { IList GetAll(); ToolDto AddTool(ToolDto toolDto); } public class ToolService : IToolService { private ToolDataContext _context; private IResourceService _resourceService; private static List toolsDTO = new List public ToolService(IResourceService resourceService, ToolDataContext context) { _context = context; _resourceService = resourceService; } public IList GetAll() { if(toolsDTO.Count == 0) { var toolsWithoutLinks = _context.Tools; foreach(var tool in toolsWithoutLinks) { toolsDTO .Add( new ToolDto { Description = tool.Description, Name = tool.Name, Title = tool.Title, Links = _resourceService.GetLinks(tool.Id).ToList() }); } return toolsDTO; } else { return toolsDTO; } } public ToolDto AddTool(ToolDto toolDto) { var tool = new ToolEntity { Name = toolDto.Name, Description = toolDto.Description, Title = toolDto.Title }; _context.Tools.Add(tool); _context.SaveChanges(); foreach(var link in toolDto.Links) { _resourceService.AddResource(tool.Id, link); } toolsDTO.Add(toolDto); return toolDto; } /* public Tool GetToolById(int id) { //todo refactor } */ } }
c#
24
0.467259
100
24.771084
83
starcoderdata
const puppeteer = require('puppeteer'); const urlLib = require('url'); /* This function extracts all the information we want from the website by using the puppeteer library. Returns the extracted information in JSON format, if it fails at some point, it will return the error. */ exports.extractInfo = function(url, callback) { (async() => { var returnJSON = {}; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setRequestInterception(true); allRequests = []; // all requests made by the website allCertificates = []; // all certificates of the requests made by the website. We will extract the certificate to the domain we search for. certificate = {}; page.on('request', (request) => { allRequests.push({ "url": request.url().trim(), "method": request.method() }); request.continue(); }); page.on('response', async(resPage) => { if (resPage.securityDetails() != null) { allCertificates.push(resPage.securityDetails()); } }); // TO-DO: for the future work, we might also consider sharing a global puppeteer "page" instance // and also break down individiual services (screenshot, pagesource etc) in different try catch statements // In order to make sure that if one of them fails the others won't be affected. try { const response = await page.goto(url, { timeout: 3000000 }); const screenshot = await page.screenshot(); const resp = await response.text(); //page source ip = response._request._response._remoteAddress.ip; const requests = response.request().redirectChain(); // the chain of redirection, in case of any redirectChain = []; for (i = 0; i < requests.length; i++) { redirectChain.push(requests[i].url()); } //filter the certificates, search only for the website's certificate. We need to consider redirection to https as well. const domain = urlLib.parse(url).hostname; for (i = 0; i < allCertificates.length; i++) { if (allCertificates[i]._subjectName.indexOf(domain) > -1 || redirectChain.indexOf(allCertificates[i]._subjectName) > -1) { certificate = allCertificates[i]; break; } } if ("_validFrom" in certificate && "_validTo" in certificate) { certificate["_validFrom"] = new Date(certificate["_validFrom"] * 1000).toLocaleDateString("en-US"); certificate["_validTo"] = new Date(certificate["_validTo"] * 1000).toLocaleDateString("en-US"); } source = ""; destination = ""; if (requests.length > 0) { source = requests[0].url().toString(); destination = requests[requests.length - 1].url().toString(); } returnJSON = { "resp": resp.toString(), "ss": screenshot.toString('base64'), "ip": ip, "allRequests": allRequests, "redirectChain": redirectChain, "sourceDestination": { "source": source, "destination": destination }, "certificate": certificate }; await browser.close(); //regardless of the outcome, close the browser. callback(returnJSON, null); } catch (err) { callback(null, err); } })() }
javascript
21
0.630265
143
35.933333
90
starcoderdata
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class AuthModel extends CI_Model{ function auth_cek($user,$pass) { $query = $this->db->query("SELECT * FROM users WHERE email='".$user."' AND password = '".$pass."'"); return $query; } function auth_cek_id($id) { $query = $this->db->query("SELECT * FROM users WHERE id = $id"); return $query; } function auth_get_all() { $query = $this->db->query("SELECT * FROM users WHERE active = 1"); return $query; } function auth_up_login() { $login_time = date('Y-m-d H:i:s'); $id = $this->session->userdata('ses_id'); $auth_up_login_data = array( 'logged_in' => 1, 'logged_in_time' => $login_time ); $this->db->where('id', $id); $result = $this->db->update('users', $auth_up_login_data); return $result; } function auth_up_logout() { $id = $this->session->userdata('ses_id'); $auth_up_login_data = array( 'logged_in' => 0 ); $this->db->where('id', $id); $result = $this->db->update('users', $auth_up_login_data); return $result; } function auth_add() { $id = $this->session->userdata('ses_id'); $auth_add_data = array( 'name' => $this->input->post('auth_name'), 'email' => $this->input->post('auth_email'), 'level' => $this->input->post('auth_level'), // 'password' => do_hash($this->input->post('auth_email')), 'password' => do_hash($this->input->post('auth_password')), 'created_by' => $id, ); $result = $this->db->insert('users',$auth_add_data); return $result; } function auth_delete() { $update_date = date('Y-m-d H:i:s'); $id = $this->input->post('auth_id'); $auth_delete_data = array( 'active' => 0, 'updated_at' => $update_date, ); $this->db->where('id', $id); $result = $this->db->update('users', $auth_delete_data); return $result; } }
php
16
0.586507
102
24.541667
72
starcoderdata
'use strict'; var Campsi = require('campsi-core'); module.exports = Campsi.extend('text', 'text/area', function () { return { getTagName: function () { return 'textarea'; }, submit: function () { } }; });
javascript
14
0.515625
65
22.363636
11
starcoderdata
protected void processDisconnect() { int count = 0; while (!outgoingMessageQueue.isEmpty()) { // wait until messages are sent try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //time out of about ~10 seconds if (count++ > 10) break; } terminateConnection(); }
java
11
0.642202
43
22.428571
14
inline
/* * Copyright 2011-2018 the original author or 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 io.lettuce.core.protocol; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.openjdk.jmh.annotations.*; import io.lettuce.core.ClientOptions; import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.output.ValueOutput; import io.netty.buffer.ByteBuf; /** * Benchmark for {@link CommandHandler}. * * Test cases: * * command writes * (in-eventloop) writes * (in-eventloop) reads * * * @author * @author */ @State(Scope.Benchmark) public class CommandHandlerBenchmark { private static final ByteArrayCodec CODEC = new ByteArrayCodec(); private static final ClientOptions CLIENT_OPTIONS = ClientOptions.create(); private static final EmptyContext CHANNEL_HANDLER_CONTEXT = new EmptyContext(); private static final byte[] KEY = "key".getBytes(); private static final String VALUE = "value\r\n"; private final EmptyPromise PROMISE = new EmptyPromise(); private CommandHandler commandHandler; private ByteBuf reply1; private ByteBuf reply10; private ByteBuf reply100; private ByteBuf reply1000; private List commands1; private List commands10; private List commands100; private List commands1000; @Setup public void setup() throws Exception { commandHandler = new CommandHandler(CLIENT_OPTIONS, EmptyClientResources.INSTANCE, new DefaultEndpoint(CLIENT_OPTIONS, EmptyClientResources.INSTANCE)); commandHandler.channelRegistered(CHANNEL_HANDLER_CONTEXT); commandHandler.setState(CommandHandler.LifecycleState.CONNECTED); reply1 = createByteBuf(String.format("+%s", VALUE)); reply10 = createByteBuf(createBulkReply(10)); reply100 = createByteBuf(createBulkReply(100)); reply1000 = createByteBuf(createBulkReply(1000)); commands1 = createCommands(1); commands10 = createCommands(10); commands100 = createCommands(100); commands1000 = createCommands(1000); } @TearDown public void tearDown() throws Exception { commandHandler.channelUnregistered(CHANNEL_HANDLER_CONTEXT); Arrays.asList(reply1, reply10, reply100, reply1000).forEach(ByteBuf::release); } private static List createCommands(int count) { return IntStream.range(0, count).mapToObj(i -> createCommand()).collect(Collectors.toList()); } private static ByteBuf createByteBuf(String str) { ByteBuf buf = CHANNEL_HANDLER_CONTEXT.alloc().directBuffer(); buf.writeBytes(str.getBytes()); return buf; } private static String createBulkReply(int numOfReplies) { String baseReply = String.format("$%d\r\n%s\r\n", VALUE.length(), VALUE); return String.join("", Collections.nCopies(numOfReplies, baseReply)); } @SuppressWarnings("unchecked") private static Command createCommand() { return new Command(CommandType.GET, new ValueOutput<>(CODEC), new CommandArgs(CODEC).addKey(KEY)) { @Override public boolean isDone() { return false; } }; } @Benchmark public void measureNettyWriteAndRead() throws Exception { Command command = createCommand(); commandHandler.write(CHANNEL_HANDLER_CONTEXT, command, PROMISE); int index = reply1.readerIndex(); reply1.retain(); commandHandler.channelRead(CHANNEL_HANDLER_CONTEXT, reply1); // cleanup reply1.readerIndex(index); } @Benchmark public void measureNettyWriteAndReadBatch1() throws Exception { doBenchmark(commands1, reply1); } @Benchmark public void measureNettyWriteAndReadBatch10() throws Exception { doBenchmark(commands10, reply10); } @Benchmark public void measureNettyWriteAndReadBatch100() throws Exception { doBenchmark(commands100, reply100); } @Benchmark public void measureNettyWriteAndReadBatch1000() throws Exception { doBenchmark(commands1000, reply1000); } private void doBenchmark(List commandStack, ByteBuf response) throws Exception { commandHandler.write(CHANNEL_HANDLER_CONTEXT, commandStack, PROMISE); int index = response.readerIndex(); response.retain(); commandHandler.channelRead(CHANNEL_HANDLER_CONTEXT, response); // cleanup response.readerIndex(index); } }
java
12
0.69846
126
30.892216
167
starcoderdata
<?php namespace Drupal\social_content_block\Plugin\Field\FieldWidget; use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\social_content_block\ContentBlockManagerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Plugin implementation of the 'content_block_plugin_field' widget. * * @FieldWidget( * id = "content_block_plugin_field", * label = @Translation("Content block plugin field"), * field_types = { * "string" * } * ) */ class ContentBlockPluginFieldWidget extends ContentBlockPluginWidgetBase { /** * The prefix to search for. */ const CONFIG_PREFIX = 'field.field.block_content.custom_content_list.'; /** * An array containing matching configuration object names. * * @var array */ protected $fieldConfigs; /** * Constructs a ContentBlockPluginFieldWidget object. * * @param string $plugin_id * The plugin_id for the widget. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The definition of the field to which the widget is associated. * @param array $settings * The widget settings. * @param array $third_party_settings * Any third party settings. * @param \Drupal\social_content_block\ContentBlockManagerInterface $content_block_manager * The content block manager. * @param array $field_configs * An array containing matching configuration object names. */ public function __construct( $plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, ContentBlockManagerInterface $content_block_manager, array $field_configs ) { parent::__construct( $plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings, $content_block_manager ); $this->fieldConfigs = $field_configs; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container->get('plugin.manager.content_block'), $container->get('config.factory')->listAll(self::CONFIG_PREFIX) ); } /** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $element = parent::formElement($items, $delta, $element, $form, $form_state); $selected_plugin_id = $items->getEntity()->field_plugin_id->value; $selector = $this->contentBlockManager->getSelector('field_plugin_id', 'value', $element['#field_parents']); foreach ($this->contentBlockManager->getDefinitions() as $plugin_id => $plugin_definition) { $element[$plugin_id] = [ '#type' => 'select', '#title' => $element['value']['#title'], '#description' => $element['value']['#description'], '#empty_value' => 'all', '#empty_option' => t('All'), '#weight' => -1, '#states' => [ 'visible' => [ $selector => [ 'value' => $plugin_id, ], ], ], ]; if ($selected_plugin_id === $plugin_id) { $element[$plugin_id]['#default_value'] = $element['value']['#default_value']; } foreach ($plugin_definition['fields'] as $field) { if (isset($form[$field])) { // Depending on the field type the field title to filter by is in // different places. // For entity reference fields. if (isset($form[$field]['widget']['target_id']['#title'])) { $element[$plugin_id]['#options'][$field] = $form[$field]['widget']['target_id']['#title']; } // For other field types (e.g. select) elseif (isset($form[$field]['widget']['#title'])) { $element[$plugin_id]['#options'][$field] = $form[$field]['widget']['#title']; } // Otherwise we show a helpful message to the developer or QA that // they should implement an additional clause. else { $element[$plugin_id]['#options'][$field] = "-- Could not find widget title for '{$field}' in " . self::class . ' --'; } $form[$field]['#states'] = [ 'visible' => [ $selector => [ 'value' => $plugin_id, ], $this->contentBlockManager->getSelector('field_plugin_field', $plugin_id) => [ ['value' => 'all'], ['value' => $field], ], ], ]; } elseif (in_array(self::CONFIG_PREFIX . $field, $this->fieldConfigs)) { // Add the field machine name instead of the field label when the // field still not added to the form structure. The field will be // processed in the following place: // @see \Drupal\social_content_block\ContentBuilder::processBlockForm() $element[$plugin_id]['#options'][$field] = $field; } } } $element['#element_validate'][] = [get_class($this), 'validateElement']; return $element; } /** * Form validation handler for widget elements. * * @param array $element * The form element. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. */ public static function validateElement(array $element, FormStateInterface $form_state) { $value = $form_state->getValue([ 'field_plugin_field', 0, $form_state->getValue(['field_plugin_id', 0, 'value']), ]); if ($value === 'all') { $form_state->setValueForElement($element, NULL); } else { $form_state->setValueForElement($element, ['value' => $value]); } } }
php
22
0.601334
132
31.877005
187
starcoderdata
<?php namespace app\controllers; use app\models\Customer; use yii\elasticsearch\Exception; use yii\rest\ActiveController as Controller; class CustomerController extends Controller { public $modelClass = Customer::class; public function actions() { $actions = parent::actions(); unset($actions['view'], $actions['delete'],$actions['update'],$actions['index']); return $actions; } public function actionIndex() { $customers = Customer::find()->limit(100)->all(); // $customer = Customer::find()->query([ // 'bool' => [ // 'must' => [ // ['term' => ['name' => 'rest']], // ['terms' => ['email' => [' // ] // ] // ])->all(); // $customer = Customer::find()->query(['match' => ['name' => 'testRestActive']])->search(); // return $this->asJson(['customers' => $customer['hits']['hits'][0]]); return $this->asJson(['customers' => $customers]); } public function actionCreate() { $customer = new Customer(); if ($customer->load(\Yii::$app->request->post())) { $customer->insert(); return $this->asJson(['customer' => $customer]); } else { return $customer->errors; } } public function actionView($id) { $customer = new Customer(); if (\Yii::$app->request->get()) { $customer = Customer::findOne($id); return $this->asJson(['customer' => $customer]); } else { return $customer->errors; } } public function actionDelete($id) { $customer = new Customer(); try { $customer = Customer::deleteAll(['id' => $id]); return $this->asJson(['message' => 'delete']); } catch (Exception $e) { return $customer->errors; } } public function actionUpdate($id){ $customer = new Customer(); $findID = Customer::findOne($id); dd($findID); // if($customer->load(\Yii::$app->request->post())) } }
php
15
0.501379
99
25.864198
81
starcoderdata
public final void doInit(){ // called by battle terminateListeners.clear(); moving = false; speedFilter = 1.0; shouldTerminate = false; init(); }
java
6
0.592179
35
19
9
inline
def setUp(self): """Create the setting to test.""" super().setUp() self.phase = Parameter("φ") self.freq = Parameter("ν") self.d0_ = DriveChannel(Parameter("ch0")) with pulse.build(name="xp") as xp: pulse.play(Gaussian(160, 0.5, 40), self.d0_) with pulse.build(name="xp12") as xp12: pulse.shift_phase(self.phase, self.d0_) pulse.set_frequency(self.freq, self.d0_) pulse.play(Gaussian(160, 0.5, 40), self.d0_) # To make things more interesting we will use a call. with pulse.build(name="xp02") as xp02: pulse.call(xp) pulse.call(xp12) self.cals = Calibrations() self.cals.add_schedule(xp, num_qubits=1) self.cals.add_schedule(xp12, num_qubits=1) self.cals.add_schedule(xp02, num_qubits=1) self.date_time = datetime.strptime("15/09/19 10:21:35", "%d/%m/%y %H:%M:%S") self.cals.add_parameter_value(ParameterValue(1.57, self.date_time), "φ", (3,), "xp12") self.cals.add_parameter_value(ParameterValue(200, self.date_time), "ν", (3,), "xp12")
python
11
0.576923
94
37.166667
30
inline
def get_selected_layers(): """Get the selected layers Returns: list """ _app = app() group_selected_layers() selection = list(_app.ActiveDocument.ActiveLayer.Layers) _app.ExecuteAction( _app.CharIDToTypeID("undo"), None, get_com_objects().constants().psDisplayNoDialogs ) return selection
python
11
0.606648
60
18.052632
19
inline
import pytest from therandy.rules.cp_omitting_directory import match, get_new_command from therandy.types import Command @pytest.mark.parametrize('script, output', [ ('cp dir', 'cp: dor: is a directory'), ('cp dir', "cp: omitting directory 'dir'")]) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script, output', [ ('some dir', 'cp: dor: is a directory'), ('some dir', "cp: omitting directory 'dir'"), ('cp dir', '')]) def test_not_match(script, output): assert not match(Command(script, output)) def test_get_new_command(): assert get_new_command(Command('cp dir', '')) == 'cp -a dir'
python
10
0.661721
71
29.636364
22
starcoderdata
// This file has been generated by Py++. #include "boost/python.hpp" #include "generators/include/python_CEGUI.h" #include "ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556.pypp.hpp" namespace bp = boost::python; struct ConstBaseIterator_less__std_scope_vector_less__CEGUI_scope_ImageryComponent__greater__comma__CEGUI_scope_ImageryComponent__greater__wrapper : CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >, bp::wrapper< CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > > { ConstBaseIterator_less__std_scope_vector_less__CEGUI_scope_ImageryComponent__greater__comma__CEGUI_scope_ImageryComponent__greater__wrapper( ) : CEGUI::ConstBaseIterator<std::vector<CEGUI::ImageryComponent, std::allocator >, CEGUI::ImageryComponent>( ) , bp::wrapper< CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > >(){ // null constructor } virtual ::CEGUI::ImageryComponent getCurrentValue( ) const { bp::override func_getCurrentValue = this->get_override( "getCurrentValue" ); return func_getCurrentValue( ); } }; void register_ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_class(){ { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > typedef bp::class_< ConstBaseIterator_less__std_scope_vector_less__CEGUI_scope_ImageryComponent__greater__comma__CEGUI_scope_ImageryComponent__greater__wrapper, boost::noncopyable > ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer_t; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer_t ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer = ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer_t( "ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556", bp::no_init ); bp::scope ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_scope( ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer ); ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( bp::init< >("*************************************************************************\n\ No default construction available\n\ *************************************************************************\n") ); { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::getCurrentValue typedef CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > exported_class_t; typedef ::CEGUI::ImageryComponent ( exported_class_t::*getCurrentValue_function_type )( ) const; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( "getCurrentValue" , bp::pure_virtual( getCurrentValue_function_type(&::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::getCurrentValue) ) , "*!\n\ \n\ Return the value for the item at the current iterator position.\n\ *\n" ); } { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::isAtEnd typedef CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > exported_class_t; typedef bool ( exported_class_t::*isAtEnd_function_type )( ) const; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( "isAtEnd" , isAtEnd_function_type( &::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::isAtEnd ) , "*!\n\ \n\ Return whether the current iterator position is at the end of the iterators range.\n\ *\n" ); } { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::isAtStart typedef CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > exported_class_t; typedef bool ( exported_class_t::*isAtStart_function_type )( ) const; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( "isAtStart" , isAtStart_function_type( &::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::isAtStart ) , "*!\n\ \n\ Return whether the current iterator position is at the start of the iterators range.\n\ *\n" ); } ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( bp::self != bp::self ); { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::operator= typedef CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > exported_class_t; typedef ::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > & ( exported_class_t::*assign_function_type )( ::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > const & ) ; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( "assign" , assign_function_type( &::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::operator= ) , ( bp::arg("rhs") ) , bp::return_self< >() , "*!\n\ \n\ ConstBaseIterator assignment operator\n\ *\n" ); } ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( bp::self == bp::self ); { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::toEnd typedef CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > exported_class_t; typedef void ( exported_class_t::*toEnd_function_type )( ) ; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( "toEnd" , toEnd_function_type( &::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::toEnd ) , "*!\n\ \n\ Set the iterator current position to the end position.\n\ *\n" ); } { //::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::toStart typedef CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent > exported_class_t; typedef void ( exported_class_t::*toStart_function_type )( ) ; ConstBaseIterator_e6837f87c747b0388313d47a6a1e8556_exposer.def( "toStart" , toStart_function_type( &::CEGUI::ConstBaseIterator< std::vector< CEGUI::ImageryComponent >, CEGUI::ImageryComponent >::toStart ) , "*!\n\ \n\ Set the iterator current position to the start position.\n\ *\n" ); } } }
c++
24
0.635683
350
58.816
125
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ProcessController extends Controller { public function amounts() { return view('coinprocess.amounts'); } public function sendto() { return view('coinprocess.sendto'); } public function confirmation() { return view('coinprocess.confirmation'); } public function sending() { return view('coinprocess.sending'); } }
php
10
0.653333
52
17.103448
29
starcoderdata
import QuadtreeShader from './QuadtreeShader.js' import tinycolor from 'tinycolor2' import { shuffle } from '../Utils.js' /** * Quadtree shader */ export default class ASCIIQuadtreeShader extends QuadtreeShader { constructor (name) { super(name || "ASCII Quadtree") this.patterns = [ ".:+<#" ] } fontFromSize (fontSize) { return `${fontSize}px Courier` } estimateWidthOfCharacter (ctx) { return Math.floor(ctx.measureText(" ").width) } prepare (ctx, data, palette) { super.prepare(ctx, data, palette) ctx.miterLimit = 2 const frameCharacters = shuffle(this.patterns)[0].split('') frameCharacters.reverse() this.characters = frameCharacters } renderQuad(ctx, quad) { const luminance = tinycolor(quad.fill).getLuminance() const characterIndex = (this.characters.length - 1) - Math.round(luminance * (this.characters.length - 1)) const character = this.characters[characterIndex] ctx.font = this.fontFromSize(quad.h) ctx.fillStyle = quad.fill; ctx.strokeStyle = quad.fill; this.fillText(ctx, character, quad.x + .2 * quad.w, quad.y + quad.h*0.85) if (!this.shouldFill() && this.shouldStroke()) { this.strokeText(ctx, character, quad.x + .2 * quad.w, quad.y + quad.h*0.85, quad) } } fillText (ctx, character, x, y) { if (this.shouldFill()) { ctx.fillText(character, x, y) } } strokeText (ctx, character, x, y, quad) { if (!this.shouldFill()) { ctx.lineWidth = Math.max(1.5, Math.floor(quad.w/25)) } else { ctx.lineWidth = 1 } if (this.shouldStroke()) { ctx.strokeText(character, x, y) } } }
javascript
16
0.629454
110
21.77027
74
starcoderdata
<div class="row"> <form method="post" class="form-horizontal" action="<?php echo base_url().$url_submit;?>" enctype="multipart/form-data"> <div class="span10"> <div class="widget"> <div class="widget-header"> <i class="icon-list-alt"> <?php echo $_title; ?> <div class="widget-content"> <div class="control-group"> <label class="control-label" for="project_name">Project Name <div class="controls"> <input type="text" class="span3" id="project_name" name="project_name" value="<?php echo empty($result['content']['name']) ? '' : $result['content']['name']; ?>" placeholder="Project Name"> <input type="hidden" class="span3" id="project_num" name="project_num" value="<?php echo $project?>"> <input type="hidden" class="span3" id="project_id" name="project_id" value="<?php echo empty($id_project) ? '' : $id_project;?>"> <div class="control-group"> <label class="control-label" for="project_type">Project Type <div class="controls"> <input type="text" name="project_type" id="project_type" placeholder="Project Type" value="<?php echo empty($result['content']['type']) ? '' : $result['content']['type']; ?>"> <div class="control-group"> <label class="control-label" for="project_status">Status <div class="controls"> <select name="project_status" id="project_status" class="span2"> <?php if(isset($result['content']['active'])){ ?> <option value="-" selected>Select Status <option value="1" <?php echo ($result['content']['active'] == 1) ? 'selected' : ''; ?>>Active <option value="0" <?php echo ($result['content']['active'] == 0) ? 'selected' : ''; ?>>Inactive <?php } else{ ?> <option value="-" selected>Select Status <option value="1">Active <option value="0">Inactive <?php }?> <?php if(isset($images) && $images){ foreach ($images as $key => $value) { ?> <div class="control-group" id="foto_input<?php echo $key?>"> <label class="control-label" for="project_img">Image <div class="controls" id="img_area"> <input type="file" name="fotos[]" id="foto<?php echo $key?>" onchange="showImage(this,'<?php echo $key?>')"> <img src="<?php echo base_url().$value['url']?>" id="imgctr<?php echo $key?>" width="250"> <?php } } else{ ?> <div class="control-group" id="foto_input0"> <label class="control-label" for="project_img">Image <div class="controls" id="img_area"> <input type="file" name="fotos[]" id="foto0" onchange="showImage(this,0)"> <?php $key = 0;} ?> <div class="control-group"> <div class="controls"> <a class="btn btn-success" id="btn_plus"><i class="icon-plus"> <div class="control-group" id="foto_input0"> <div class="controls"> *max. size 2MB/image <div class="form-actions"> <button type="submit" class="btn btn-primary">Save <button class="btn">Cancel <script type="text/javascript"> var ctr = '<?php echo $key+1;?>'; var foto_input = '<?php echo $key;?>'; $('#btn_plus').click(function(){ $('#foto_input'+foto_input).after('<div class="control-group" id="foto_input'+ctr+'">'+ '<div class="controls" id="img_area">'+ '<input type="file" name="fotos[]" id="foto'+ctr+'" onchange="showImage(this,'+ctr+')">'+ ' ' ctr++; foto_input++; }); function showImage(elem,num){ $('#imgctr'+num).remove(); if (elem.files && elem.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#foto'+num).after('<img src="'+e.target.result+'" id="imgctr'+num+'" width="250">'); }; reader.readAsDataURL(elem.files[0]); } }
php
10
0.426442
211
47.833333
114
starcoderdata
#include<stdio.h> #include<stdlib.h> int main(void){ while(1){ char x[50][50]; char y[1000]; int h, w; scanf("%d%d",&h,&w); if(h==0) break; for(int i=0;i<h;i++) scanf("%s",x[i]); scanf("%s",y); //printf("%s\n",y); int nh=0, nw=0; int t = 0; for(int i=0;y[i]!='\0';i++){ for(int j=0;j<h;j++){ for(int k=0;k<w;k++){ if(x[j][k]==y[i]){ t += abs(nh-j)+abs(nw-k)+1; nh = j; nw = k; } } } } printf("%d\n",t); } }
c
20
0.303571
51
22.172414
29
codenet
<?php namespace App\Models; use Exception; class Money { private string $amount; private Currency $currency; public function __construct(int|string $amount, Currency $currency) { $this->currency = $currency; if (is_string($amount)) { $this->checkStringMoney($amount); $this->amount = $amount; }else { if ($amount < 1){ throw new Exception('Amount must be at least 1'); } if ($amount > 100){ $this->amount = (string) $amount/100; }else { $this->amount = (string) '0.'.$amount; } } } public function getAmount(): string { return $this->amount; } public function sameCurrencyCheck(Money $other) { if ($this->currency != $other->currency){ throw new Exception('Currency must be the same'); } } public function greaterCheck(Money $other) { if (!$this->greater($other)){ throw new Exception('First amount must be greater than second'); } } public function checkStringMoney(string $value) { if (!preg_match('/^\d+(\.\d{2})?$/', $value)) { throw new Exception('Write a real number with 2 decimal places after dot'); } if ($value == '0'){ throw new Exception('Number can\'t be 0'); } } public function equals(Money $other): bool { $this->sameCurrencyCheck($other); return bccomp($this->amount, $other->amount, 2) === 0; } public function greater(Money $other): bool { $this->sameCurrencyCheck($other); return bccomp($this->amount, $other->amount, 2) > 0; } public function add(Money $other): Money { $this->sameCurrencyCheck($other); $newValue = bcadd($this->amount, $other->amount, 2); return new Money($newValue, $this->currency); } public function subtract(Money $other): Money { $this->greaterCheck($other); $newValue = bcsub($this->amount, $other->amount, 2); return new Money($newValue, $this->currency); } public function multiply(string $number): Money { $this->checkStringMoney($number); $newValue = bcmul($this->amount, $number, 2); return new Money($newValue, $this->currency); } public function divide(string $number): Money { $this->checkStringMoney($number); $newValue = bcdiv($this->amount,$number, 2); return new Money($newValue, $this->currency); } }
php
16
0.546142
87
23.036364
110
starcoderdata
namespace OpenSkiePOS { public interface POSButtonInterface { bool Configure(); void Save( System.Xml.XmlWriter w ); void Load( System.Xml.XPath.XPathNavigator r ); bool Click( int qty ); } }
c#
11
0.653153
49
13.857143
14
starcoderdata
func TestExecScriptBefore(t *testing.T) { // With invalid script defer func() { common.BuildConfig.Build.Scripts.After = []string{} }() common.BuildConfig.Build.Scripts.Before = []string{ "invalid-script.sh", } assert.NotNil(t, ExecScriptBefore(nil)) // Happy case // Create a script and run it script := ` #!/bin/sh echo "ut" ` defer func() { os.RemoveAll("ut.sh") }() assert.Nil(t, ioutil.WriteFile("ut.sh", []byte(script), os.ModePerm)) common.BuildConfig.Build.Scripts.Before = []string{ "ut.sh", } assert.Nil(t, ExecScriptBefore(nil)) }
go
13
0.674336
70
21.64
25
inline
#include #include #include #include "string_utils.h" int string_is_empty(const char *s) { return s == NULL || *s == 0; } static char* rtrim(char *str) { if (str == NULL || *str == '\0') { return str; } char *p = str + strlen(str) - 1; while (p >= str && isspace(*p)) { *p = '\0'; --p; } return str; } static char* ltrim(char *str) { if (str == NULL || *str == '\0') { return str; } int len = 0; char *p = str; while (*p != '\0' && isspace(*p)) { ++p; ++len; } memmove(str, p, strlen(str) - len + 1); return str; } char* string_trim(char *str) { str = rtrim(str); str = ltrim(str); return str; }
c
10
0.469438
43
13.872727
55
starcoderdata
using System; namespace KFCC.Exchanges.EBinance { internal class SpotErrcode2Msg { internal static string Prase(string v) { throw new NotImplementedException(); } } }
c#
10
0.611111
48
17.083333
12
starcoderdata
#include<iostream> #include<string> using namespace std; class Node{ int data; Node* prev; Node* next; public: Node(){ data = 0; } Node(int x, Node* p, Node* n){ data = x; prev = p; next = n; } void SetPrev(Node* p){ prev = p; } void SetNext(Node* n){ next = n; } Node* GetPrev(){ return prev; } Node* GetNext(){ return next; } int GetData(){ return data; } }; class LinkedList{ Node* head; Node* tail; public: LinkedList(){ head = new Node(); tail = new Node(); head->SetNext(tail); tail->SetPrev(head); } void Insert(int x){ Node* node = new Node(x, head, head->GetNext()); node->GetNext()->SetPrev(node); node->GetPrev()->SetNext(node); } void Delete(int x){ Node* current = head->GetNext(); while(current != tail){ if(current->GetData() == x){ current->GetNext()->SetPrev(current->GetPrev()); current->GetPrev()->SetNext(current->GetNext()); delete current; return; } current = current->GetNext(); } } void DeleteFirst(){ Node* node = head->GetNext(); node->GetNext()->SetPrev(head); head->SetNext(node->GetNext()); delete node; } void DeleteLast(){ Node* node = tail->GetPrev(); tail->SetPrev(node->GetPrev()); node->GetPrev()->SetNext(tail); delete node; } Node* GetHead(){ return head; } Node* GetTail(){ return tail; } }; int main(){ LinkedList list; int n; cin >> n; string command; for(int i = 0; i < n; i++){ cin >> command; if(command == "insert"){ int x; cin >> x; list.Insert(x); }else if(command == "delete"){ int x; cin >> x; list.Delete(x); }else if(command == "deleteFirst"){ list.DeleteFirst(); }else if(command == "deleteLast"){ list.DeleteLast(); } } Node* node = list.GetHead()->GetNext(); Node* tail = list.GetTail(); while(node != tail){ if(node != list.GetHead()->GetNext()){ cout << ' '; } cout << node->GetData(); node = node->GetNext(); } cout << endl; return 0; }
c++
16
0.579238
52
14.96
125
codenet
def check(seq, elem): if elem in seq: return True else: return False def check1(seq, elem): return elem in seq
python
7
0.573248
22
12.166667
12
starcoderdata
package main import "fmt" type myString string type myThing struct { name string } func (t myThing) String() string { return t.name } func main() { printMe(1) printMe(int32(2)) printMe("a nimble string") printMe(true) printMe(myThing{" // create struct of type mything, use {} printMe(myString("my string")) // convert string to myString, use () fmt.Println(isMyString("some string")) // false fmt.Println(isMyString(myString("my string"))) // true } func isMyString(thing interface{}) bool { if _, ok := thing.(myString); ok { return true } return false } func printMe(thing interface{}) { switch t := thing.(type) { case int, int32, int64: fmt.Printf("Integer thing %T: %d\n", t, t) case string: fmt.Printf("String thing %T: %s\n", t, t) case bool: fmt.Printf("Boolean thing %T: %t\n", t, t) case fmt.Stringer: fmt.Printf("Stringer thing: %T: %s\n", t, t.String()) default: fmt.Printf("Unknown thing: %#v\n", t) } }
go
11
0.650256
69
19.744681
47
starcoderdata
fn main() { let args: Vec<String> = env::args().collect(); //println!("{:#?}", args); let mut opts = Options::new(); opts.optflag("h", "help", "print usage"); opts.optopt("c", "config", "config file", "CONFIG"); let options = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if options.opt_present("h") { usage(&args[0]); std::process::exit(0); } let config_file = match options.opt_str("c") { Some(cf) => { cf } None => { format!("{}/gpmdp_rc.yaml", env::var("HOME").unwrap()) } }; if options.free.is_empty() { println!("ERROR: invalid command line args!"); usage(&args[0]); std::process::exit(1); } let cmd = options.free; let token: String; let url: String; match get_config(&config_file) { Some(cfg) => { token = cfg[0]["token"].as_str().unwrap().to_string(); url = cfg[0]["url"].as_str().unwrap().to_string(); } None => { std::process::exit(1); } } // connect to the GPMPD websocket and call the closure match ws::connect(url, |out| { Client::new(out, &cmd, &token) }) { Ok(_) => std::process::exit(0), Err(_) => std::process::exit(1) } }
rust
18
0.485097
74
24.826923
52
inline
<?php error_reporting(0); $ip = ""; header('Content-Type: application/json; charset=utf-8'); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['X-Real-IP'])) { $ip = $_SERVER['X-Real-IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; $ip = preg_replace("/,.*/", "", $ip); # hosts are comma-separated, client is first } else { $ip = $_SERVER['REMOTE_ADDR']; } $ip = preg_replace("/^::ffff:/", "", $ip); if ($ip == "::1") { // ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this echo json_encode(['processedString' => $ip . " - localhost IPv6 access", 'rawIspInfo' => ""]); die(); } if (stripos($ip, 'fe80:') === 0) { // simplified IPv6 link-local address (should match fe80::/10) echo json_encode(['processedString' => $ip . " - link-local IPv6 access", 'rawIspInfo' => ""]); die(); } if (strpos($ip, '127.') === 0) { //anything within the 127/8 range is localhost ipv4, the ip must start with 127.0 echo json_encode(['processedString' => $ip . " - localhost IPv4 access", 'rawIspInfo' => ""]); die(); } if (strpos($ip, '10.') === 0) { // 10/8 private IPv4 echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]); die(); } if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) { // 172.16/12 private IPv4 echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]); die(); } if (strpos($ip, '192.168.') === 0) { // 192.168/16 private IPv4 echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]); die(); } if (strpos($ip, '169.254.') === 0) { // IPv4 link-local echo json_encode(['processedString' => $ip . " - link-local IPv4 access", 'rawIspInfo' => ""]); die(); } /** * Optimized algorithm from http://www.codexworld.com * * @param float $latitudeFrom * @param float $longitudeFrom * @param float $latitudeTo * @param float $longitudeTo * * @return float [km] */ function distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) { $rad = M_PI / 180; $theta = $longitudeFrom - $longitudeTo; $dist = sin($latitudeFrom * $rad) * sin($latitudeTo * $rad) + cos($latitudeFrom * $rad) * cos($latitudeTo * $rad) * cos($theta * $rad); return acos($dist) / $rad * 60 * 1.853; } function getIpInfoTokenString(){ $apikeyFile="getIP_ipInfo_apikey.php"; if(!file_exists($apikeyFile)) return ""; require $apikeyFile; if(empty($IPINFO_APIKEY)) return ""; return "?token=".$IPINFO_APIKEY; } if (isset($_GET["isp"])) { $isp = ""; $rawIspInfo=null; try { $json = file_get_contents("https://ipinfo.io/" . $ip . "/json".getIpInfoTokenString()); $details = json_decode($json, true); $rawIspInfo=$details; if (array_key_exists("org", $details)){ $isp .= $details["org"]; $isp=preg_replace("/AS\d{1,}\s/","",$isp); //Remove AS##### from ISP name, if present }else{ $isp .= "Unknown ISP"; } if (array_key_exists("country", $details)){ $isp .= ", " . $details["country"]; } $clientLoc = NULL; $serverLoc = NULL; if (array_key_exists("loc", $details)){ $clientLoc = $details["loc"]; } if (isset($_GET["distance"])) { if ($clientLoc) { $locFile="getIP_serverLocation.php"; $serverLoc=null; if(file_exists($locFile)){ require $locFile; }else{ $json = file_get_contents("https://ipinfo.io/json".getIpInfoTokenString()); $details = json_decode($json, true); if (array_key_exists("loc", $details)){ $serverLoc = $details["loc"]; } if($serverLoc){ $lf=fopen($locFile,"w"); fwrite($lf,chr(60)."?php\n"); fwrite($lf,'$serverLoc="'.addslashes($serverLoc).'";'); fwrite($lf,"\n"); fwrite($lf,"?".chr(62)); fclose($lf); } } if ($serverLoc) { try { $clientLoc = explode(",", $clientLoc); $serverLoc = explode(",", $serverLoc); $dist = distance($clientLoc[0], $clientLoc[1], $serverLoc[0], $serverLoc[1]); if ($_GET["distance"] == "mi") { $dist /= 1.609344; $dist = round($dist, -1); if ($dist < 15) $dist = "<15"; $isp .= " (" . $dist . " mi)"; }else if ($_GET["distance"] == "km") { $dist = round($dist, -1); if ($dist < 20) $dist = "<20"; $isp .= " (" . $dist . " km)"; } } catch (Exception $e) { } } } } } catch (Exception $ex) { $isp = "Unknown ISP"; } echo json_encode(['processedString' => $ip . " - " . $isp, 'rawIspInfo' => $rawIspInfo]); } else { echo json_encode(['processedString' => $ip, 'rawIspInfo' => ""]); } ?>
php
24
0.509156
139
36.041958
143
starcoderdata
package com.scloudic.jsuite.log.db.service; import com.scloudic.jsuite.log.db.mapper.OperateLogMapper; import com.scloudic.jsuite.log.db.entity.OperateLog; import com.scloudic.jsuite.log.db.service.impl.DbLogService; import com.scloudic.jsuite.log.model.LogBean; import com.scloudic.rabbitframework.core.utils.PageBean; import com.scloudic.rabbitframework.core.utils.StringUtils; import com.scloudic.rabbitframework.jbatis.mapping.RowBounds; import com.scloudic.rabbitframework.jbatis.mapping.lambda.SFunctionUtils; import com.scloudic.rabbitframework.jbatis.mapping.param.Criteria; import com.scloudic.rabbitframework.jbatis.mapping.param.Where; import com.scloudic.rabbitframework.jbatis.service.IServiceImpl; import com.scloudic.rabbitframework.core.utils.BeanUtils; import com.scloudic.rabbitframework.core.utils.UUIDUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Component("jsuiteLogService") public class DbLogServiceImpl extends IServiceImpl<OperateLogMapper, OperateLog> implements DbLogService { @Autowired private OperateLogMapper operateLogMapper; @Override public OperateLogMapper getBaseMapper() { return operateLogMapper; } @Override public int saveLog(LogBean logBean) { OperateLog operateLog = new OperateLog(); BeanUtils.copyProperties(operateLog, logBean); operateLog.setOperateLogId(UUIDUtils.getRandomUUID32()); return operateLogMapper.insertByEntity(operateLog); } @Transactional(readOnly = true) @Override public PageBean findLog(String searchKey, String operateType, String startDate, String endDate, Long pageNum, Long pageSize) { Where where = new Where(); Criteria criteria = where.createCriteria(); if (StringUtils.isNotBlank(operateType)) { criteria.andEqual(OperateLog::getOperateType, operateType); } if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) { String createTime = SFunctionUtils.getFieldName(OperateLog::getCreateTime); criteria.andGreaterThanEqual("date_format(" + createTime + ",'%Y-%m-%d')", startDate); criteria.andLessThanEqual("date_format(" + createTime + ",'%Y-%m-%d')", endDate); } if (StringUtils.isNotBlank(searchKey)) { Criteria addCriteria = where.addCreateCriteria(); addCriteria.orLike(OperateLog::getContent, "%" + searchKey + "%"); addCriteria.orLike(OperateLog::getLogRemark, "%" + searchKey + "%"); addCriteria.orLike(OperateLog::getLoginName, "%" + searchKey + "%"); } Long totalCount = operateLogMapper.selectCountByParams(where); PageBean pageBean = new PageBean pageSize, totalCount); if (totalCount.longValue() == 0) { return pageBean; } where.orderByDesc(OperateLog::getCreateTime); List operateLogs = operateLogMapper.findLogBeanByWhere(where, new RowBounds(pageBean.getStartPage(), pageBean.getPageSize())); pageBean.setDatas(operateLogs); return pageBean; } }
java
13
0.702308
98
44.64
75
starcoderdata
namespace esp_cxx { template <typename T> class DataLogger { public: virtual ~DataLogger() = default; virtual void Init() {} virtual void Log(const char* tag, T data) {} }; // Starts an asynchronous ring-buffer based data logger for a single type of // function. Useful for logging things like packet dumps off of the main // handling thread so as to avoid missing protocol deadlines. // // Usage: // void LogPacket(std::unique_ptr<PacketType> packet); // DataLogger<std::unique_ptr<PacketType>, 50, &LogPacket> logger; // ... // logger.Log(std::move(some_packet)); template <typename T, size_t size> class AsyncDataLogger : public DataLogger<T> { public: // |event_manager| is where LogFunc is run. explicit AsyncDataLogger(EventManager* event_manager, std::function<void(T)> log_func) : event_manager_(event_manager), log_func_(log_func) { PublishLog(); } virtual ~AsyncDataLogger() = default; void Log(const char* tag, T data) override { data_log_.Put(std::move(data)); } private: void PublishLog() { // Limit how many logs are sent at once so data logging cannot // completely DoS the |event_manager_|. static constexpr int kMaxLogBurst = 5; static constexpr int kLogIntervalMs = 10; for (int i = 0; i < kMaxLogBurst; ++i) { auto data = data_log_.Get(); if (!data) { break; } log_func_(std::move(data.value())); } event_manager_->RunDelayed([=]{PublishLog();}, data_log_.NumItems() == 0 ? kLogIntervalMs : 0); } // EventManager to run the LogFunc() on. EventManager* event_manager_; // Function to use on log data. std::function<void(T)> log_func_; // Ring buffer for data to log. DataBuffer<T, size> data_log_; }
c
15
0.65791
99
28.694915
59
inline
<?php class M_Ramal extends CI_Model{ function ramal(){ $this->db->order_by('id_ramal desc'); return $this->db->get('ramal'); } function tambah_data_ramal($data,$table){ $this->db->insert($table,$data); } function limit_tahun(){ $this->db->select('tahun'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function limit_ar(){ $this->db->select('ramal_ar'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function limit_ma(){ $this->db->select('ramal_ma'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function limit_arma(){ $this->db->select('ramal_arma'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function mape_ar(){ $this->db->select('mape_ar'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function mape_ma(){ $this->db->select('mape_ma'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function mape_arma(){ $this->db->select('mape_arma'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function error_ar(){ $this->db->select('error_ar'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function error_ma(){ $this->db->select('error_ma'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function error_arma(){ $this->db->select('error_arma'); $this->db->order_by('id_ramal desc'); $this->db->limit('1'); return $this->db->get('ramal'); } function update_data_ramal($where,$data,$table){ $this->db->where($where); $this->db->update($table,$data); } }
php
10
0.581903
49
21.114943
87
starcoderdata
#include // [[Rcpp::depends(RcppEigen)]] #include "typedefs.h" #include "include/helpers.hpp" #include "include/multivariate_helpers.hpp" using namespace Rcpp; using namespace std; using namespace Eigen; //**********************************************************************// // Main function //**********************************************************************// // Run a Gibbs sampler for the multivariate probit model. Note that the // parameters are not normalized // [[Rcpp::export]] Rcpp::List mv_probit_uninf_gibbs_cpp( Eigen::MatrixXi Y, Eigen::MatrixXd X, int K = 2, int n_iter = 10000, int burn_in = 5000, bool verbose = true ){ // problem info int N = X.rows(); int P = X.cols(); int M = Y.cols(); Eigen::VectorXd one_N = Eigen::VectorXd::Constant(N, 1.0); int n_samps = n_iter - burn_in; // initializing matricies to store results Eigen::MatrixXd b0_mat = Eigen::MatrixXd::Constant(n_samps, M, 1.0); Eigen::MatrixXd B_mat = Eigen::MatrixXd::Constant(n_samps, M * P, 1.0); Eigen::MatrixXd mtheta_mat = Eigen::MatrixXd::Constant(n_samps, M * K, 1.0); Eigen::VectorXd tau_vec = Eigen::VectorXd::Constant(n_samps, 1.0); Eigen::VectorXd loglik_vec = Eigen::VectorXd::Constant(n_samps, 1.0); // starting values Eigen::VectorXd b0 = Eigen::VectorXd::Constant(M, 0.0); Eigen::MatrixXd B = Eigen::MatrixXd::Constant(M, P, 0.0); Eigen::MatrixXd mtheta = Eigen::MatrixXd::Constant(M, K, 0.0); Eigen::MatrixXd mpsi = Eigen::MatrixXd::Constant(N, K, 0.0); double tau = 1.0; // probit specific Eigen::MatrixXd Z = Eigen::MatrixXd::Constant(N, M, 0.0); Eigen::MatrixXd E_hat = Eigen::MatrixXd::Constant(N, M, 0.0); int iter = 0; for(int i = 0; i < n_iter; i++) { // check interrupt and print progress Rcpp::checkUserInterrupt(); if(verbose && (i % 100 == 0)) { Rcout << "Done with Iteration " << i << " of " << n_iter << "\r"; } // Z E_hat = one_N * b0.transpose() + X * B.transpose() + mpsi * mtheta.transpose(); mv_probit_gibbs_Z(Y, E_hat, tau, N, M, Z); // mpsi E_hat = Z - one_N * b0.transpose() - X * B.transpose(); mvlm_uninf_gibbs_mpsi(E_hat, mtheta, tau, N, K, mpsi); // mtheta mvlm_uninf_gibbs_mtheta( E_hat, mpsi, tau, M, K, mtheta ); // b_0 E_hat = Z - X * B.transpose() - mpsi * mtheta.transpose(); mvlm_uninf_gibbs_b0(E_hat, tau, N, M, b0); // B E_hat = Z - one_N * b0.transpose() - mpsi * mtheta.transpose(); mvlm_uninf_gibbs_B(E_hat, X, tau, M, P, B); // storing results; need maps for B, mpsi, mtheta, mgamma, and cov_mat Eigen::Map B_vec(B.data(), B.size()); Eigen::Map theta_vec(mtheta.data(), mtheta.size()); if(i >= burn_in) { b0_mat.row(iter) = b0; B_mat.row(iter) = B_vec; mtheta_mat.row(iter) = theta_vec; iter = iter + 1; } // log likelihood //E_hat = Z - one_N * b0.transpose() - X * B.transpose() - // mpsi * mtheta.transpose(); //loglik_vec(i) = 1.0/2.0 * tau.array().log().sum() - // (D_tau * E_hat.transpose() * E_hat).trace(); } Rcpp::List retl; retl["b0_mat"] = b0_mat; retl["B_mat"] = B_mat; retl["mtheta_mat"] = mtheta_mat; retl["loglik_vec"] = loglik_vec; return retl; }
c++
14
0.575685
78
30.647619
105
starcoderdata
def test_construct_and_compare_versions(benchmark): """Benchmark constructing a Version and comparing it to a previously constructed Version.""" v = Version(3.0) def work(version): _ = version >= Version(2, 11) # noqa: F841 benchmark.pedantic(work, args=(v,), iterations=100, rounds=100)
python
10
0.681529
96
38.375
8
inline
func parseOnbuild(image string, cfg Config) ([]*parser.Node, error) { log.Entry(context.Background()).Tracef("Checking base image %s for ONBUILD triggers.", image) // Image names are case SENSITIVE img, err := RetrieveImage(image, cfg) if err != nil { return nil, fmt.Errorf("retrieving image %q: %w", image, err) } if len(img.Config.OnBuild) == 0 { return []*parser.Node{}, nil } log.Entry(context.Background()).Tracef("Found ONBUILD triggers %v in image %s", img.Config.OnBuild, image) obRes, err := parser.Parse(strings.NewReader(strings.Join(img.Config.OnBuild, "\n"))) if err != nil { return nil, err } return obRes.AST.Children, nil }
go
13
0.689291
107
29.181818
22
inline
class COption { public: COptionProto* m_proto; // Option Proto int m_type; // Option Type int m_level; // Option Level int m_value; // Option Value short m_dbValue; // Option DB Value COption(); void MakeOptionValue(COptionProto* proto, int factLevel, int num); // Make Option Type, Level use Proto void SetOptionValue(short dbValue); // Set Option Value use dbValue void ApplyOptionValue(CPC* pc, CItem* item); // Apply Option Value void GetDBValue(short dbValue); // DB value -> type : level void SetDBValue(); // type : level -> DB value static short SetDBValue(int type, int level); static void ApplyOptionValue(CPC* pc, int nType, int nValue, CItem* pItem , int nPosition = -1 ); void ApplyOptionValue(CAPet* apet, CItem* item); static void ApplyOptionValue(CAPet* apet, int nType, int nValue, CItem* pItem); static void ApplyOptionValue(CCharacter* ch, int nType, int nValue , CItem* pItem ); }
c
9
0.68905
104
32.413793
29
inline
package com.mfc.profile.dao; import java.util.HashMap; import java.util.Map; import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import com.mfc.profile.domain.User; @Repository public class ProfileRepository { protected Logger logger = LoggerFactory.getLogger(this.getClass()); private Map<String, User> users = new HashMap<String, User>(); public ProfileRepository() { IntStream.range(1, 11).forEach(item -> add(item)); } private void add(int i) { String key = "account" + i; User user = new User(key, "name" + i); users.put(key, user); } public Map<String, User> getAll() { return users; } public User get(String key) { System.out.println("====> dao.get() called"); logger.debug("====> dao.get() called"); return users.get(key); } }
java
11
0.697809
68
20.675
40
starcoderdata
func TestEnableIPv6(t *testing.T) { if !testutils.IsRunningInContainer() { defer testutils.SetupTestOSContext(t)() } tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\nnameserver 2001:4860:4860::8888\n") expectedResolvConf := []byte("search pommesfrites.fr\nnameserver 127.0.0.11\nnameserver 2001:4860:4860::8888\noptions ndots:0\n") //take a copy of resolv.conf for restoring after test completes resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf") if err != nil { t.Fatal(err) } //cleanup defer func() { if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { t.Fatal(err) } }() netOption := options.Generic{ netlabel.EnableIPv6: true, netlabel.GenericData: options.Generic{ "BridgeName": "testnetwork", }, } ipamV6ConfList := []*libnetwork.IpamConf{{PreferredPool: "fe99::/64", Gateway: "fe99::9"}} n, err := createTestNetwork("bridge", "testnetwork", netOption, nil, ipamV6ConfList) if err != nil { t.Fatal(err) } defer func() { if err := n.Delete(); err != nil { t.Fatal(err) } }() ep1, err := n.CreateEndpoint("ep1") if err != nil { t.Fatal(err) } if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { t.Fatal(err) } resolvConfPath := "/tmp/libnetwork_test/resolv.conf" defer os.Remove(resolvConfPath) sb, err := controller.NewSandbox(containerID, libnetwork.OptionResolvConfPath(resolvConfPath)) if err != nil { t.Fatal(err) } defer func() { if err := sb.Delete(); err != nil { t.Fatal(err) } }() err = ep1.Join(sb) if err != nil { t.Fatal(err) } content, err := ioutil.ReadFile(resolvConfPath) if err != nil { t.Fatal(err) } if !bytes.Equal(content, expectedResolvConf) { t.Fatalf("Expected:\n%s\nGot:\n%s", string(expectedResolvConf), string(content)) } if err != nil { t.Fatal(err) } }
go
14
0.668435
130
23.493506
77
inline
func (p *sourceParser) tryConsumeBinaryExpression(subTryExprFn tryParserFn, binaryTokenType tokenType, nodeType sourceshape.NodeType) (shared.AstNode, bool) { rightNodeBuilder := func(leftNode shared.AstNode, operatorToken lexeme) (shared.AstNode, bool) { rightNode, ok := subTryExprFn() if !ok { return nil, false } // Create the expression node representing the binary expression. exprNode := p.createNode(nodeType) exprNode.Connect(sourceshape.NodeBinaryExpressionLeftExpr, leftNode) exprNode.Connect(sourceshape.NodeBinaryExpressionRightExpr, rightNode) return exprNode, true } return p.performLeftRecursiveParsing(subTryExprFn, rightNodeBuilder, nil, binaryTokenType) }
go
11
0.797994
158
42.6875
16
inline
/** * @author github.com/luncliff ( */ #include #include using namespace coro; auto no_spawn_coroutine() -> pthread_detacher { co_await suspend_never{}; } int main(int, char*[]) { auto detacher = no_spawn_coroutine(); // we didn't created the thread. this must be the zero pthread_t tid = detacher; if (tid != pthread_t{}) return __LINE__; return EXIT_SUCCESS; }
c++
8
0.635762
58
19.590909
22
starcoderdata
# Copyright 2019 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import MishmashLiteral record_literal = "r" field_literal = "f" value_literal = "v" op_literal = "o" unknown_literal = "u" param_set = "p" def test_emptyLiteral(): mishmash_literal = MishmashLiteral.MishmashLiteral() assert mishmash_literal.isUnknown() == True assert mishmash_literal.getType() == unknown_literal assert mishmash_literal.getLiteral() == None def test_RecordType(): mishmash_literal = MishmashLiteral.MishmashLiteral(None, record_literal) assert mishmash_literal.isRecord() == True assert mishmash_literal.getType() == record_literal def test_FieldType(): mishmash_literal = MishmashLiteral.MishmashLiteral(None, field_literal) assert mishmash_literal.isField() == True assert mishmash_literal.getType() == field_literal def test_ValueType(): mishmash_literal = MishmashLiteral.MishmashLiteral(None, value_literal) assert mishmash_literal.isValue() == True assert mishmash_literal.getType() == value_literal def test_OpType(): mishmash_literal = MishmashLiteral.MishmashLiteral(None, op_literal) assert mishmash_literal.isOp() == True assert mishmash_literal.getType() == op_literal def test_UnknownType(): mishmash_literal = MishmashLiteral.MishmashLiteral(None, unknown_literal) assert mishmash_literal.isUnknown() == True assert mishmash_literal.getType() == unknown_literal mishmash_literal = MishmashLiteral.MishmashLiteral(None, unknown_literal) assert mishmash_literal.isUnknown() == True assert mishmash_literal.getType() == unknown_literal def test_boolean(): boolean_lit = MishmashLiteral.MishmashLiteral.boolean(True) assert boolean_lit.getLiteral() == True assert boolean_lit.getType() == unknown_literal def test_integer(): integer_lit = MishmashLiteral.MishmashLiteral.integer(1234) assert integer_lit.getLiteral() == 1234 assert integer_lit.getType() == unknown_literal def test_double(): double_lit = MishmashLiteral.MishmashLiteral.double(12.34) assert double_lit.getLiteral() == 12.34 assert double_lit.getType() == unknown_literal def test_string(): string_lit = MishmashLiteral.MishmashLiteral.string("asdf") assert string_lit.getLiteral() == "asdf" assert string_lit.getType() == unknown_literal def test_op_as_string_without_prefix(): string_lit = MishmashLiteral.MishmashLiteral.string("avg") assert string_lit.getLiteral() == "avg" assert string_lit.getType() == unknown_literal def test_op_as_string_with_prefix(): string_lit = MishmashLiteral.MishmashLiteral.string("__avg") assert string_lit.getLiteral() == "avg" assert string_lit.getType() == op_literal def test_null(): null_lit = MishmashLiteral.MishmashLiteral.null() assert null_lit.getLiteral() == None assert null_lit.getType() == unknown_literal #TODO test_jsonSerialize_without_param #TODO test_jsonSerialize_without_param_with_op #TODO test_jsonSerialize_with_param #TODO add test parameter with mishmashset with values #TODO add test for from json #TODO add test for prettyPrint #TODO add tests for array object resource exception
python
8
0.732623
77
27.44697
132
starcoderdata
public string[] GetNewsGroups() { /* RFC 977 3.6.1. LIST Returns a list of valid newsgroups and associated information. Each newsgroup is sent as a line of text in the following format: group last first p where <group> is the name of the newsgroup, <last> is the number of the last known article currently in that newsgroup, <first> is the number of the first article currently in the newsgroup, and <p> is either 'y' or 'n' indicating whether posting to this newsgroup is allowed ('y') or prohibited ('n'). The <first> and <last> fields will always be numeric. They may have leading zeros. If the <last> field evaluates to less than the <first> field, there are no articles currently on file in the newsgroup. Example: C: LIST S: 215 list of newsgroups follows S: net.wombats 00543 00501 y S: net.unix-wizards 10125 10011 y S: . */ if(this.IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(!this.IsConnected){ throw new InvalidOperationException("NNTP client is not connected."); } // Send LIST command WriteLine("LIST"); // Read server response string responseLine = ReadLine(); if(!responseLine.StartsWith("215")){ throw new Exception(responseLine); } List<string> newsGroups = new List<string>(); responseLine = ReadLine(); while(responseLine != "."){ newsGroups.Add(responseLine.Split(' ')[0]); responseLine = ReadLine(); } return newsGroups.ToArray(); }
c#
15
0.51592
85
36.240741
54
inline
package com.andres.elevator.entities; import java.awt.image.BufferedImage; public class Mushroom extends Prize { public Mushroom(int parentWidth, int ascensorWidth) { super(parentWidth, ascensorWidth); } private BufferedImage mSprite; @Override protected void loadSprite() { mSprite = getSpriteSheet().getSubimage(71, 43, 16, 16); } @Override protected BufferedImage getPrizeSprite() { return mSprite; } }
java
10
0.712446
57
18.304348
23
starcoderdata
package octopus.api; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import octopus.api.structures.OctopusNode; public class GraphOperations { /** * Add an edge from the node src to the node dst if it does * not already exist. * * @param src the source of the edge * @param dst the destination of the edge */ public static void addEdge(Graph graph, OctopusNode src, OctopusNode dst, String edgeType) { Iterator it = src.edges(Direction.OUT, edgeType); while(it.hasNext()){ Edge edge = it.next(); if (edge.inVertex().equals(dst)) { return; } } src.addEdge(edgeType, dst); } public static Vertex addNode(Graph graph, Map<String, String> properties) { Vertex newVertex = graph.addVertex(0); for (Entry<String, String> entrySet : properties.entrySet()) { newVertex.property(entrySet.getKey(), entrySet.getValue()); } return newVertex; } }
java
12
0.721837
91
21.192308
52
starcoderdata
// Copyright (c) Quarrel. All rights reserved. using DiscordAPI.Models; using Quarrel.ViewModels.Models.Bindables.Channels; namespace Quarrel.ViewModels.Services.Discord.Channels { /// /// Manages the all channels the client has access to. /// public interface IChannelsService { /// /// Gets the currently open channel. /// BindableChannel CurrentChannel { get; } /// /// Gets a channel by id. /// /// <param name="channelId">The id of the channel. /// <see cref="BindableChannel"/> with id <paramref name="channelId"/>, or null. BindableChannel GetChannel(string channelId); /// /// Adds or updates a channel in the channel list. /// /// <param name="channelId">The channel's id. /// <param name="channel">The <see cref="BindableChannel"/> object. void AddOrUpdateChannel(string channelId, BindableChannel channel); /// /// Removes a channel from the channel list. /// /// <param name="channelId">The channel's id void RemoveChannel(string channelId); /// /// Gets a channel's settings. /// /// <param name="channelId">The channel's id. /// <see cref="ChannelOverride"/> for the channel. ChannelOverride GetChannelSettings(string channelId); /// /// Adds or updates a channel's settings. /// /// <param name="channelId">The channel's id. /// <param name="channelOverride">The channel's new settings. void AddOrUpdateChannelSettings(string channelId, ChannelOverride channelOverride); } }
c#
8
0.624266
111
37.566038
53
starcoderdata
jQuery(document).ready(function() { jQuery('#small-menu').click(function(e) { jQuery(this).toggleClass('active'); jQuery('#nav-bar ul').toggleClass('active'); e.preventDefault(); }); });
javascript
13
0.655319
48
28.5
8
starcoderdata
package io.vertx.up.rs.hunt; import io.vertx.ext.web.RoutingContext; import io.vertx.up.atom.Envelop; import io.vertx.up.atom.agent.Event; import io.vertx.up.exception.WebException; import io.vertx.up.func.Actuator; class Responser { public static void exec(final Actuator consumer, final RoutingContext context, final Event event) { try { consumer.execute(); } catch (final WebException ex) { final Envelop envelop = Envelop.failure(ex); Answer.reply(context, envelop, event); } } }
java
12
0.615385
57
28.095238
21
starcoderdata
'use strict' const { WebClient } = require('@slack/client') const SlackPostman = require('./slack_postman') // constructor //~~~~~~~~~~~~~~~~~ test('constructor', () => { const postman = new SlackPostman({ web: 'WEB', botUser: 'BOT_USER', }) expect(postman.web).toBe('WEB') expect(postman.botUser).toBe('BOT_USER') }) // post //~~~~~~~~~~~~~~~~~ test('post', async () => { const web = new WebClient('xxx') const postMessage = jest.fn().mockReturnValue(Promise.resolve()) web.chat.postMessage = postMessage const postman = new SlackPostman({ web, botUser: { username: 'username', iconUrl: 'iconUrl', }, }) await postman.post('channel', 1234, 'hello') expect(postMessage.mock.calls.length).toBe(1) expect(postMessage.mock.calls[0][0]).toMatchObject({ channel: 'channel', text: 'hello', username: 'username', icon_url: 'iconUrl', thread_ts: 1234, reply_broadcast: false, }) })
javascript
15
0.60559
66
19.553191
47
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Reactive.Linq; using AllMyLights.Connectors.Sinks; using AllMyLights.Connectors.Sinks.Chroma; using AllMyLights.Connectors.Sinks.OpenRGB; using AllMyLights.Connectors.Sinks.Wallpaper; using AllMyLights.Connectors.Sources; using AllMyLights.Connectors.Sources.Mqtt; using AllMyLights.Connectors.Sources.OpenRGB; using AllMyLights.Extensions; using AllMyLights.Models.OpenRGB; using AllMyLights.Platforms; using MQTTnet; using MQTTnet.Extensions.ManagedClient; using NLog; using OpenRGB.NET; namespace AllMyLights.Connectors { public class ConnectorFactory { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly HttpClient HttpClient = new HttpClient(); private Configuration Configuration { get; } public ConnectorFactory(Configuration configuration) { Configuration = configuration; } private static Dictionary<string, IOpenRGBClient> OpenRGBClientRegistry { get; } = new Dictionary<string, IOpenRGBClient>(); private IOpenRGBClient GetOpenRGBClientInstance(string server, int? port) { var portOrDefault = port ?? 6742; var serverOrDefault = server ?? "127.0.0.1"; return OpenRGBClientRegistry.SetDefault($"{serverOrDefault}:{portOrDefault}", () => new OpenRGBClient( ip: serverOrDefault, port: portOrDefault, autoconnect: false )); } public ISource[] GetSources() { Logger.Info($"Configuring {Configuration.Sources.Count()} sources"); return Configuration.Sources.Select<SourceOptions, ISource>(sourceOptions => sourceOptions switch { MqttSourceOptions options => new MqttSource(options, new MqttFactory().CreateManagedMqttClient()), OpenRGBSourceOptions options => new OpenRGBSource( options, GetOpenRGBClientInstance(options.Server, options.Port), Observable.Interval(TimeSpan.FromMilliseconds(options.PollingInterval ?? 1000)) ), _ => throw new NotImplementedException($"Source for type {sourceOptions.Type} not implemented") }).ToArray(); } public ISink[] GetSinks() { Logger.Info($"Configuring {Configuration.Sinks.Count()} sinks"); return Configuration.Sinks.Select<SinkOptions, ISink>(sinkOptions => sinkOptions switch { OpenRGBSinkOptions options => new OpenRGBSink(options, GetOpenRGBClientInstance(options.Server, options.Port)), MqttSinkOptions options => new MqttSink(options, new MqttFactory().CreateManagedMqttClient()), WallpaperSinkOptions options => new WallpaperSink(options, Desktop.GetPlatformInstance()), ChromaSinkOptions options => new ChromaSink(options, new ChromaClient(HttpClient), Observable.Interval(TimeSpan.FromSeconds(2))), _ => throw new NotImplementedException($"Sinks for type {sinkOptions.Type} not implemented") }).ToArray(); } } }
c#
27
0.671651
145
41.558442
77
starcoderdata
document.write("<script type='text/javascript' src='https://cdn.bootcss.com/jquery/3.4.1/jquery.js'> document.write("<script type='text/javascript' src='https://res.wx.qq.com/open/js/jweixin-1.3.2.js'> function toWechat() { wx.miniProgram.switchTab({ url: '/pages/storage/view/view' }); }
javascript
8
0.686327
112
40.555556
9
starcoderdata
def _smoothSamples(self, counts): '''Add custom chromosome features''' # Scale mads mad_sub = self.mad.loc[counts.columns] mads = (counts - counts.median()).div(mad_sub).dropna(axis=1) # Smooth chromosomes smooth_chroms = Parallel(n_jobs=self.n_jobs, prefer="threads")(delayed(self._chromSmoothing) (chrom, mads) for chrom in self.chroms) # Aggregate results smooth_samples = pd.DataFrame(index=counts.index) for smooth_chrom in smooth_chroms: smooth_samples = pd.concat([smooth_samples, smooth_chrom], axis=1, join="inner") smooth_samples = smooth_samples.sub(smooth_samples.median(axis=1), axis=0) return smooth_samples
python
13
0.564748
100
36.954545
22
inline
namespace Autofac.Variants.Resources { using System; using System.Collections.Generic; using System.Linq; using Exceptions; using Models; using Settings; [Serializable] internal class EmbeddedResourceResolver { private readonly List embeddedResources; private readonly ISettings settings; public EmbeddedResourceResolver(ISettings settings) { this.settings = settings; var resourcesProvider = new EmbeddedResourcesProvider(settings); this.embeddedResources = resourcesProvider.GetAssembliesResources(); } public EmbeddedResource ResolveEmbeddedResource(string resourceName) { var resources = this.embeddedResources .Where(resource => resource.ResourceName.Equals(resourceName, StringComparison.OrdinalIgnoreCase)) .ToList(); if (!resources.Any()) { throw new ResourceNotFoundException(resourceName, this.settings.VariantId); } var variantResources = resources.Where(r => r.VariantName == this.settings.VariantId).ToList(); if (variantResources.Count > 1) { throw new AmbiguousResourceException(resourceName, this.settings.VariantId); } return variantResources.SingleOrDefault(); } public EmbeddedResource ResolveDefaultEmbeddedResource(string resourceName) { var defaultResources = this.embeddedResources .Where(resource => resource.AssemblyName.Equals(this.settings.DefaultVariantAssemblyName) && resource.ResourceName.Equals(resourceName, StringComparison.OrdinalIgnoreCase)) .ToList(); if (!defaultResources.Any()) { throw new ResourceNotFoundException(resourceName); } if (defaultResources.Count > 1) { throw new AmbiguousResourceException(resourceName); } return defaultResources.Single(); } } }
c#
22
0.618566
114
31.477612
67
starcoderdata
static void RunEatingSimulation() { // Set things up Person person = new Farmer(); person.Inventory.Add(new Apple()); person.Inventory.Add(new Apple()); person.Inventory.Add(new PoisonApple()); person.Inventory.Add(new Watermelon()); // Start the tasks var theTasks = new List<Task>(); // Start ShowStatus(person) and others without waiting for completion, // then hold on to the task so we can wait later theTasks.Add(ShowStatus(person)); theTasks.Add(HungerLoop(person)); theTasks.Add(EatLoop(person)); // Wait for the person to die (gruesome, I know) Task.WaitAll(theTasks.ToArray()); }
c#
11
0.559645
82
36.571429
21
inline
def calculate_winners(df, voteshare_col): """Assumes df has `ons_id` and `party` columns.""" return ( df.sort_values(voteshare_col, ascending=False) .groupby("ons_id") .head(1)[["ons_id", "party"]] .set_index("ons_id") .party )
python
16
0.495177
58
33.666667
9
inline
package com.github.seratch.jslack.api.methods.request.files.remote; import com.github.seratch.jslack.api.methods.SlackApiRequest; /** * https://api.slack.com/methods/files.remote.add */ public class FilesRemoteAddRequest implements SlackApiRequest { /** * Authentication token. Requires scope: `remote_files:write` */ private String token; /** * Creator defined GUID for the file. */ private String externalId; /** * URL of the remote file. */ private String externalUrl; /** * Title of the file being shared. */ private String title; /** * type of file */ private String filetype; /** * File containing contents that can be used to improve searchability for the remote file. */ private byte[] indexableFileContents; /** * Preview of the document via multipart/form-data. */ private byte[] previewImage; FilesRemoteAddRequest(String token, String externalId, String externalUrl, String title, String filetype, byte[] indexableFileContents, byte[] previewImage) { this.token = token; this.externalId = externalId; this.externalUrl = externalUrl; this.title = title; this.filetype = filetype; this.indexableFileContents = indexableFileContents; this.previewImage = previewImage; } public static FilesRemoteAddRequestBuilder builder() { return new FilesRemoteAddRequestBuilder(); } public String getToken() { return this.token; } public String getExternalId() { return this.externalId; } public String getExternalUrl() { return this.externalUrl; } public String getTitle() { return this.title; } public String getFiletype() { return this.filetype; } public byte[] getIndexableFileContents() { return this.indexableFileContents; } public byte[] getPreviewImage() { return this.previewImage; } public void setToken(String token) { this.token = token; } public void setExternalId(String externalId) { this.externalId = externalId; } public void setExternalUrl(String externalUrl) { this.externalUrl = externalUrl; } public void setTitle(String title) { this.title = title; } public void setFiletype(String filetype) { this.filetype = filetype; } public void setIndexableFileContents(byte[] indexableFileContents) { this.indexableFileContents = indexableFileContents; } public void setPreviewImage(byte[] previewImage) { this.previewImage = previewImage; } public static class FilesRemoteAddRequestBuilder { private String token; private String externalId; private String externalUrl; private String title; private String filetype; private byte[] indexableFileContents; private byte[] previewImage; FilesRemoteAddRequestBuilder() { } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder token(String token) { this.token = token; return this; } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder externalId(String externalId) { this.externalId = externalId; return this; } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder externalUrl(String externalUrl) { this.externalUrl = externalUrl; return this; } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder title(String title) { this.title = title; return this; } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder filetype(String filetype) { this.filetype = filetype; return this; } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder indexableFileContents(byte[] indexableFileContents) { this.indexableFileContents = indexableFileContents; return this; } public FilesRemoteAddRequest.FilesRemoteAddRequestBuilder previewImage(byte[] previewImage) { this.previewImage = previewImage; return this; } public FilesRemoteAddRequest build() { return new FilesRemoteAddRequest(token, externalId, externalUrl, title, filetype, indexableFileContents, previewImage); } public String toString() { return "FilesRemoteAddRequest.FilesRemoteAddRequestBuilder(token=" + this.token + ", externalId=" + this.externalId + ", externalUrl=" + this.externalUrl + ", title=" + this.title + ", filetype=" + this.filetype + ", indexableFileContents=" + java.util.Arrays.toString(this.indexableFileContents) + ", previewImage=" + java.util.Arrays.toString(this.previewImage) + ")"; } } }
java
23
0.65803
382
28.573099
171
starcoderdata
#ifndef ABSTRACTINTERPOLATIONOPERATOR_20210910_H #define ABSTRACTINTERPOLATIONOPERATOR_20210910_H #include "interface/BlockMatrix.h" namespace tndm { class AbstractInterpolationOperator { public: virtual ~AbstractInterpolationOperator() {} virtual unsigned max_degree() const = 0; virtual std::size_t block_size(unsigned degree) const = 0; virtual void assemble(unsigned to_degree, unsigned from_degree, BlockMatrix& matrix) = 0; }; } // namespace tndm #endif // ABSTRACTINTERPOLATIONOPERATOR_20210910_H
c
13
0.768946
93
26.05
20
starcoderdata
using RimWorld; using Verse; namespace Neko { public class TankDef : ThingDef { public override void ResolveReferences() { inspectorTabs.Remove(typeof(ITab_Pawn_Needs)); inspectorTabs.Remove(typeof(ITab_Pawn_Character)); inspectorTabs.Remove(typeof(ITab_Pawn_Training)); inspectorTabs.Remove(typeof(ITab_Pawn_Gear)); inspectorTabs.Remove(typeof(ITab_Pawn_Guest)); inspectorTabs.Remove(typeof(ITab_Pawn_Prisoner)); inspectorTabs.Remove(typeof(ITab_Pawn_Social)); base.ResolveReferences(); Log.Message("Nya! Nya! Nya!", false); } } }
c#
12
0.689769
56
27.857143
21
starcoderdata
private static JSONObject selectTablas(MongoDatabase db, String tabla) { ArrayList<String> listaInfo= new ArrayList<>(); ArrayList<String> listaFecha= new ArrayList<>(); //Recoge datos de la tabla MongoCollection<Document> table= db.getCollection(tabla); System.out.println(table.countDocuments()); //Busca y muestra todos los datos de la tabla FindIterable<Document> cur = table.find(); for (Document document : cur) { listaInfo.add(document.get("info").toString()); listaFecha.add(document.get("fecha").toString()); System.out.println(document.get("info") + " " + document.get("fecha")); } if(listaFecha.size()<11){ return jsonAdd(listaInfo,listaFecha,0,listaFecha.size()); }else{ return jsonAdd(listaInfo,listaFecha,listaFecha.size()-10,listaFecha.size()); } }
java
13
0.623377
88
45.25
20
inline
package cn.dsc.easyexcel.servie.impl; import cn.dsc.easyexcel.model.bo.CouponExcelBO; import cn.dsc.easyexcel.servie.ExcelService; import com.alibaba.excel.EasyExcelFactory; import com.alibaba.excel.ExcelReader; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.metadata.Sheet; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.*; import java.sql.SQLOutput; import java.util.List; /** * @author dingShiChen * @since 2019/8/24 */ @Slf4j @Service public class ExcelServiceImpl implements ExcelService { @Override public void readExcel(InputStream inputStream) { try { ExcelReader reader = EasyExcelFactory.getReader(inputStream, new AnalysisEventListener() { @Override public void invoke(Object o, AnalysisContext analysisContext) { log.info("当前行号:{}", analysisContext.getCurrentRowNum()); log.info("object : {}", o); //object的类型是一个String数组,内容为excel里一行的数据 } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { log.info("解析excel结束"); } }); reader.read(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void readExcelModel(InputStream inputStream) { try { List data = EasyExcelFactory.read(inputStream, new Sheet(0, 1, CouponExcelBO.class)); for (Object o : data) { log.info(o.toString()); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
java
18
0.704403
96
23.291667
72
starcoderdata
import request from '@/utils/request' // Golang后端地址 const BaseUrl = 'http://localhost:8080' // 更新或者新建 export function createOrUpdateNotice(data,token) { return request({ headers:{ "Authrication":"Bearer "+token }, url: BaseUrl + '/notice/create', method: 'post', data }) } // todo 获取所有模版的信息 export function getAllFlowTemplateInfo() { return request({ url: BaseUrl + '/flowTemplate/getAllFlowTemplateInfo', method: 'get', }) } export function getInfo(token) { return request({ headers: { 'Authrication': 'Bearer ' + token }, url: BaseUrl + '/user/getInfo', method: 'get', params: { token } }) }
javascript
11
0.630156
58
16.146341
41
starcoderdata
package housekeeping import ( "context" "fmt" "math" "runtime" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo" "gitlab.com/gitlab-org/gitaly/v14/internal/git/stats" ) const ( // looseObjectLimit is the limit of loose objects we accept both when doing incremental // repacks and when pruning objects. looseObjectLimit = 1024 ) // RepackObjectsConfig is configuration for RepackObjects. type RepackObjectsConfig struct { // FullRepack determines whether all reachable objects should be repacked into a single // packfile. This is much less efficient than doing incremental repacks, which only soak up // all loose objects into a new packfile. FullRepack bool // WriteBitmap determines whether reachability bitmaps should be written or not. There is no // reason to set this to `false`, except for legacy compatibility reasons with existing RPC // behaviour WriteBitmap bool } // RepackObjects repacks objects in the given repository and updates the commit-graph. The way // objects are repacked is determined via the RepackObjectsConfig. func RepackObjects(ctx context.Context, repo *localrepo.Repo, cfg RepackObjectsConfig) error { var options []git.Option if cfg.FullRepack { options = append(options, git.Flag{Name: "-A"}, git.Flag{Name: "--pack-kept-objects"}, git.Flag{Name: "-l"}, log2Threads(runtime.NumCPU()), ) } if err := repo.ExecAndWait(ctx, git.SubCmd{ Name: "repack", Flags: append([]git.Option{git.Flag{Name: "-d"}}, options...), }, git.WithConfig(GetRepackGitConfig(ctx, cfg.WriteBitmap)...)); err != nil { return err } if err := WriteCommitGraph(ctx, repo); err != nil { return err } stats.LogObjectsInfo(ctx, repo) return nil } // GetRepackGitConfig returns configuration suitable for Git commands which write new packfiles. func GetRepackGitConfig(ctx context.Context, bitmap bool) []git.ConfigPair { config := []git.ConfigPair{ {Key: "pack.island", Value: "r(e)fs/heads"}, {Key: "pack.island", Value: "r(e)fs/tags"}, {Key: "pack.islandCore", Value: "e"}, {Key: "repack.useDeltaIslands", Value: "true"}, } if bitmap { config = append(config, git.ConfigPair{Key: "repack.writeBitmaps", Value: "true"}) config = append(config, git.ConfigPair{Key: "pack.writeBitmapHashCache", Value: "true"}) } else { config = append(config, git.ConfigPair{Key: "repack.writeBitmaps", Value: "false"}) } return config } // log2Threads returns the log-2 number of threads based on the number of // provided CPUs. This prevents repacking operations from exhausting all // available CPUs and increasing request latency func log2Threads(numCPUs int) git.ValueFlag { n := math.Max(1, math.Floor(math.Log2(float64(numCPUs)))) return git.ValueFlag{Name: "--threads", Value: fmt.Sprint(n)} }
go
22
0.730552
96
31.883721
86
starcoderdata
from kim.utils import attr_or_key def test_attr_or_key_util(): class Foo(object): bar = 'baz' foo_dict = {'bar': 'baz'} invalid = 'str' assert attr_or_key(Foo(), 'bar') == 'baz' assert attr_or_key(Foo(), 'qux') is None assert attr_or_key(foo_dict, 'bar') == 'baz' assert attr_or_key(foo_dict, 'qux') is None assert attr_or_key(invalid, 'bar') is None def test_attr_or_key_util_dot_syntax(): class Bar(object): xyz = 'abc' class Foo(object): bar = Bar() foo_dict = {'bar': {'xyz': 'abc'}} assert attr_or_key(Foo(), 'bar.xyz') == 'abc' assert attr_or_key(Foo(), 'bar.qux') is None assert attr_or_key(foo_dict, 'bar.xyz') == 'abc' assert attr_or_key(foo_dict, 'bar.qux') is None def test_attr_or_key_util_dot_syntax_escape(): foo_dict = {"bar.xyz": "abc"} assert attr_or_key(foo_dict, "bar\\.xyz") == "abc"
python
10
0.568928
54
20.761905
42
starcoderdata
import React from 'react'; import './NavBar.css'; import { Link } from 'react-scroll'; import Timeline from '@material-ui/lab/Timeline'; import TimelineItem from '@material-ui/lab/TimelineItem'; import TimelineSeparator from '@material-ui/lab/TimelineSeparator'; import TimelineConnector from '@material-ui/lab/TimelineConnector'; import TimelineContent from '@material-ui/lab/TimelineContent'; import TimelineDot from '@material-ui/lab/TimelineDot'; export default function NavBar() { return ( <div className="navBar"> <div className="navBar__timeline"> <TimelineDot color="primary" /> <TimelineConnector /> <Link to="landingPage" activeClass="active" spy={true} smooth={true} aria-label="Link to landing page" > Home <TimelineDot /> <TimelineConnector /> <Link to="about" smooth={true} spy={true} aria-label="Link to about section" > About <TimelineDot /> <TimelineConnector /> <Link to="projectPage" smooth={true} spy={true} aria-label="Link to project section" > Projects <TimelineDot /> <Link to="contact" smooth={true} spy={true} aria-label="Link to contact section" > Contact ); }
javascript
15
0.481496
67
27.235955
89
starcoderdata
package org.wikiup.servlet.impl.document; import org.wikiup.core.impl.document.DocumentWrapper; import org.wikiup.core.inf.Document; import org.wikiup.servlet.ServletProcessorContext; import org.wikiup.servlet.impl.iterator.InterceptableDocumentIterator; import java.util.Iterator; public class InterceptableDocument extends DocumentWrapper { private ServletProcessorContext context; public InterceptableDocument(ServletProcessorContext context, Document data) { super(data); this.context = context; } @Override public Iterable getChildren() { final Iterable iterable = super.getChildren(); return new Iterable { public Iterator iterator() { return new InterceptableDocumentIterator(iterable.iterator(), context, null); } }; } @Override public Iterable getChildren(final String name) { final Iterable iterable = super.getChildren(); return new Iterable { public Iterator iterator() { return new InterceptableDocumentIterator(iterable.iterator(), context, name); } }; } }
java
13
0.681351
93
33.868421
38
starcoderdata
static private String setReadyToInstallInfoText(PackageDescription packageData, String indent, String htmlInfoText) { // String spacer = "<spacer type=horizontal size=" + indent.toString() + ">"; // System.out.println(ind); if (( packageData.isLeaf() ) || ( packageData.isAllChildrenHidden() )) { if ( ! packageData.isHidden() ) { if ( packageData.getSelectionState() == packageData.INSTALL ) { // htmlInfoText = htmlInfoText + spacer + packageData.getName() + "<br>"; htmlInfoText = htmlInfoText + indent + packageData.getName() + "<br>"; } } } if (( ! packageData.isLeaf() ) && ( ! packageData.isAllChildrenHidden() )) { if ( ! packageData.isHidden() ) { if (( packageData.getSelectionState() == packageData.INSTALL ) || ( packageData.getSelectionState() == packageData.INSTALL_SOME )) { // htmlInfoText = htmlInfoText + spacer + "<b>" + packageData.getName() + "</b>" + "<br>"; // htmlInfoText = htmlInfoText + indent + "<b>" + packageData.getName() + "</b>" + "<br>"; htmlInfoText = htmlInfoText + indent + packageData.getName() + "<br>"; } } indent = indent + ".."; for (Enumeration e = packageData.children(); e.hasMoreElements(); ) { PackageDescription child = (PackageDescription) e.nextElement(); htmlInfoText = setReadyToInstallInfoText(child, indent, htmlInfoText); } } return htmlInfoText; }
java
15
0.540299
117
51.375
32
inline
#include "core/hepch.h" #include "ResourceFont.h" Hachiko::ResourceFont::ResourceFont() : Resource(Resource::Type::FONT) {} Hachiko::ResourceFont::ResourceFont(UID id) : Resource(id, Resource::Type::FONT) {}
c++
7
0.729858
83
29.142857
7
starcoderdata
package com.example.desafiob2w.repository; import com.example.desafiob2w.model.Planeta; import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.http.ResponseEntity; import java.util.Optional; public interface PlanetaRepository extends MongoRepository<Planeta, ObjectId> { Optional findByNomeIgnoreCase(String nome); }
java
4
0.843299
80
39.416667
12
starcoderdata
/** * Copyright 2020 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * 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. */ //===================================================================================================== // NGSetupFailureIEs NGAP-PROTOCOL-IES ::= { // { ID id-Cause CRITICALITY ignore TYPE Cause PRESENCE // mandatory }| { ID id-TimeToWait CRITICALITY ignore // TYPE TimeToWait PRESENCE optional }| { ID // id-CriticalityDiagnostics CRITICALITY ignore TYPE CriticalityDiagnostics // PRESENCE optional }, // ... // } //===================================================================================================== #include #include "lte/gateway/c/core/oai/test/ngap/util_ngap_pkt.h" int encode_setup_failure_pdu( Ngap_NGAP_PDU_t* pdu, uint8_t** buffer, uint32_t* length) { asn_encode_to_new_buffer_result_t res = {NULL, {0, NULL, NULL}}; res = asn_encode_to_new_buffer( NULL, ATS_ALIGNED_CANONICAL_PER, &asn_DEF_Ngap_NGAP_PDU, pdu); *buffer = (unsigned char*) res.buffer; *length = res.result.encoded; ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_Ngap_NGAP_PDU, pdu); return (0); } /* * Failure cause and type. Return the NGAPPDU Failure */ int ngap_ng_setup_failure_stream( const Ngap_Cause_PR cause_type, const long cause_value, bstring& stream) { uint8_t* buffer_p; uint32_t length = 0; Ngap_NGAP_PDU_t pdu; Ngap_NGSetupFailure_t* out; Ngap_NGSetupFailureIEs_t* ie = NULL; Ngap_Cause_t* cause_p = NULL; memset(&pdu, 0, sizeof(pdu)); pdu.present = Ngap_NGAP_PDU_PR_unsuccessfulOutcome; pdu.choice.unsuccessfulOutcome.procedureCode = Ngap_ProcedureCode_id_NGSetup; pdu.choice.unsuccessfulOutcome.criticality = Ngap_Criticality_reject; pdu.choice.unsuccessfulOutcome.value.present = Ngap_UnsuccessfulOutcome__value_PR_NGSetupFailure; out = &pdu.choice.unsuccessfulOutcome.value.choice.NGSetupFailure; ie = (Ngap_NGSetupFailureIEs_t*) calloc(1, sizeof(Ngap_NGSetupFailureIEs_t)); ie->id = Ngap_ProtocolIE_ID_id_Cause; ie->criticality = Ngap_Criticality_ignore; ie->value.present = Ngap_NGSetupFailureIEs__value_PR_Cause; cause_p = &ie->value.choice.Cause; cause_p->present = cause_type; cause_p->choice.nas = cause_value; ASN_SEQUENCE_ADD(&out->protocolIEs, ie); if (encode_setup_failure_pdu(&pdu, &buffer_p, &length) < 0) { return (EXIT_FAILURE); } stream = blk2bstr(buffer_p, length); free(buffer_p); return (EXIT_SUCCESS); } int ngap_ng_setup_failure_pdu( const Ngap_Cause_PR cause_type, const long cause_value, Ngap_NGAP_PDU_t& encode_pdu) { Ngap_NGSetupFailure_t* out; Ngap_NGSetupFailureIEs_t* ie = NULL; Ngap_Cause_t* cause_p = NULL; encode_pdu.present = Ngap_NGAP_PDU_PR_unsuccessfulOutcome; encode_pdu.choice.unsuccessfulOutcome.procedureCode = Ngap_ProcedureCode_id_NGSetup; encode_pdu.choice.unsuccessfulOutcome.criticality = Ngap_Criticality_reject; encode_pdu.choice.unsuccessfulOutcome.value.present = Ngap_UnsuccessfulOutcome__value_PR_NGSetupFailure; out = &encode_pdu.choice.unsuccessfulOutcome.value.choice.NGSetupFailure; ie = (Ngap_NGSetupFailureIEs_t*) calloc(1, sizeof(Ngap_NGSetupFailureIEs_t)); ie->id = Ngap_ProtocolIE_ID_id_Cause; ie->criticality = Ngap_Criticality_ignore; ie->value.present = Ngap_NGSetupFailureIEs__value_PR_Cause; cause_p = &ie->value.choice.Cause; cause_p->present = cause_type; cause_p->choice.nas = cause_value; ASN_SEQUENCE_ADD(&out->protocolIEs, ie); return (EXIT_SUCCESS); } bool ng_setup_failure_decode(const_bstring const raw, Ngap_NGAP_PDU_t* pdu) { asn_dec_rval_t dec_ret; memset(pdu, 0, sizeof(Ngap_NGAP_PDU_t)); dec_ret = aper_decode( NULL, &asn_DEF_Ngap_NGAP_PDU, (void**) &pdu, bdata(raw), blength(raw), 0, 0); if (dec_ret.code != RC_OK) { return false; } return true; }
c++
11
0.657169
103
33.273438
128
starcoderdata
/* https://www.apollographql.com/blog/modularizing-your-graphql-schema-code-d7f71d5ed5f2/ Schema Builder */ const { makeExecutableSchema, gql } = require('apollo-server-express'); const { merge } = require('lodash'); // Seperate Schema Files const { Examples, ExampleResolvers } = require('./graphql-schemas/example'); const { Users, UserResolvers } = require('./graphql-schemas/users') const { Study, StudyResolvers } = require('./graphql-schemas/study') const { Questionnaire, QuestionnaireResolvers } = require('./graphql-schemas/questionnaire') const { Response, ResponseResolvers } = require('./graphql-schemas/response') const { VideoNotes, VideoNoteResolvers } = require('./graphql-schemas/videoNotes') // These empty Query an Mutations give a base to build off of for extending const Query = gql` type Query { _empty: String } `; const Mutation = gql` type Mutation { _empty: String } `; const resolvers = {}; // Build Scheme with each file const schema = makeExecutableSchema({ typeDefs: [Query, Mutation, Examples, Users, Study, Questionnaire, Response, VideoNotes], resolvers: merge(resolvers, ExampleResolvers, UserResolvers, StudyResolvers, QuestionnaireResolvers, ResponseResolvers, VideoNoteResolvers) }); // Export as module module.exports = schema;
javascript
9
0.731707
143
33.526316
38
starcoderdata
private string BuildConnectionString(string dataSource) { var builder = new SQLiteConnectionStringBuilder(); builder.Version = 3; builder.DataSource = dataSource; builder.FailIfMissing = false; // create a new file if not existing return builder.ToString(); }
c#
10
0.594828
79
37.777778
9
inline
import {on} from '@ember/object/evented'; import Component from '@ember/component'; import AdminMode from 'percy-web/lib/admin-mode'; export default Component.extend({ isAdminEnabled: false, setup: on('init', function() { this.set('isAdminEnabled', AdminMode.isAdmin()); }), actions: { toggleAdmin() { this.toggleProperty('isAdminEnabled'); if (this.get('isAdminEnabled')) { AdminMode.setAdminMode(); } else { AdminMode.clear(); } }, }, });
javascript
15
0.625247
52
21.043478
23
starcoderdata
package de.viadee.mateoorchestrator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Marcel_Flasskamp */ public class MateoInstances { private static final Logger LOGGER = LoggerFactory.getLogger(MateoInstances.class); private static final String FILENAME = "src/main/resources/mateoInstances.txt"; private static final String EMPTY_STRING = ""; private MateoInstances() { } public static boolean addMateo(URI mateoUri) throws IOException { if (!getMateos().contains(mateoUri)) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME, true))) { writer.newLine(); writer.write(mateoUri.toString()); return true; } } else { return false; } } public static boolean removeAll() throws IOException { return Files.deleteIfExists(new File(FILENAME).toPath()); } public static boolean removeMateo(URI mateoUri) throws IOException { List listLines = readFileToList(); if (listLines.contains(mateoUri.toString())) { listLines.remove(mateoUri.toString()); writeListToFile(listLines); } else { return false; } return true; } private static List readFileToList() throws IOException { List listLines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(FILENAME))) { while (reader.ready()) { String line = reader.readLine(); listLines.add(line); } } return listLines; } public static Set getMateos() { Set mateoList = new HashSet<>(); ifFileDoesntExistsGenerateIt(); try (BufferedReader reader = new BufferedReader(new FileReader(FILENAME))) { while (reader.ready()) { String line = reader.readLine(); if (!line.isBlank() && !line.startsWith("#")) mateoList.add(new URI(line)); } } catch (IOException e) { LOGGER.error("Couldn't read mateoInstances File."); } catch (URISyntaxException e) { LOGGER.error("Some lines doesn't contain a valid URI"); } return mateoList; } private static void ifFileDoesntExistsGenerateIt() { if (!new File(FILENAME).exists()) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME))) { writer.write(EMPTY_STRING); } catch (IOException e) { e.printStackTrace(); } } } private static boolean writeListToFile(List lines) throws IOException { boolean first = true; try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME))) { for (String line : lines) { if (first) { writer.write(line); first = false; } else { writer.newLine(); writer.write(line); } } } return new File(FILENAME).exists(); } }
java
16
0.581355
94
30.688073
109
starcoderdata
from pca9632.controller import Controller, REG_MODE1, REG_PWM0, REG_PWM1, REG_PWM2, REG_PWM3 import pytest @pytest.fixture def led_controller(): dev = Controller() yield dev dev.reset() dev.all_off() dev.power_off() def test_reset(led_controller): dev = led_controller dev.reset() def test_power_on(led_controller): dev = led_controller dev.power_on() assert dev._read(REG_MODE1) >> 4 & 1 == 0 def test_power_off(led_controller): dev = led_controller dev.power_off() assert dev._read(REG_MODE1) >> 4 & 1 == 1 def test_enable(led_controller): dev = led_controller for i in range(4): dev.led_enable(i) assert dev.led_enabled(i) == True def test_disable(led_controller): dev = led_controller for i in range(4): dev.led_disable(i) assert dev.led_enabled(i) == False def test_all_on(led_controller): dev = led_controller dev.all_on() assert dev._read(REG_PWM0) == 255 assert dev._read(REG_PWM1) == 255 assert dev._read(REG_PWM2) == 255 assert dev._read(REG_PWM3) == 255 def test_all_off(): dev = Controller() dev.all_off() dev.power_off() def test_full_range(led_controller): dev = led_controller for i in range(4): for v in range(256): dev.set_led(i, v) assert v == dev._read(REG_PWM0+i)
python
12
0.618375
92
21.822581
62
starcoderdata
// // ZZAboutCell.h // zuwome // // Created by angBiu on 16/9/6. // Copyright © 2016年 zz. All rights reserved. // #import #import "TTTAttributedLabel.h" /** 关于空虾 */ @interface ZZAboutCell : UITableViewCell @property (nonatomic, strong) UILabel *titleLabel; @property (nonatomic, strong) UILabel *contentLabel; @property (nonatomic, strong) UIView *lineView; @property (nonatomic, strong) TTTAttributedLabel *numberLabel; @property (nonatomic, strong) UIImageView *imgView; - (void)setIndexPath:(NSIndexPath *)indexPath; @end
c
5
0.738617
69
21.807692
26
starcoderdata
/********************************************************************** * * This source code is part of the Tree-based Network Optimizer (TORO) * * TORO Copyright (c) 2007 * and * * TORO is licences under the Common Creative License, * Attribution-NonCommercial-ShareAlike 3.0 * * You are free: * - to Share - to copy, distribute and transmit the work * - to Remix - to adapt the work * * Under the following conditions: * * - Attribution. You must attribute the work in the manner specified * by the author or licensor (but not in any way that suggests that * they endorse you or your use of the work). * * - Noncommercial. You may not use this work for commercial purposes. * * - Share Alike. If you alter, transform, or build upon this work, * you may distribute the resulting work only under the same or * similar license to this one. * * Any of the above conditions can be waived if you get permission * from the copyright holder. Nothing in this license impairs or * restricts the author's moral rights. * * TORO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. **********************************************************************/ #ifndef _TRANSFORMATION3_HXX_ #define _TRANSFORMATION3_HXX_ #include #include #include "dmatrix.hh" namespace AISNavigation { template <class T> struct Vector3 { T elems[3] ; Vector3(T x, T y, T z) {elems[0]=x; elems[1]=y; elems[2]=z;} Vector3() {elems[0]=0.; elems[1]=0.; elems[2]=0.;} Vector3(const DVector t){} // translational view inline const T& x() const {return elems[0];} inline const T& y() const {return elems[1];} inline const T& z() const {return elems[2];} inline T& x() {return elems[0];} inline T& y() {return elems[1];} inline T& z() {return elems[2];} // rotational view inline const T& roll() const {return elems[0];} inline const T& pitch() const {return elems[1];} inline const T& yaw() const {return elems[2];} inline T& roll() {return elems[0];} inline T& pitch() {return elems[1];} inline T& yaw() {return elems[2];} }; template <class T> struct Pose3 : public DVector Pose3(); Pose3(const Vector3 rot, const Vector3 trans); Pose3(const T& x, const T& y, const T& z, const T& roll, const T& pitch, const T& yaw); Pose3(const DVector v): DVector {assert(v.dim()==6);} inline operator const DVector () {return (const DVector inline operator DVector () {return *this;} inline const T& roll() const {return DVector inline const T& pitch() const {return DVector inline const T& yaw() const {return DVector inline const T& x() const {return DVector inline const T& y() const {return DVector inline const T& z() const {return DVector inline T& roll() {return DVector inline T& pitch() {return DVector inline T& yaw() {return DVector inline T& x() {return DVector inline T& y() {return DVector inline T& z() {return DVector }; /*! * A Quaternion can be used to either represent a rotational axis * and a Rotation, or, the point which will be rotated */ template <class T> struct Quaternion{ /*! * Default Constructor: w=x=y=z=0; */ Quaternion(); /*! * The Quaternion representation of the point "pose" */ Quaternion(const Vector3 pose); /*! * create a Quaternion by scalar w and the imaginery parts x,y, and z. */ Quaternion(const T _w, const T _x, const T _y, const T _z); /*! * create a rotational Quaternion, roll along x-axis, pitch along y-axis and yaw along z-axis */ Quaternion(const T _roll_x_phi, const T _pitch_y_theta, const T _yaw_z_psi); /*! * @return the conjugated version of this quaternion */ inline Quaternion conjugated() const; /*! * @return this quaternion, but normalized */ inline Quaternion normalized() const; /*! * @return the inverse of this Quaternion */ inline Quaternion inverse() const; /*construct a quaternion on the axis/angle representation*/ inline Quaternion(const Vector3 axis, const T& angle); /*! * if this Quaternion represents a point, use this function * to rotate the point along with angle * @param axis the rotational axis * @param alpha rotational angle */ inline Quaternion rotateThisAlong (const Vector3 axis, const T alpha) const; /*! * if this Quaternion represents a rotational axis + rotation, * use this function to rotate another point represented as a Quaternion p * @param p the point to be rotated by Point is represented as a Quaternion * @return rotated Point (represented as a Quaternion) */ inline Quaternion rotatePoint(const Quaternion& p) const; /*! * if this Quaternion represents a rotational axis + rotation, * use this function to rotate another point * @param p the point to be rotated by * @return rotated Point */ inline Vector3 rotatePoint(const Vector3 p) const; /*! * if this Quaternion represents a rotational axis, add a rotation of angle * along axis to the Quaternion * @param alpha rotational value * @return this Quaternion with included information about the rotation along axis */ inline Quaternion withRotation (const T alpha) const; /*! * Given rotational axis x,y,z, get the rotation along these axis encoded in this Quaternion * @return rotation along x,y,z axis encoded in Quaternion */ inline Vector3 toAngles() const; inline Vector3 axis() const; inline T angle() const; /*! * @return the norm of this Quaternion */ inline T norm() const; /*! * @return the real part (==w) of this Quaternion */ inline T re() const; /*! * @return the imaginery part (== (x,y,z)) of this Quaternion */ inline Vector3 im() const; T w,x,y,z; }; template <class T> inline Quaternion operator + (const Quaternion & left, const Quaternion right); template <class T> inline Quaternion operator - (const Quaternion & left, const Quaternion right); template <class T> inline Quaternion operator * (const Quaternion & left, const Quaternion right); template <class T> inline Quaternion operator * (const Quaternion & left, const T scalar); template <class T> inline Quaternion operator * (const T scalar, const Quaternion right); template <class T> std::ostream& operator << (std::ostream& os, const Quaternion q); template <class T> inline T innerproduct(const Quaternion left, const Quaternion right); template <class T> inline Quaternion slerp(const Quaternion from, const Quaternion to, const T lambda); template <class T> struct Transformation3{ Quaternion rotationQuaternion; Vector3 translationVector; Transformation3(){} inline static Transformation3 identity(); Transformation3 (const Vector3 trans, const Quaternion rot); Transformation3 (const Pose3 v); Transformation3 (const T& x, const T& y, const T& z, const T& roll, const T& pitch, const T& yaw); inline Vector3 translation() const; inline Quaternion rotation() const; inline Pose3 toPoseType() const; inline void setTranslation(const Vector3 t); inline void setTranslation(const T& x, const T& y, const T& z); inline void setRotation(const Vector3 r); inline void setRotation(const T& roll, const T& pitch, const T& yaw); inline void setRotation(const Quaternion q); inline Transformation3 inv() const; inline bool validRotation(const T& epsilon=0.001) const; }; template <class T> inline Vector3 operator * (const Transformation3 m, const Vector3 v); template <class T> inline Transformation3 operator * (const Transformation3 m1, const Transformation3 m2); template <class T> struct Operations3D{ typedef T BaseType; typedef Pose3 PoseType; typedef Quaternion RotationType; typedef Vector3 TranslationType; typedef Transformation3 TransformationType; typedef DMatrix CovarianceType; typedef DMatrix InformationType; typedef Transformation3 ParametersType; }; } // namespace AISNavigation /**************************** IMPLEMENTATION ****************************/ #include "transformation3.hxx" #endif
c++
15
0.625361
114
31.833333
276
starcoderdata
import { render, screen } from '@testing-library/react'; import LanguageComparatorView from './view.js'; function useTranslationMock(value) { return value; } test('Renders an empty list', () => { render( <LanguageComparatorView useTranslation={() => useTranslationMock({})} /> ); }); test('Renders an non-empty list', () => { render( <LanguageComparatorView useTranslation={() => useTranslationMock({ test: 'Test' })} /> ); });
javascript
18
0.656319
62
18.608696
23
starcoderdata
#pragma once #include namespace icarus { template<typename T> struct GasModel { explicit constexpr GasModel(T temperature = 288.15, T specificGasConstant = 287.058) : mScaleHeight(specificGasConstant * temperature / standardGravity) {} constexpr T altitude(T pressure) const { return mScaleHeight * std::log(standardPressure / pressure); } constexpr T pressure(T altitude) const { return standardPressure * std::exp(-altitude / mScaleHeight); } private: T mScaleHeight; static constexpr T standardPressure = 101325; static constexpr T standardGravity = 9.81; }; }
c++
14
0.618852
94
24.241379
29
starcoderdata
package com.augusto.pontointeligente.api.services; import com.augusto.pontointeligente.api.model.Company; import org.springframework.stereotype.Service; import java.util.Optional; @Service public interface CompanyService { Company searchByTaxNumber(String taxNumber); Company save(Company company); }
java
4
0.813889
54
21.5
16
starcoderdata
@Override public ServiceResults getItemByName( ServiceContext context, String name ) throws Exception { // just get the UUID and then getItemById such that same results are being returned in both cases // don't use uniqueIndexRepair on read only logic UUID entityId = em.getUniqueIdFromAlias( getEntityType(), name, false); if ( entityId == null ) { if (logger.isTraceEnabled()) { logger.trace("Miss on entityType: {} with name: {}", getEntityType(), name); } String msg = "Cannot find entity with name: "+name; throw new EntityNotFoundException( msg ); } return getItemById( context, entityId, false); }
java
12
0.623803
105
33.857143
21
inline
package com.metricalsky.backlogged.backend.backlog.service; import java.time.Duration; import com.metricalsky.backlogged.backend.activity.entity.TimeActivity; import com.metricalsky.backlogged.backend.activity.service.ActivityMapper; import com.metricalsky.backlogged.backend.backlog.dto.BacklogItemDto; import com.metricalsky.backlogged.backend.backlog.entity.BacklogItem; import com.metricalsky.backlogged.backend.common.service.EntityMapper; public class BacklogItemMapper implements EntityMapper<BacklogItem, BacklogItemDto> { private final ActivityMapper activityMapper = new ActivityMapper(); @Override public BacklogItem toEntity(BacklogItemDto dto) { var entity = new BacklogItem(); entity.setId(dto.getId()); entity.setName(dto.getName()); entity.setType(dto.getType()); entity.setStatus(dto.getStatus()); entity.setResolution(dto.getResolution()); entity.setDuration(dto.getDuration()); return entity; } @Override public BacklogItemDto toDto(BacklogItem entity) { var dto = new BacklogItemDto(); dto.setId(entity.getId()); dto.setName(entity.getName()); dto.setType(entity.getType()); dto.setStatus(entity.getStatus()); dto.setResolution(entity.getResolution()); dto.setDuration(entity.getDuration()); if (entity.getActivities() != null) { dto.setActivityTime(entity.getActivities().stream() .filter(TimeActivity.class::isInstance) .map(TimeActivity.class::cast) .map(TimeActivity::getDuration) .reduce(Duration::plus) .orElse(null)); } return dto; } public BacklogItemDto toDetailedDto(BacklogItem entity) { var dto = new BacklogItemDto(); dto.setId(entity.getId()); dto.setName(entity.getName()); dto.setType(entity.getType()); dto.setStatus(entity.getStatus()); dto.setResolution(entity.getResolution()); dto.setDuration(entity.getDuration()); if (entity.getActivities() != null) { dto.setActivities(entity.getActivities() .stream() .map(activityMapper::toDto) .toList()); } return dto; } public void patchEntity(BacklogItem entity, BacklogItemDto dto) { entity.setName(dto.getName()); entity.setType(dto.getType()); entity.setStatus(dto.getStatus()); entity.setResolution(dto.getResolution()); entity.setDuration(dto.getDuration()); } }
java
18
0.644662
85
36.338028
71
starcoderdata
#include #include #include #include #include #include #include #include #include template <class... Args> void atomic_print(Args&&... args) { std::stringstream ss; (ss << ... << args) << '\n'; std::cout << ss.str(); } int main() { // Example 3.1: Chains of continuations running in parallel. std::cout << "\n*** Example 3.1 *** : Chains of continuations running in parallel. Some may throw.\n"; // The first function in the chain of continuations takes one parameter and // the last function returns a double. // The output of the last continuation will be sqrt(i^2 - 2*i - 1), where is the input // to the first continuation. int iInput = 10; // Set iInput = 0 to raise an exception. auto f = Lazy::future then([](auto i){ return std::vector{i * i, -2 * i, -1}; }). then([](const auto& vec) {return std::accumulate(vec.begin(), vec.end(), 0.0);}). then([](auto x) { if (x < 0) throw std::runtime_error("f: Error: negative value detected!"); return x;}). then([](auto x){ return std::sqrt(double(x)); }). finalize(); // The first function in the chain of continuations takes two parameters and // the last function returns a vector which contains {x, x*x, ... x^n} double dValue = 2.0; // Set dValue=0 and iN = -1 to raise an exception. int iN = 10; // Negative iN means negative exponents. auto g = Lazy::future iN). then([](double x, int n) { if (x == 0 && n < 0) throw std::runtime_error("g: Error: n must be positive if x is zero!"); int iSign = (n < 0) ? -1 : 1; std::vector vec(iSign * n); double xx = x; for (auto& v : vec) { v = xx; xx = (iSign < 0) ? xx / x : xx * x; } return vec; }). then([](auto vec) { atomic_print("g: The vector has ", vec.size(), " elements."); // Simulate an operation on the vector std::this_thread::sleep_for(std::chrono::seconds(1)); return vec; }). finalize(); // Launch the threads. std::cout << "Calling f.run...\n"; auto f_run = f.run(); std::cout << "Calling g.run...\n"; auto g_run = g.run(); // Do something else while f and g are running... // Now get the results try { double dResult = f.get(f_run); std::vector vec = g.get(g_run); std::cout << "Future f returned " << dResult << "\n"; std::cout << "Future g returned {"; for (auto v : vec) std::cout << v << ", "; std::cout << "}\n"; } // If both futures throw, the first one will be caught here. // The other one will be ignored silently and the exception object // released so there will be no memory leak. catch (const std::exception& e) { std::cout << "EXCEPTION: " << e.what() <<"\n"; } }
c++
21
0.528866
121
38.329412
85
starcoderdata
#include #include #include #include //We need this for the seed of the random generator int testExtDungeonRoom[25][9]={ {1,0,1,1,0,0,0,1,1}, {2,0,1,0,1,0,0,1,1}, {3,0,1,0,1,0,0,1,1}, {4,0,1,0,1,0,0,1,1}, {5,0,0,1,1,0,0,1,1}, {6,1,1,0,0,0,0,1,1}, {6,1,1,0,0,0,0,1,1}, {8,0,1,1,0,0,0,1,1}, {9,0,1,0,1,0,0,1,1}, {10,1,0,0,1,0,0,1,1}, {11,0,0,1,0,0,0,1,1}, {12,1,0,1,0,0,0,1,1}, {13,1,1,1,0,0,0,1,1}, {14,0,1,0,1,0,0,1,1}, {15,0,0,1,1,0,0,1,1}, {16,1,1,1,0,0,0,1,1}, {17,1,1,0,1,0,0,1,1}, {18,1,0,0,1,0,0,1,1}, {19,0,1,1,0,0,0,1,1}, {20,1,0,1,1,0,0,1,1}, // {20,10,11,12,13,14,15,16,17}, {21,1,1,0,0,0,0,1,1}, {22,0,1,0,1,0,0,1,1}, {23,0,1,0,1,0,0,1,1}, {24,1,0,0,1,0,0,1,1}, {25,1,0,0,0,0,0,1,1} }; char resN = ' '; char resE = ' '; char resS = ' '; char resW = ' '; int checkExits(int i) { //int testExtDungeonRoom[25][9]; resN = ' '; resE = ' '; resS = ' '; resW = ' '; if (testExtDungeonRoom[i][1] == 1) { // printf("There is an exit to the north\n\n"); resN = ('N'); testExtDungeonRoom[i][1]=3; } if (testExtDungeonRoom[i][2] == 1) { // printf("There is an exit to the east\n\n"); resE = ('E'); testExtDungeonRoom[i][2]=3; } if (testExtDungeonRoom[i][3] == 1) { // printf("There is an exit to the south\n\n"); resS = ('S'); testExtDungeonRoom[i][3]=3; } if (testExtDungeonRoom[i][4] == 1) { // printf("There is an exit to the west\n\n"); resW = ('W'); testExtDungeonRoom[i][4]=3; } for(int j=0;j<9;j++){ printf("%d",testExtDungeonRoom[i][j]); printf(","); } //char c[4]={resN, resE, resS, resW}; return(1); } int main(int argc, char *argv[]) { srand( (unsigned)time( NULL ) ); int hit = (rand() % 80); //We generate a random number between 0 and 79 int distance = 100; int zombie = 4; int zombieHealth = 500; int deadlyBlast = 1; int decision = 10; int attack = 0; int room = 0; int i = 0; // int extDungeonRoom[25][9]; int val = 0; int testEx = 0; char exitN; char exitE; char exitS; char exitW; i = 15; room = 20; testEx = testExtDungeonRoom[i][0]; printf("testExtDungeonRoom [0][0] value = %d\n\n",testEx ); printf("You are in room %d\n\n",room ); printf("%c\n\n", 248); checkExits(i); printf("Exits: %c %c %c %c\n\n",resN, resE, resS, resW ); printf("You are %d miles away.\n", distance); distance = distance * 5; printf("You hit the Zombie and caused %d damage!\n",hit); printf("The Zombie has %d health left.\n",(zombieHealth - hit)); printf("You just have been teleported to another place. You are now %d miles away.\n", distance); printf("\nYou see %d Zombies arriving!\n", zombie); zombie = zombie - deadlyBlast; printf("You hit a Zombie hard and placed a deadly blast against his rotten skull!\nThere are %d Zombies left!\n", zombie); printf("\nEnter '0' for running away or '1' to fight:\n"); while( scanf( "%d", &decision ) == 0 ) printf("Your decision is: \n %d ", decision); { if ( decision == 0 ) { printf("You avoid the fight and run away. There are %d Zombies following you!\n", zombie); } else { printf("The Zombie has %d health left.\n",(zombieHealth)); while( zombieHealth >= 0) { hit = (rand() % 80); printf("You fight and attack the Zombie closest to you!\n"); printf("You hit the Zombie and caused %d damage!\n",hit); if ( zombieHealth - hit > 0 ) //We need to subtract the hit here! { printf("The Zombie has %d health left.\n\n",(zombieHealth - hit)); zombieHealth = zombieHealth - hit; } else { printf("\nThe Zombie is dead!\n"); break; } attack = 1; Sleep(2000); } } printf("\n\nEND OF THE PROGRAM\n\n"); return 0; } }
c
16
0.563532
122
23.785714
154
starcoderdata
package com.qiangdong.reader.controller.manage; import com.qiangdong.reader.entity.UserAgreement; import com.qiangdong.reader.request.BaseRequest; import com.qiangdong.reader.request.user_agreement.AddOrUpdateUserAgreementRequest; import com.qiangdong.reader.request.user_agreement.DeleteUserAgreementRequest; import com.qiangdong.reader.request.user_agreement.GetUserAgreementRequest; import com.qiangdong.reader.request.user_agreement.ListUserAgreementRequest; import com.qiangdong.reader.response.PageResponse; import com.qiangdong.reader.response.Response; import com.qiangdong.reader.service.IUserAgreementService; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/manage/user-agreement") public class ManageUserAgreementController { @Autowired private IUserAgreementService userAgreementService; @PostMapping("/list-user-agreement") public PageResponse listUserAgreement(@RequestBody ListUserAgreementRequest request) { return userAgreementService.listUserAgreement(request); } @PostMapping("/detail") public Response getUserAgreement(@RequestBody GetUserAgreementRequest request) { return userAgreementService.getUserAgreement(request, new UserAgreement()); } @PostMapping("/add-update") public Response addOrUpdateUserAgreement(@RequestBody @Valid AddOrUpdateUserAgreementRequest request) { return userAgreementService.addOrUpdateUserAgreement(request); } @DeleteMapping("/{userAgreementId}") public Response deleteUserAgreement(@RequestBody DeleteUserAgreementRequest request) { return userAgreementService.deleteUserAgreement(request, new UserAgreement()); } }
java
10
0.848455
119
43.326087
46
starcoderdata
int LogAccessHttp::marshal_client_req_unmapped_url_host(char *buf) { int plen = INK_MIN_ALIGN; validate_unmapped_url(); validate_unmapped_url_path(); int alen = m_client_req_unmapped_url_host_len; if (alen < 0) { alen = 0; } // calculate the the padded length only if the actual length // is not zero. We don't want the padded length to be zero // because marshal_mem should write the DEFAULT_STR to the // buffer if str is nil, and we need room for this. if (alen) { plen = round_strlen(alen + 1); // +1 for eos } if (buf) { marshal_mem(buf, m_client_req_unmapped_url_host_str, alen, plen); } return plen; }
c++
10
0.656489
69
23.296296
27
inline
var MSG = { title: "BlocklyCraft", blocks: "Blocks", linkTooltip: "Save and link to blocks.", deployTooltip: "Deploy the program defined by the blocks in the workspace.", badCode: "Program error:\n%1", timeout: "Maximum execution iterations exceeded.", trashTooltip: "Discard all blocks.", catLogic: "Logic", catLoops: "Loops", catMath: "Math", catText: "Text", catLists: "Lists", catColour: "Colour", catVariables: "Variables", catDrone: "Drone", catInventory: "Inventory", listVariable: "list", textVariable: "text", httpRequestError: "There was a problem with the request.", linkAlert: "Share your blocks with this link:\n\n%1", hashError: "Sorry, '%1' doesn't correspond with any saved program.", xmlError: "Could not load your saved file. Perhaps it was created with a different version of Blockly?", badXml: "Error parsing XML:\n%1\n\nSelect 'OK' to abandon your changes or 'Cancel' to further edit the XML." }; Blockly.Msg.DRONE = "Drone"; Blockly.Msg.MATERIALS = "Materials"; Blockly.Msg.MOUVEMENT = "Mouvement"; Blockly.Msg.RECTANGLE = "Rectangle"; Blockly.Msg.DELETE = "Delete"; Blockly.Msg.CIRCLE = "Circle"; Blockly.Msg.WIDTH = "Width"; Blockly.Msg.HEIGHT = "Height"; Blockly.Msg.LENGTH = "Length"; Blockly.Msg.RADIUS = "Radius"; Blockly.Msg.FULL = "Full"; Blockly.Msg.EMPTY = "Empty"; Blockly.Msg.INVENTORY = "Inventory"; Blockly.Msg.ITEMS_TOOLS = "Tools"; Blockly.Msg.ITEMS_FOOD = "Food"; Blockly.Msg.ITEMS_TRANSPORTATION = "Transportation"; Blockly.Msg.ITEMS_WEAPONS_ARMOR = "Weapons & Armor"; Blockly.Msg.ANIMALS = "Animals"; Blockly.Msg.MOUVEMENT_UP = "up"; Blockly.Msg.MOUVEMENT_DOWN = "down"; Blockly.Msg.MOUVEMENT_FWD = "forward"; Blockly.Msg.MOUVEMENT_BACK = "back"; Blockly.Msg.MOUVEMENT_RIGHT = "right"; Blockly.Msg.MOUVEMENT_LEFT = "left"; Blockly.Msg.MOUVEMENT_TURN_RIGHT = "turn right"; Blockly.Msg.MOUVEMENT_TURN_LEFT = "turn left"; Blockly.Msg.MOUVEMENT_BACKTOSTART = "go back to start"; Blockly.Msg.MOUVEMENT_SAVESTART = "save this start"; Blockly.Msg.DEPLOY_SUCCESS = "Perfect, now you can test your command in Minecraft"; Blockly.Msg.MISSING_NAME = "Your command doesn't have a name."; Blockly.Msg.TOOLTIP_DRONE = "Construct a Drone Object"; Blockly.Msg.TOOLTIP_MATERIALS = "Naturally generated and created material blocks."; Blockly.Msg.TOOLTIP_ANIMALS = "Spawn passive and pameable animals."; Blockly.Msg.TOOLTIP_DRONEMOVE = "Control the Drone's movement using any of the following methods."; Blockly.Msg.TOOLTIP_RECTANGLE = "'A convenience method for building things.'"; Blockly.Msg.TOOLTIP_CIRCLE = "A convenience method for building cylinders. Building begins radius blocks to the right and forward."; Blockly.Msg.TOOLTIP_DELETE = "A convenience method to delete things or areas."; Blockly.Msg.TOOLTIP_INVENTORY = "Provides functions to add items to, remove items from and check the contents of a player's inventory"; Blockly.Msg.TOOLTIP_TOOLS = "Tools are items used by the player while held to perform actions faster and more efficiently."; Blockly.Msg.TOOLTIP_FOOD = "Foods are consumable items that when eaten restore hunger points and sometimes cause status effects."; Blockly.Msg.TOOLTIP_TRANSPORTATION = "Transportation involves the methods by which players move around the world."; Blockly.Msg.TOOLTIP_WEAPONS_ARMOR = "Armor is used to reduce damage from mobs, players, lava, and explosions. Weapons are mostly used to kill mobs and players faster strategically."; Blockly.Msg.ANIMALS_NAMES = []; // init blocks array Blockly.Msg.ANIMALS_NAMES.BAT = 'Bat'; Blockly.Msg.ANIMALS_NAMES.CHICKEN = 'Chicken'; Blockly.Msg.ANIMALS_NAMES.COW = 'Cow'; Blockly.Msg.ANIMALS_NAMES.PIG = 'Pig'; Blockly.Msg.ANIMALS_NAMES.RABBIT = 'Rabbit'; Blockly.Msg.ANIMALS_NAMES.WOLF = 'Wolf'; Blockly.Msg.ANIMALS_NAMES.SHEEP = 'Sheep'; Blockly.Msg.ANIMALS_NAMES.HORSE = 'Horse'; Blockly.Msg.ANIMALS_NAMES.OCELOT = 'Ocelot'; Blockly.Msg.ITEMS_NAMES = []; // init items array //tools Blockly.Msg.ITEMS_NAMES.diamondAxe = "Diamond Axe"; Blockly.Msg.ITEMS_NAMES.diamondHoe = "Diamond Hoe"; Blockly.Msg.ITEMS_NAMES.diamondSpade = "Diamond Shovel"; Blockly.Msg.ITEMS_NAMES.diamondPickaxe = "Diamond Pickaxe"; Blockly.Msg.ITEMS_NAMES.shears = "Shears"; Blockly.Msg.ITEMS_NAMES.flintAndSteel = "Flint and Steel"; Blockly.Msg.ITEMS_NAMES.fishingRod = "Fishing Rod"; Blockly.Msg.ITEMS_NAMES.bed = "Bed"; Blockly.Msg.ITEMS_NAMES.torch = "Torch"; //food Blockly.Msg.ITEMS_NAMES.carrot = "Carrot"; Blockly.Msg.ITEMS_NAMES.potato = "Potatoe"; Blockly.Msg.ITEMS_NAMES.cocoa = "Cocoa Beans"; Blockly.Msg.ITEMS_NAMES.apple = "Apple"; Blockly.Msg.ITEMS_NAMES.melon = "Melon"; Blockly.Msg.ITEMS_NAMES.sugar = "Sugar"; Blockly.Msg.ITEMS_NAMES.milkBucket = "Milk bucket"; Blockly.Msg.ITEMS_NAMES.egg = "Egg"; Blockly.Msg.ITEMS_NAMES.wheat = "Wheat"; Blockly.Msg.ITEMS_NAMES.pumpkin = "Pumpkin"; //transportation Blockly.Msg.ITEMS_NAMES.rails = "Rail"; Blockly.Msg.ITEMS_NAMES.minecart = "Minecart"; Blockly.Msg.ITEMS_NAMES.poweredRail = "Rail (Powered)"; Blockly.Msg.ITEMS_NAMES.redstoneTorchOn = "Redstone Torch (active)"; //weapons & armor Blockly.Msg.ITEMS_NAMES.bow = "Bow"; Blockly.Msg.ITEMS_NAMES.arrow = "Arrow"; Blockly.Msg.ITEMS_NAMES.diamondBoots = "Diamond Boots"; Blockly.Msg.ITEMS_NAMES.diamondChestplate = "Diamond Chestplate"; Blockly.Msg.ITEMS_NAMES.diamondHelmet = "Diamond Helmet"; Blockly.Msg.ITEMS_NAMES.diamondLeggings = "Diamond Leggings"; Blockly.Msg.ITEMS_NAMES.tnt = "tnt"; Blockly.Msg.OBJNAMES = []; // init blocks array Blockly.Msg.OBJNAMES[0] = "air"; Blockly.Msg.OBJNAMES[1] = "stone"; Blockly.Msg.OBJNAMES[2] = "grass"; Blockly.Msg.OBJNAMES[3] = "dirt"; Blockly.Msg.OBJNAMES[4] = "cobblestone"; Blockly.Msg.OBJNAMES[5] = "oak"; Blockly.Msg.OBJNAMES[6] = "sapling oak"; Blockly.Msg.OBJNAMES[7] = "bedrock"; Blockly.Msg.OBJNAMES[8] = "water"; Blockly.Msg.OBJNAMES[9] = "water still"; Blockly.Msg.OBJNAMES[10] = "lava"; Blockly.Msg.OBJNAMES[11] = "lava still"; Blockly.Msg.OBJNAMES[12] = "sand"; Blockly.Msg.OBJNAMES[13] = "gravel"; Blockly.Msg.OBJNAMES[14] = "gold ore"; Blockly.Msg.OBJNAMES[15] = "iron ore"; Blockly.Msg.OBJNAMES[16] = "coal ore"; Blockly.Msg.OBJNAMES[17] = "wood"; Blockly.Msg.OBJNAMES[18] = "leaves"; Blockly.Msg.OBJNAMES[19] = "sponge"; Blockly.Msg.OBJNAMES[20] = "glass"; Blockly.Msg.OBJNAMES[21] = "lapis lazuli ore"; Blockly.Msg.OBJNAMES[22] = "lapis lazuli block"; Blockly.Msg.OBJNAMES[23] = "dispenser"; Blockly.Msg.OBJNAMES[24] = "sandstone"; Blockly.Msg.OBJNAMES[25] = "note"; Blockly.Msg.OBJNAMES[26] = "bed"; Blockly.Msg.OBJNAMES[27] = "powered rail"; Blockly.Msg.OBJNAMES[28] = "detector rail"; Blockly.Msg.OBJNAMES[29] = "sticky piston"; Blockly.Msg.OBJNAMES[30] = "cobweb"; Blockly.Msg.OBJNAMES[31] = "grass tall"; Blockly.Msg.OBJNAMES[32] = "dead bush"; Blockly.Msg.OBJNAMES[33] = "piston"; Blockly.Msg.OBJNAMES[34] = "piston extn"; Blockly.Msg.OBJNAMES[35] = "wool white"; Blockly.Msg.OBJNAMES[37] = "dandelion"; Blockly.Msg.OBJNAMES[37] = "flower yellow"; Blockly.Msg.OBJNAMES[38] = "rose"; Blockly.Msg.OBJNAMES[38] = "flower red"; Blockly.Msg.OBJNAMES[39] = "mushroom brown"; Blockly.Msg.OBJNAMES[40] = "mushroom red"; Blockly.Msg.OBJNAMES[41] = "gold"; Blockly.Msg.OBJNAMES[42] = "iron"; Blockly.Msg.OBJNAMES[43] = "double slab stone"; Blockly.Msg.OBJNAMES[44] = "slab stone"; Blockly.Msg.OBJNAMES[45] = "brick red"; Blockly.Msg.OBJNAMES[46] = "tnt"; Blockly.Msg.OBJNAMES[47] = "bookshelf"; Blockly.Msg.OBJNAMES[48] = "moss stone"; Blockly.Msg.OBJNAMES[49] = "obsidian"; Blockly.Msg.OBJNAMES[50] = "torch"; Blockly.Msg.OBJNAMES[51] = "fire"; Blockly.Msg.OBJNAMES[52] = "monster spawner"; Blockly.Msg.OBJNAMES[53] = "stairs oak"; Blockly.Msg.OBJNAMES[67] = "stairs cobblestone"; Blockly.Msg.OBJNAMES[54] = "chest"; Blockly.Msg.OBJNAMES[55] = "redstone wire"; Blockly.Msg.OBJNAMES[56] = "diamond ore"; Blockly.Msg.OBJNAMES[57] = "diamond"; Blockly.Msg.OBJNAMES[58] = "crafting table"; Blockly.Msg.OBJNAMES[59] = "wheat seeds"; Blockly.Msg.OBJNAMES[60] = "farmland"; Blockly.Msg.OBJNAMES[61] = "furnace"; Blockly.Msg.OBJNAMES[62] = "furnace burning"; Blockly.Msg.OBJNAMES[63] = "sign post"; Blockly.Msg.OBJNAMES[64] = "door wood"; Blockly.Msg.OBJNAMES[65] = "ladder"; Blockly.Msg.OBJNAMES[66] = "rail"; Blockly.Msg.OBJNAMES[68] = "sign"; Blockly.Msg.OBJNAMES[69] = "lever"; Blockly.Msg.OBJNAMES[70] = "pressure plate stone"; Blockly.Msg.OBJNAMES[71] = "door iron"; Blockly.Msg.OBJNAMES[72] = "pressure plate wood"; Blockly.Msg.OBJNAMES[73] = "redstone ore"; Blockly.Msg.OBJNAMES[74] = "redstone ore glowing"; Blockly.Msg.OBJNAMES[75] = "torch redstone"; Blockly.Msg.OBJNAMES[76] = "torch redstone active"; Blockly.Msg.OBJNAMES[77] = "stone button"; Blockly.Msg.OBJNAMES[78] = "slab snow"; Blockly.Msg.OBJNAMES[79] = "ice"; Blockly.Msg.OBJNAMES[80] = "snow"; Blockly.Msg.OBJNAMES[81] = "cactus"; Blockly.Msg.OBJNAMES[82] = "clay"; Blockly.Msg.OBJNAMES[83] = "sugar cane"; Blockly.Msg.OBJNAMES[84] = "jukebox"; Blockly.Msg.OBJNAMES[85] = "fence"; Blockly.Msg.OBJNAMES[86] = "pumpkin"; Blockly.Msg.OBJNAMES[87] = "netherrack"; Blockly.Msg.OBJNAMES[88] = "soulsand"; Blockly.Msg.OBJNAMES[89] = "glowstone"; Blockly.Msg.OBJNAMES[90] = "netherportal"; Blockly.Msg.OBJNAMES[91] = "jackolantern"; Blockly.Msg.OBJNAMES[92] = "cake"; Blockly.Msg.OBJNAMES[93] = "redstone repeater"; Blockly.Msg.OBJNAMES[94] = "redstone repeater active"; Blockly.Msg.OBJNAMES[95] = "stained glass white"; Blockly.Msg.OBJNAMES[96] = "trapdoor"; Blockly.Msg.OBJNAMES[97] = "monster egg"; Blockly.Msg.OBJNAMES[98] = "brick stone"; Blockly.Msg.OBJNAMES[99] = "mushroom brown huge"; Blockly.Msg.OBJNAMES[100] = "mushroom red huge"; Blockly.Msg.OBJNAMES[101] = "iron bars"; Blockly.Msg.OBJNAMES[102] = "glass pane"; Blockly.Msg.OBJNAMES[103] = "melon"; Blockly.Msg.OBJNAMES[104] = "pumpkin stem"; Blockly.Msg.OBJNAMES[105] = "melon stem"; Blockly.Msg.OBJNAMES[106] = "vines"; Blockly.Msg.OBJNAMES[107] = "fence gate"; Blockly.Msg.OBJNAMES[110] = "mycelium"; Blockly.Msg.OBJNAMES[111] = "lily pad"; Blockly.Msg.OBJNAMES[112] = "nether"; Blockly.Msg.OBJNAMES[113] = "nether fence"; Blockly.Msg.OBJNAMES[115] = "netherwart"; Blockly.Msg.OBJNAMES[116] = "table enchantment"; Blockly.Msg.OBJNAMES[117] = "brewing stand"; Blockly.Msg.OBJNAMES[118] = "cauldron"; Blockly.Msg.OBJNAMES[119] = "endportal"; Blockly.Msg.OBJNAMES[120] = "endportal frame"; Blockly.Msg.OBJNAMES[121] = "endstone"; Blockly.Msg.OBJNAMES[122] = "dragon egg"; Blockly.Msg.OBJNAMES[123] = "redstone lamp"; Blockly.Msg.OBJNAMES[124] = "redstone lamp active"; Blockly.Msg.OBJNAMES[126] = "slab oak"; Blockly.Msg.OBJNAMES[127] = "cocoa"; Blockly.Msg.OBJNAMES[129] = "emerald ore"; Blockly.Msg.OBJNAMES[130] = "enderchest"; Blockly.Msg.OBJNAMES[131] = "tripwire hook"; Blockly.Msg.OBJNAMES[132] = "tripwire"; Blockly.Msg.OBJNAMES[133] = "emerald"; Blockly.Msg.OBJNAMES[137] = "command"; Blockly.Msg.OBJNAMES[138] = "beacon"; Blockly.Msg.OBJNAMES[139] = "cobblestone wall"; Blockly.Msg.OBJNAMES[140] = "flowerpot"; Blockly.Msg.OBJNAMES[141] = "carrots"; Blockly.Msg.OBJNAMES[142] = "potatoes"; Blockly.Msg.OBJNAMES[143] = "button wood"; Blockly.Msg.OBJNAMES[144] = "mobhead"; Blockly.Msg.OBJNAMES[145] = "anvil"; Blockly.Msg.OBJNAMES[146] = "chest trapped"; Blockly.Msg.OBJNAMES[147] = "pressure plate weighted light"; Blockly.Msg.OBJNAMES[148] = "pressure plate weighted heavy"; Blockly.Msg.OBJNAMES[149] = "redstone comparator"; Blockly.Msg.OBJNAMES[150] = "redstone comparator active"; Blockly.Msg.OBJNAMES[151] = "daylight sensor"; Blockly.Msg.OBJNAMES[152] = "redstone"; Blockly.Msg.OBJNAMES[153] = "netherquartzore"; Blockly.Msg.OBJNAMES[154] = "hopper"; Blockly.Msg.OBJNAMES[155] = "quartz"; Blockly.Msg.OBJNAMES[157] = "rail activator"; Blockly.Msg.OBJNAMES[158] = "dropper"; Blockly.Msg.OBJNAMES[159] = "stained clay white"; Blockly.Msg.OBJNAMES[161] = "acacia leaves"; Blockly.Msg.OBJNAMES[162] = "acacia wood"; Blockly.Msg.OBJNAMES[170] = "hay"; Blockly.Msg.OBJNAMES[171] = "carpet white"; Blockly.Msg.OBJNAMES[172] = "hardened clay"; Blockly.Msg.OBJNAMES[173] = "coal block"; Blockly.Msg.OBJNAMES[174] = "packed ice"; Blockly.Msg.OBJNAMES[175] = "double plant";
javascript
6
0.728862
182
41.594406
286
starcoderdata
import os import sys from bs4 import BeautifulSoup from urllib.parse import quote from urllib.request import Request, urlopen, urlretrieve def get_script_data(data_dir): r = "https://imsdb.com" all_scripts = "https://imsdb.com/all-scripts.html" req = Request(all_scripts) html_page = urlopen(req) soup = BeautifulSoup(html_page, 'html.parser') movie_links = [] for link in soup.findAll('a'): l = quote(link.get('href')) if "Script" in l: movie_links.append(r+l) movie_links = movie_links[5:] # first 5 are from little sidebar recommenation thing (will repeat) movie_count = 0 error_count = 0 scripts = [] for movie_link in movie_links: movie_count += 1 req = Request(movie_link) html_page = urlopen(req) soup = BeautifulSoup(html_page, 'html.parser') script_links = [] for link in soup.findAll('a'): l = link.get('href') if l is not None and "scripts" in l and "all-scripts" not in l: script_links.append(r+l) if len(script_links) == 0: continue script_link = script_links[0] name = script_link.split("/")[-1] try: # urlretrieve(script_link, os.path.join(data_dir, name)) req = Request(script_link) html = urlopen(req) soup = BeautifulSoup(html, "html.parser") pre = str(soup.find("pre")) # seems like the pre flag almost always has the script if len(pre) < 10000: print(f"Link failed: {script_link}") error_count += 1 print(f"{error_count}/{movie_count} links failed") with open(os.path.join(data_dir, name), "w+") as f: f.write(pre) except: print(f"Link failed: {script_link}") error_count += 1 print(f"{error_count}/{movie_count} links failed") if __name__ == "__main__": if len(sys.argv) == 2: get_script_data(sys.argv[1]) else: print("Usage: python get_html.py data_dir")
python
16
0.622327
99
28.953125
64
starcoderdata
package com.touwolf.mailchimp.api.lists; import com.touwolf.mailchimp.MailchimpException; import com.touwolf.mailchimp.data.MailchimpResponse; import com.touwolf.mailchimp.impl.MailchimpBuilder; import com.touwolf.mailchimp.impl.MailchimpUtils; import com.touwolf.mailchimp.model.list.abusereport.ListsAbuseReportsReadRequest; import com.touwolf.mailchimp.model.list.abusereport.ListsAbuseReportsReadResponse; import com.touwolf.mailchimp.model.list.abusereport.ListsAbuseReportsResponse; import org.apache.commons.lang.StringUtils; import org.bridje.ioc.Component; /** * Manage abuse complaints for a specific list. An abuse complaint occurs when your recipient reports an email as spam in their mail program. */ @Component public class ListsAbuseReports { private MailchimpBuilder builder; public ListsAbuseReports builder(MailchimpBuilder builder) { this.builder = builder; return this; } /** * Get all abuse reports for a specific list. * * @param listId The unique id for the list. * @param request Query string parameters * @throws MailchimpException */ public MailchimpResponse read(String listId, ListsAbuseReportsReadRequest request) throws MailchimpException { if (StringUtils.isBlank(listId)) { throw new MailchimpException("The field list_id is required"); } String url = "/lists/" + listId + "/abuse-reports"; url = MailchimpUtils.formatQueryString(url, "fields", request.getFields()); url = MailchimpUtils.formatQueryString(url, "exclude_fields", request.getExcludeFields()); url = MailchimpUtils.formatQueryString(url, "count", request.getCount()); url = MailchimpUtils.formatQueryString(url, "offset", request.getOffset()); return builder.get(url, ListsAbuseReportsReadResponse.class); } /** * Get details about a specific abuse report. * * @param listId The unique id for the list. * @param reportId The id for the abuse report. * @param request Query string parameters * @throws MailchimpException */ public MailchimpResponse read(String listId, String reportId, ListsAbuseReportsReadRequest request) throws MailchimpException { if (StringUtils.isBlank(listId)) { throw new MailchimpException("The field list_id is required"); } if (StringUtils.isBlank(listId)) { throw new MailchimpException("The field report_id is required"); } String url = "/lists/" + listId + "/abuse-reports/" + reportId; url = MailchimpUtils.formatQueryString(url, "fields", request.getFields()); url = MailchimpUtils.formatQueryString(url, "exclude_fields", request.getExcludeFields()); url = MailchimpUtils.formatQueryString(url, "count", request.getCount()); url = MailchimpUtils.formatQueryString(url, "offset", request.getOffset()); return builder.get(url, ListsAbuseReportsResponse.class); } }
java
11
0.717547
158
40.432432
74
starcoderdata
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons whether in the United States or abroad requires # an export license or other authorization. # # Contractor Name: # Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II Master Rights File ("Master Rights File.pdf") for # further licensing information. ## # # Name: # LtgThread.py # GFS1-NHD:A6837.0000-SCRIPT;11 # # Status: # DELIVERED # # History: # Revision 11 (DELIVERED) # Created: 06-JUL-2005 18:16:39 TROJAN # spr 6548 # # Revision 10 (DELIVERED) # Created: 07-MAY-2005 11:35:15 OBERFIEL # Added Item Header Block # # Revision 9 (DELIVERED) # Created: 28-APR-2005 19:30:43 TROJAN # spr 6816 # # Revision 8 (DELIVERED) # Created: 18-APR-2005 17:32:03 OBERFIEL # Changes to support gamin # # Revision 7 (DELIVERED) # Created: 11-MAR-2005 15:55:31 TROJAN # spr 6717 # # Revision 6 (DELIVERED) # Created: 15-FEB-2005 13:47:37 TROJAN # spr 6650 # # Revision 5 (APPROVED) # Created: 21-OCT-2004 19:27:19 TROJAN # spr 6417 # # Revision 4 (APPROVED) # Created: 30-SEP-2004 20:22:10 TROJAN # stdr 873 # # Revision 3 (APPROVED) # Created: 01-JUL-2004 14:59:39 OBERFIEL # Update # # Revision 2 (DELIVERED) # Created: 09-JAN-2004 15:27:50 PCMS # Updating for code cleanup # # Revision 1 (REVIEW) # Created: 08-JAN-2004 21:31:17 PCMS # Initial version # # Change Document History: # 1: # Change Document: GFS1-NHD_SPR_6548 # Action Date: 09-AUG-2005 14:09:33 # Relationship Type: In Response to # Status: CLOSED # Title: AvnFPS: Data acquistion change in OB6 # # # LtgThread.py # acesses lightning data # Author: SAIC/MDL, November 2003 # last update: 05/29/05 ## # This is a base file that is not intended to be overridden. ## import logging, math, os, Queue, re, time import Numeric import Scientific.IO.NetCDF import Avn, AvnParser _Pattern = re.compile(r'[0-9]{8}_[0-9]{4}') _Logger = logging.getLogger(__name__) def _old(fname): try: tms = time.strptime(fname[:13], '%Y%m%d_%H%M') except ValueError: return True return time.mktime(tms) < time.time() - 8000.0 ############################################################################### class Server(object): WaitTime = 60.0 # time between reads (seconds) def __init__(self, inqueue, outqueue, info): self.inqueue = inqueue self.outqueue = outqueue self.name = info['name'] self.datapath = info['source'] self.distance = float(info['distance']) self.age = int(info['age'])*60 self.lastStrikeNum = 0 def __getSites(self): ids = AvnParser.getAllSiteIds() dlat = math.degrees(self.distance/3959.0) self.sitelist = [] self.sitedata = {} for ident in ids['taf']: info = AvnParser.getTafSiteCfg(ident) if info is None: continue lat = float(info['geography']['lat']) lon = float(info['geography']['lon']) dlon = dlat/math.cos(math.radians(lat)) d = {'id': ident, 'lat': (lat-dlat, lat+dlat) , \ 'lon': (lon-dlon, lon+dlon)} self.sitelist.append(d) self.sitedata[ident] = [] # list of lightnings if not self.sitelist: raise SystemExit def __matchSite(self, lat, lon): def _match(s): slat, slon = s['lat'], s['lon'] return slat[0] < lat < slat[1] and slon[0] < lon < slon[1] return [s['id'] for s in self.sitelist if _match(s)] def __readNetCDF(self, path): changed = {} # a set indicating new data for a site now = time.time() try: fh = Scientific.IO.NetCDF.NetCDFFile(path) _Logger.info('Processing file %s', path) cutoff = now - self.age # remove data older that self.age for id in self.sitedata: d = self.sitedata[id] k = 0 for k in range(len(d)): if d[k] >= cutoff: break if k > 0: self.sitedata[id] = d[k:] changed[id] = 0 timevar = fh.variables['time'] lastStrikeNum = len(timevar) for n in range(self.lastStrikeNum, lastStrikeNum): if timevar[n] < cutoff: continue lat = fh.variables['lat'][n] lon = fh.variables['lon'][n] idlist = self.__matchSite(lat, lon) for id in idlist: self.sitedata[id].append(timevar[n]) changed[id] = 0 fh.close() self.lastStrikeNum = lastStrikeNum except IOError: # bad or nonexistent file _Logger.error('Error accessing %s', path) for ident in self.sitedata: if ident not in changed: continue path = os.path.join('data', 'ltg', ident) data = '\n'.join([str(t) for t in self.sitedata[ident]]) file(path, 'w').write(data) self.outqueue.put(Avn.Bunch(src=self.name, ident=ident)) def paths(self): return [self.datapath] def run(self): self.__getSites() while True: lasttime = time.time() flist = [] # optimization while True: try: code, fname, direct = self.inqueue.get(True, 6) if code == 0: # end thread _Logger.info('Got exit request') raise SystemExit if _Pattern.match(fname) and (direct, fname) not in flist: flist.append((direct, fname)) except Queue.Empty: pass if time.time() > lasttime + self.WaitTime: break try: for direct, fname in flist: if not _old(fname): self.__readNetCDF(os.path.join(direct, fname)) except Exception: _Logger.exception('Unexpected error') break
python
19
0.513615
106
32.593458
214
starcoderdata
#include #include #include #include #include #include #include #include #include #include namespace Onyx { AudioSource::AudioSource() { alGenSources(1, &m_id); } AudioSource::AudioSource(const std::string& path) { alGenSources(1, &m_id); setFile(path); } AudioSource::~AudioSource() { alDeleteSources(1, &m_id); } void AudioSource::update(float dt) { auto transform = object->getTransform(); alSourcefv(m_id, AL_POSITION, &transform->translation.x); auto camera = Game::getInstance()->getScene()->getCamera(); alListenerfv(AL_POSITION, &camera->transform.translation.x); } void AudioSource::setFile(const std::string& path) { m_buffer = AssetManager::getInstance()->getAudio(path); alSourcei(m_id, AL_BUFFER, m_buffer->m_id); } void AudioSource::setBuffer(const std::shared_ptr buffer) { m_buffer = buffer; alSourcei(m_id, AL_BUFFER, m_buffer->m_id); } void AudioSource::play() const { alSourcePlay(m_id); } void AudioSource::pause() const { alSourcePause(m_id); } void AudioSource::stop() const { alSourceStop(m_id); } void AudioSource::rewind() const { alSourceRewind(m_id); } }
c++
13
0.69247
71
18.216216
74
starcoderdata