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
#ifndef __revere_ut_utils_h #define __revere_ut_utils_h #include #include "r_fakey/r_fake_camera.h" std::shared_ptr _create_fc(int port); std::shared_ptr _create_fc(int port, const std::string& username, const std::string& password); #endif
c
8
0.711921
119
26.454545
11
starcoderdata
/** * @Author: Caven * @Date: 2021-04-27 13:04:50 */ class Widget { constructor() { this._viewer = undefined this._ready = false this._wrapper = undefined this._enabled = false } set enabled(enabled) { this._enabled = enabled this._enableHook && this._enableHook() } get enabled() { return this._enabled } /** * mount content * @private */ _mountContent() {} /** * binds event * @private */ _bindEvent() {} /** * Unbinds event * @private */ _unbindEvent() {} /** * When enable modifies the hook executed, the subclass copies it as required * @private */ _enableHook() { !this._ready && this._mountContent() if (this._enabled) { !this._wrapper.parentNode && this._viewer.container.appendChild(this._wrapper) this._bindEvent() } else { this._unbindEvent() this._wrapper.parentNode && this._viewer.container.removeChild(this._wrapper) } } /** * Updating the Widget location requires subclass overrides * @param windowCoord * @private */ _updateWindowCoord(windowCoord) {} /** * Setting widget content * @param content * @returns {Widget} */ setContent(content) { if (content && typeof content === 'string') { this._wrapper.innerHTML = content } else if (content && content instanceof Element) { while (this._wrapper.hasChildNodes()) { this._wrapper.removeChild(this._wrapper.firstChild) } this._wrapper.appendChild(content) } return this } /** * hide widget */ hide() { this._wrapper && (this._wrapper.style.cssText = ` visibility:hidden; `) } /** * * @param viewer * @returns {Widget} */ addTo(viewer) { return this } } export default Widget
javascript
16
0.578575
79
17.029412
102
starcoderdata
@Override protected List<Version> toValues(ComplexValueForeignKey complexValueFk, List<Row> rawValues) throws IOException { List<Version> versions = super.toValues(complexValueFk, rawValues); // order versions newest to oldest Collections.sort(versions); return versions; }
java
7
0.666667
73
27.083333
12
inline
<?php use common\models\goods\Goods; use common\models\goods\GoodsAttribute; use kartik\select2\Select2; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $model Goods */ $goodsRefs = ArrayHelper::index($model->goodsAttValueRefs, 'attribute_value_id', 'attribute_id');; foreach($goodsRefs as &$ref){ $ref = array_keys($ref); } ?> <div class="goods-att-box"> <?php $form = ActiveForm::begin(['id' => 'goods-attr-form']);?> <?php foreach ($model->goodsModel->goodsAttributes as $att): ?> <div class="att-item-box"> <label class="att-label"><?= ($att->is_required ? "*" : '') . $att->name ?> <div class="att-value-box"> <?php $attName = "attrs[$att->id][]"; $attValues = ArrayHelper::map($att->goodsAttributeValues, 'id', 'value'); $attValue = isset($goodsRefs[$att->id]) ? $goodsRefs[$att->id] : null; switch ($att->input_type) { case GoodsAttribute::TYPE_SINGLE_SELECT: echo Select2::widget([ 'name' => $attName, 'value' => $attValue, 'data' => $attValues, ]); break; case GoodsAttribute::TYPE_MULTPLE_SELECT: echo Html::checkboxList($attName, $attValue, $attValues); break; case GoodsAttribute::TYPE_SINGLE_INPUT: echo Html::textInput($attName, '', ['maxlength' => $att->value_length, 'class' => 'form-control']); break; case GoodsAttribute::TYPE_MULTPLE_INPUT: echo Html::textarea($attName, '', ['maxlength' => $att->value_length, 'class' => 'form-control']); break; } ?> <div class="clean-padding"><div class="help-block"> <?php endforeach; ?> <?php ActiveForm::end(); ?> /** * 保存属性 */ function saveAttribute() { $.ajax({ type: "POST", url: 'save-attribute?goods_id=<?= $model->id ?>', data: $('#goods-attr-form').serialize(), success: function (r, textStatus) { if (r.code != '0') { console.log(r); $.notify({message: '保存属性失败!\n' + r.msg}, {type: 'danger'}); }else{ $.notify({message: '保存属性成功!'}, {type: 'success'}); } }, error: function (e) { $.notify({message: '保存属性失败!'}, {type: 'danger'}); } }); }
php
14
0.463472
123
38.263158
76
starcoderdata
package tk.mamong_us.objects; import com.siinus.simpleGrafix.gfx.ImageTile; import tk.mamong_us.Main; import tk.mamong_us.core.ProgramObject; public abstract class GameObject implements ProgramObject { protected Main program; protected int id; protected float speedX,speedY; protected int width, height; protected int ox, oy; protected int x=0, y=0; protected ImageTile spriteSheet; /** * Creates a new Game object. * * @param program The associated program * @param width The width of the bounding box * @param height The height of the bounding box * @param ox The offset of the bounding box to the right * @param oy The offset of the bounding box to down */ public GameObject(Main program, ImageTile spriteSheet, int width, int height, int ox, int oy) { this.program = program; this.spriteSheet = spriteSheet; this.width = width; this.height = height; this.ox = ox; this.oy = oy; } public GameObject(Main program, int id, int width, int height, int ox, int oy) { this.program = program; this.id = id; this.width = width; this.height = height; this.ox = ox; this.oy = oy; } public void setY(int y) { this.y = y; } public void setX(int x) { this.x = x; } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public void setSpeedX(float speedX) { this.speedX = speedX; } public void setSpeedY(float speedY) { this.speedY = speedY; } public float getSpeedY() { return speedY; } public float getSpeedX() { return speedX; } public ImageTile getSpriteSheet() { return spriteSheet; } public int offX() { return (int) ((program.getWindow().getWidth()/(program.getWindow().getScale()*2))-program.getCamera().getX()); } public int offY() { return (int) ((program.getWindow().getHeight()/(program.getWindow().getScale()*2))-program.getCamera().getY()); } }
java
16
0.597327
119
23.944444
90
starcoderdata
<?php namespace Akamai\Tests\Http; use \Akamai\Http\AkamaiHeader; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use PHPUnit\Framework\TestCase; class AkamaiHeaderTest extends TestCase { /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiTrueCacheKey */ public function testCallingGetAkamaiTrueCacheKeyWithAnAkamaiHostReturnsACacheKeyString() { $trueCacheKey = '/L/localhost/'; $mock = new MockHandler([ new Response(200, ['X-True-Cache-Key' => $trueCacheKey]) ]); $handler = HandlerStack::create($mock); $result = AkamaiHeader::getAkamaiTrueCacheKey('http://localhost', ['handler' => $handler]); $request = $mock->getLastRequest(); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('Akamai-X-Get-True-Cache-Key', $request->getHeaderLine('Pragma')); $this->assertEquals($trueCacheKey, $result); } /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiTrueCacheKey */ public function testCallingGetAkamaiTrueCacheKeyWithANonAkamaiHostReturnsAnEmptyString() { $mock = new MockHandler([ new Response(200) ]); $handler = HandlerStack::create($mock); $result = AkamaiHeader::getAkamaiTrueCacheKey('http://localhost', ['handler' => $handler]); $request = $mock->getLastRequest(); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('Akamai-X-Get-True-Cache-Key', $request->getHeaderLine('Pragma')); $this->assertEquals('', $result); } /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiTrueCacheKey * @expectedException \GuzzleHttp\Exception\RequestException * @expectedExceptionMessage [curl] 6: Could not resolve host: localhost [url] http://localhost */ public function testCallingGetAkamaiTrueCacheKeyWithANonexistentDomainThrowsAnException() { $exception = "[curl] 6: Could not resolve host: localhost [url] http://localhost"; $mock = new MockHandler([ new RequestException($exception, new Request('GET', 'http://localhost')) ]); $handler = HandlerStack::create($mock); AkamaiHeader::getAkamaiTrueCacheKey('http://localhost', ['handler' => $handler]); } /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiHeader * @expectedException \InvalidArgumentException * @expectedExceptionMessage Akamai\Http\AkamaiHeader::getAkamaiHeader: Expected $url to be a string. */ public function testCallingGetAkamaiHeaderWithAnInvalidUrlThrowsAnException() { AkamaiHeader::getAkamaiHeader(null, 'True-Cache-key'); } /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiHeader * @expectedException \InvalidArgumentException * @expectedExceptionMessage Akamai\Http\AkamaiHeader::getAkamaiHeader: Expected $parameter to be a string. */ public function testCallingGetAkamaiHeaderWithAnInvalidParameterThrowsAnException() { AkamaiHeader::getAkamaiHeader('http://localhost', null); } /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiHeader * @expectedException \InvalidArgumentException * @expectedExceptionMessage Akamai\Http\AkamaiHeader::getAkamaiHeader: Expected $options to be an array. */ public function testCallingGetAkamaiHeaderWithInvalidOptionsThrowsAnException() { AkamaiHeader::getAkamaiHeader('http://localhost', 'True-Cache-Key', null); } /** * @covers \Akamai\Http\AkamaiHeader::getAkamaiHeader */ public function testCallingGetAkamaiHeaderWithValidParmeters() { $trueCacheKey = '/L/localhost/'; $mock = new MockHandler([ new Response(200, ['X-True-Cache-Key' => $trueCacheKey]) ]); $handler = HandlerStack::create($mock); $result = AkamaiHeader::getAkamaiHeader('http://localhost', 'True-Cache-Key', ['handler' => $handler]); $request = $mock->getLastRequest(); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('Akamai-X-Get-True-Cache-Key', $request->getHeaderLine('Pragma')); $this->assertEquals($trueCacheKey, $result); } }
php
19
0.673493
111
38.509091
110
starcoderdata
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Intent apolloThemeIntent = new Intent(BuildConfig.APPLICATION_ID + ".THEMES"); apolloThemeIntent.addCategory(CATEGORY_DEFAULT); mTheme = new ThemeUtils(requireContext()); // get all compatible themes PackageManager mPackageManager = requireActivity().getPackageManager(); List<ResolveInfo> mThemes = mPackageManager.queryIntentActivities(apolloThemeIntent, 0); // Default theme String defName = getString(R.string.app_name); String defPack = BuildConfig.APPLICATION_ID; Drawable defPrev = ResourcesCompat.getDrawable(getResources(), R.drawable.theme_preview, null); ThemeHolder defTheme = new ThemeHolder(defPack, defName, defPrev); mAdapter.add(defTheme); for (int i = 0; i < mThemes.size(); i++) { try { Drawable prev = null; String tPackage = mThemes.get(i).activityInfo.packageName; Resources mThemeResources = mPackageManager.getResourcesForApplication(tPackage); String name = mThemes.get(i).loadLabel(mPackageManager).toString(); // get preview int previewId = mThemeResources.getIdentifier(THEME_PREVIEW, "drawable", tPackage); if (previewId > 0) { prev = ResourcesCompat.getDrawable(mThemeResources, previewId, null); } // add to adapter ThemeHolder holder = new ThemeHolder(tPackage, name, prev); mAdapter.add(holder); } catch (Exception e) { e.printStackTrace(); } } }
java
13
0.621187
103
44.1
40
inline
from django.shortcuts import render # Create your views here. from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.exceptions import NotFound from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from favorited.models import Favorite from favorited.serializers import FavoriteDetailSerializer class FavoritesViewSet(viewsets.ModelViewSet): queryset = Favorite.objects.all() serializer_class = FavoriteDetailSerializer permission_classes = [] tags = ["favorited"]
python
8
0.818043
58
30.142857
21
starcoderdata
/* * Copyright 2002-2011, The TenDRA Project. * Copyright 1997, United Kingdom Secretary of State for Defence. * * See doc/copyright/ for the full copyright terms. */ #define _POSIX_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include "utility.h" #include "environ.h" #include "flags.h" #include "hash.h" #include "options.h" struct hash { struct hash *next; const char *value; const char *name; const char *file; int line_num; enum hash_precedence precedence; }; /* * Reconcile the table of user-defined env options. At present this function * just makes sure that non-tccenv(5) variables declared by the user were used * in the env files. If not, it's likely a subtle bug or typo, and a warning * is issued if the version -v switch is used. */ void reconcile_envopts(const struct hash *h) { const struct hash *n; /* * If the global env table is NULL, no -Y args succeeded, or none were * given. */ /* TODO: this needs reworking, now; it cannot happen if (environ_hashtable == NULL) error(ERR_FATAL, "failed to load any environment files"); */ if (!verbose) { return; } for (n = h; n != NULL; n = n->next) { /* * Additional error checking for those platforms supporting stat() for * variables which represent paths on the filesystem. */ if (0 == strncmp(n->name, "PREFIX_", 7) && strlen(n->value) > 0) { struct stat sb; if (stat(n->value, &sb) == -1) { error(ERR_SERIOUS, "%s: %s", n->value, strerror(errno)); return; } if (!S_ISDIR(sb.st_mode)) { error(ERR_SERIOUS, "%s expected to be a directory"); return; } } } } /* * PRINT OUT AN ENVIRONMENT */ void dump_env(const struct hash *h) { const struct hash *n; assert(h != NULL); IGNORE printf("Environment dump:\n"); for (n = h; n != NULL; n = n->next) { IGNORE printf("\t%-18.*s = %s\n", (int) strcspn(n->name, "$"), n->name, n->value); } } /* * SET A VARIABLE */ void envvar_set(struct hash **h, const char *name, const char *value, enum hash_order order, enum hash_precedence precedence) { struct hash *n; char sep; assert(h != NULL); assert(name != NULL); assert(value != NULL); for (n = *h; n != NULL; n = n->next) { if (streq(name, n->name)) { break; } } /* Case 1. Node was not found; push */ if (n == NULL) { n = xmalloc(sizeof *n); n->name = xstrdup(name); n->value = xstrdup(value); n->file = NULL; /* TODO */ n->line_num = -1; /* TODO */ n->precedence = precedence; n->next = *h; *h = n; return; } assert(n->value != NULL); /* Decline to replace if we're lower precedence than the existing value */ if (order == HASH_ASSIGN && precedence < n->precedence) { return; } n->precedence = precedence; sep = strstr(name, "PATH") ? ':' : ' '; /* Case 2. Update with a value */ switch (order) { case HASH_ASSIGN: n->value = xstrdup(value); break; case HASH_APPEND: n->value = string_append(n->value, value, sep); break; case HASH_PREPEND: n->value = string_append(value, n->value, sep); break; default: error(ERR_FATAL, "Attempt to update hash with invalid order %d\n", (int) order); } } /* * GET A VARIABLE * * Lookup value for tccenv(5) variables. * * This function performs all error handling; it will return a valid char *, * or fail. */ const char * envvar_get(struct hash *h, const char *name) { struct hash *n; for (n = h; n != NULL; n = n->next) { if (streq(name, n->name)) { assert(n->value != NULL); return n->value; } } return NULL; }
c
14
0.623947
78
18.387755
196
starcoderdata
void AssetWallet::deleteImports(const vector<BinaryData>& addrVec) { ReentrantLock lock(this); for (auto& scrAddr : addrVec) { int importIndex = INT32_MAX; try { //if import index does not exist or isnt negative, continue //only imports use a negative derivation index importIndex = getAssetIndexForAddr(scrAddr); if (importIndex > 0 || importIndex == INT32_MAX) continue; } catch (...) { continue; } auto assetIter = assets_.find(importIndex); if (assetIter == assets_.end()) continue; auto assetPtr = assetIter->second; //remove from wallet's maps assets_.erase(importIndex); addresses_.erase(importIndex); //erase from file deleteAssetEntry(assetPtr); } }
c++
11
0.594465
68
23.470588
34
inline
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.websvc.core.dev.wizard; import org.netbeans.api.project.ProjectUtils; import org.netbeans.api.project.Sources; import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule; import org.netbeans.modules.websvc.api.support.LogUtils; import org.netbeans.modules.websvc.core.JaxWsUtils; import org.netbeans.modules.websvc.core.ProjectInfo; import java.io.IOException; import java.util.Collections; import java.util.NoSuchElementException; import java.util.Set; import javax.swing.JComponent; import org.netbeans.api.project.Project; import org.netbeans.api.project.SourceGroup; import org.netbeans.modules.websvc.core.CreatorProvider; import org.netbeans.modules.websvc.core.HandlerCreator; import org.netbeans.modules.websvc.core.WSStackUtils; import org.netbeans.spi.java.project.support.ui.templates.JavaTemplates; import org.netbeans.spi.project.ui.templates.support.Templates; import org.openide.WizardDescriptor; import javax.swing.event.ChangeListener; import org.netbeans.modules.j2ee.common.ProjectUtil; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.netbeans.modules.websvc.api.support.SourceGroups; public class LogicalHandlerWizard implements WizardDescriptor.InstantiatingIterator { public int currentPanel = 0; private WizardDescriptor.Panel [] wizardPanels; private WizardDescriptor.Panel firstPanel; //special case: use Java Chooser private WizardDescriptor wiz; private Project project; public static final String JAVAC_CLASSPATH = "javac.classpath"; //NOI18N public static LogicalHandlerWizard create() { return new LogicalHandlerWizard(); } private static final String [] HANDLER_STEPS = new String [] { NbBundle.getMessage(LogicalHandlerWizard.class, "LBL_SpecifyLogicalHandlerInfo") //NOI18N }; public void initialize(WizardDescriptor wizard) { wiz = wizard; project = Templates.getProject(wiz); SourceGroup[] sourceGroups = SourceGroups.getJavaSourceGroups(project); //create the Java Project chooser // firstPanel = JavaTemplates.createPackageChooser(project, sourceGroups, new BottomPanel()); if (sourceGroups.length == 0) { SourceGroup[] genericSourceGroups = ProjectUtils.getSources(project).getSourceGroups(Sources.TYPE_GENERIC); firstPanel = new FinishableProxyWizardPanel(Templates.createSimpleTargetChooser(project, genericSourceGroups, new BottomPanel()), sourceGroups, false); } else firstPanel = new FinishableProxyWizardPanel(JavaTemplates.createPackageChooser(project, sourceGroups, new BottomPanel(), true)); JComponent c = (JComponent) firstPanel.getComponent(); Utils.changeLabelInComponent(c, NbBundle.getMessage(LogicalHandlerWizard.class, "LBL_JavaTargetChooserPanelGUI_ClassName_Label"), //NOI18N NbBundle.getMessage(LogicalHandlerWizard.class, "LBL_LogicalHandler_Name") ); //NOI18N c.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, //NOI18N HANDLER_STEPS); c.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, //NOI18N 0); c.getAccessibleContext().setAccessibleDescription (HANDLER_STEPS[0]); wizardPanels = new WizardDescriptor.Panel[] {firstPanel}; } public void uninitialize(WizardDescriptor wizard) { } public Set instantiate() throws IOException { //new WebServiceCreator(project, wiz).createLogicalHandler(); HandlerCreator creator = CreatorProvider.getHandlerCreator(project, wiz); if (creator!=null) { creator.createLogicalHandler(); // logging usage of wizard Object[] params = new Object[5]; String creatorClassName = creator.getClass().getName(); params[0] = creatorClassName.contains("jaxrpc") ? LogUtils.WS_STACK_JAXRPC : LogUtils.WS_STACK_JAXWS; //NOI18N params[1] = project.getClass().getName(); J2eeModule j2eeModule = JaxWsUtils.getJ2eeModule(project); params[2] = j2eeModule == null ? "J2SE" : j2eeModule.getModuleVersion()+"("+JaxWsUtils.getModuleType(project)+")"; //NOI18N params[3] = "LOGICAL HANDLER"; //NOI18N LogUtils.logWsWizard(params); } return Collections.EMPTY_SET; } public WizardDescriptor.Panel current() { return wizardPanels[currentPanel]; } public boolean hasNext() { return currentPanel < wizardPanels.length -1; } public boolean hasPrevious() { return currentPanel > 0; } public String name() { return NbBundle.getMessage(LogicalHandlerWizard.class, "LBL_Create_LogicalHandler_Title"); //NOI18N } public void nextPanel() { if(!hasNext()){ throw new NoSuchElementException(); } currentPanel++; } public void previousPanel() { if(!hasPrevious()){ throw new NoSuchElementException(); } currentPanel--; } public void addChangeListener(javax.swing.event.ChangeListener l) { } public void removeChangeListener(ChangeListener l) { } protected int getCurrentPanelIndex() { return currentPanel; } /** Dummy implementation of WizardDescriptor.Panel required in order to provide Help Button */ private class BottomPanel implements WizardDescriptor.Panel { public void storeSettings(WizardDescriptor settings) { } public void readSettings(WizardDescriptor settings) { } public java.awt.Component getComponent() { return new javax.swing.JPanel(); } public void addChangeListener(ChangeListener l) { } public void removeChangeListener(ChangeListener l) { } public boolean isValid() { ProjectInfo creator = new ProjectInfo(project); int projectType = creator.getProjectType(); //test for conditions in JSE if (projectType == ProjectInfo.JSE_PROJECT_TYPE) { return MessageHandlerWizard.isValidInJavaProject(project, wiz); } /* if (projectType == ProjectInfo.JSE_PROJECT_TYPE && Util.isSourceLevel16orHigher(project)) return true; if (projectType == ProjectInfo.JSE_PROJECT_TYPE && Util.getSourceLevel(project).equals("1.5")) { //NOI18N //test JAX-WS library if (!PlatformUtil.hasJAXWSLibrary(project)) { wiz.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(BottomPanel.class, "LBL_LogicalHandlerWarning")); // NOI18N return false; } else return true; } */ if (ProjectUtil.isJavaEE5orHigher(project) && (projectType == ProjectInfo.WEB_PROJECT_TYPE || projectType == ProjectInfo.CAR_PROJECT_TYPE || projectType == ProjectInfo.EJB_PROJECT_TYPE)) { //NOI18N return true; } //if platform is Tomcat, source level must be jdk 1.5 and jaxws library must be in classpath WSStackUtils wsStackUtils = new WSStackUtils(project); if(!ProjectUtil.isJavaEE5orHigher(project) && projectType == ProjectInfo.WEB_PROJECT_TYPE && !wsStackUtils.isJsr109Supported() && !wsStackUtils.isJsr109OldSupported() ){ if (!wsStackUtils.hasJAXWSLibrary()) { //must have jaxws library wiz.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(BottomPanel.class, "LBL_LogicalHandlerWarning")); // NOI18N return false; } else return true; } wiz.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(BottomPanel.class, "LBL_LogicalHandlerWarning")); // NOI18N return false; } public HelpCtx getHelp() { return new HelpCtx(LogicalHandlerWizard.class); } } }
java
17
0.662925
163
40.758929
224
starcoderdata
from abc import ABC, abstractmethod from typing import Optional, List, Union class Arg(ABC): """Определяет один аргумент команды""" BOT_ARG_TYPE: str def __init__( self, name: str, description: str, *, default: Optional[Union[str, int]] = None, example: Optional[str] = None, options: Optional[List[Union[str, int]]] = None, allowed: Optional[List[Union[str, int]]] = None, allow_options=False, ): """ :param name: имя аргумента. Оно станет атрибутом экземпляра команды. :param description: описание аргумента. :param default: значение по-умолчанию :param example: пример значений. Подставляется в описание аргумента. :param options: варианты для выбора. Отобразятся кнопками под сообщением в телеграм боте. :param allowed: допустимые варианты для валидации на стороне телеграм-бота. :param allow_options: сделать допустимыми те, что перечислены в options. """ self.default = default self.name = name self._description = description self._example = example self._options = options self._allowed = allowed if allow_options: self._allowed = options self._extra_info = dict() @property def arg_info(self) -> dict: arg_info = { "description": self._build_description(), "arg_schema": self._build_schema(), } arg_info.update(self._extra_info) if self._options: arg_info["options"] = self._options return arg_info def _build_description(self) -> str: description = self._description if self._example: description += f" return description def _build_schema(self) -> dict: schema = self._create_schema() if self._allowed: schema["allowed"] = self._allowed return schema @abstractmethod def _create_schema(self) -> dict: ... def __repr__(self): return f'Arg(name="{self.name}", description="{self._build_description()}")' class Integer(Arg): BOT_ARG_TYPE = "integer" def __init__(self, *args, minimum=None, maximum=None, **kwargs): """ :param minimum: минимальное значение аргумента. :param maximum: максимальное значение аргумента. """ super().__init__(*args, **kwargs) self.minimum = minimum self.maximum = maximum def _create_schema(self) -> dict: schema = { "type": self.BOT_ARG_TYPE, } if self.maximum: schema["max"] = self.maximum if self.minimum: schema["min"] = self.minimum return schema class String(Arg): BOT_ARG_TYPE = "string" def __init__(self, *args, regex=None, **kwargs): """ :param regex: Регулярное выражение, которому должно соответствовать значение аргумента """ super().__init__(*args, **kwargs) self.regex = regex def _create_schema(self) -> dict: schema = { "type": self.BOT_ARG_TYPE, } if self.regex: schema["regex"] = self.regex return schema class ListArg(Arg): BOT_ARG_TYPE = "list" def _create_schema(self) -> dict: return {"type": "list"} class MyUser(Integer): """ID пользователя телеграм, у которого есть доступ к командам клиента""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._extra_info = dict(is_granter=True) class Actuator(String): """Актуатор бота""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._extra_info = dict(is_actuator=True) class Granter(MyUser): """ID пользователя с правами на актуатор""" # TODO: повтор! def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._extra_info = dict(is_granter=True) class Channel(String): """Канал бота""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._extra_info = dict(is_channel=True) class Subscriber(MyUser): """Подписчик канала""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._extra_info = dict(is_subscriber=True)
python
16
0.571235
97
26.296296
162
starcoderdata
/* * Copyright 2019 Arcus Project * * 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 com.iris.video.recording; import com.codahale.metrics.Counter; import com.codahale.metrics.Timer; import com.iris.metrics.IrisMetricSet; import com.iris.metrics.IrisMetrics; public final class RecordingMetrics { public static final IrisMetricSet METRICS = IrisMetrics.metrics("video.recording"); public static final Counter RECORDING_START_SUCCESS = METRICS.counter("start.success"); public static final Counter RECORDING_START_FAIL = METRICS.counter("start.fail"); public static final Counter RECORDING_STOP_SUCCESS = METRICS.counter("stop.success"); public static final Counter RECORDING_STOP_FAIL = METRICS.counter("stop.fail"); public static final Counter RECORDING_STOP_BAD = METRICS.counter("stop.badrequest"); public static final Counter RECORDING_SESSION_CREATE_SUCCESS = METRICS.counter("session.create.success"); public static final Counter RECORDING_SESSION_CREATE_FAIL = METRICS.counter("session.create.fail"); public static final Counter RECORDING_SESSION_CREATE_TIMEOUT = METRICS.counter("session.create.fail.timeout"); public static final Counter RECORDING_SESSION_CREATE_INVALID = METRICS.counter("session.create.fail.invalid"); public static final Counter RECORDING_SESSION_CREATE_VALIDATION = METRICS.counter("session.create.fail.validation"); public static final Counter RECORDING_SESSION_CREATE_AUTH = METRICS.counter("session.create.fail.missingauth"); public static final Counter RECORDING_SESSION_NOVIDEO = METRICS.counter("session.fail.novideo"); public static final Counter RECORDING_SESSION_NORES = METRICS.counter("session.noresolution"); public static final Counter RECORDING_SESSION_NOFR = METRICS.counter("session.noframerate"); public static final Counter RECORDING_SESSION_NOBW = METRICS.counter("session.nobandwidth"); public static final Counter RECORDING_SESSION_BAD_ENCODING = METRICS.counter("session.fail.badencoding"); public static final Timer RECORDING_LATENCY_SUCCESS = METRICS.timer("latency.success"); public static final Timer RECORDING_LATENCY_TIMEOUT = METRICS.timer("latency.fail.timeout"); public static final Timer RECORDING_LATENCY_FUTURE = METRICS.timer("latency.fail.future"); public static final Timer RECORDING_SESSION_DURATION = METRICS.timer("session.duration"); private RecordingMetrics() { } }
java
8
0.776831
119
52.363636
55
starcoderdata
// Date localization for locale 'jp'. // Provided by Date.dayNames = ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日']; Date.abbrDayNames = ['日', '月', '火', '水', '木', '金', '土']; Date.monthNames = ['1 月', '2 月', '3 月', '4 月', '5 月', '6 月', '7 月', '8 月', '9 月', '10 月', '11 月', '12 月']; Date.abbrMonthNames = ['1 月', '2 月', '3 月', '4 月', '5 月', '6 月', '7 月', '8 月', '9 月', '10 月', '11 月', '12 月']; Date.format = 'yyyy-mm-dd';
javascript
3
0.531955
110
65.5
8
starcoderdata
def pyon_mirror_ops1(obj1, obj2): # NOTE: avoiding ops *I* believe should not be used, or not yet believe they should be used. # leaving in comments in the meantime. ops = [ \ # from dir(int): '__abs__', '__add__', '__and__', '__bool__', '__ceil__', #'__class__', '__delattr__', '__dir__', '__divmod__', # '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', # '__getattribute__', '__getnewargs__', '__gt__', # pretty sure we don't want to mirror __hash__ #'__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', # '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', # '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', # '__setattr__', '__sizeof__', '__str__', '__sub__', # '__subclasshook__', '__truediv__', '__trunc__', '__xor__', # from dir(str): '__contains__', '__getitem__', '__iter__', # pretty sure we want __len__ '__len__', ] for op in ops: mirror(obj1, obj2, op)
python
8
0.402198
94
33.973684
38
inline
package gomple_test import ( "encoding/json" "log" "net/http" "github.com/johejo/gomple" ) func handle(w http.ResponseWriter, r *http.Request) error { // do something return nil // could return error } func Example() { // with http.NewServeMux g := gomple.New() mux := http.NewServeMux() mux.HandleFunc("/", g.WrapFunc(handle)) } func errHandler(w http.ResponseWriter, r *http.Request, err error) { if err != nil { // your own error handling log.Println(err) http.Error(w, err.Error(), http.StatusInternalServerError) } } func ExampleMux() { g := gomple.New(gomple.WithErrorHandler(errHandler)) c := &controller{gomple: g} mux := gomple.NewMuxWithGomple(g) mux.Post("/users", c.createUser) } type controller struct { gomple *gomple.Gomple } type User struct { ID string `json:"id"` Name string `json:"name"` } func (c *controller) createUser(w http.ResponseWriter, r *http.Request) error { var u User if err := json.NewDecoder(r.Body).Decode(&u); err != nil { return err } log.Println(u) w.WriteHeader(http.StatusCreated) return nil }
go
11
0.69447
79
18.696429
56
starcoderdata
void RendererCharacter::flush() { if (m_quadIndex == 0) { return; } // Upload vertex data to GPU m_vertexArray->getVertexBuffers().at(0)->uploadData( m_vertexBufferBase.get(), m_quadIndex * vertexPerQuad * sizeof(CharacterVertex)); bind(); // Render bool depthTest = RenderCommand::depthTest(); RenderCommand::setDepthTest(false); RenderCommand::drawIndexed(*m_vertexArray, m_quadIndex * indexPerQuad); RenderCommand::setDepthTest(depthTest); unbind(); }
c++
10
0.700611
73
22.428571
21
inline
# Generated by Django 2.2.3 on 2019-07-23 10:47 import core.model_fields import core.validators from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('great_international', '0051_aboutukarticlesfields_aboutuklandingpage_aboutukwhychoosetheukpage'), ] operations = [ migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_ar', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_de', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_en_gb', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_es', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_fr', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_ja', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_pt', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), migrations.AlterField( model_name='aboutditservicespage', name='contact_us_section_summary_zh_hans', field=core.model_fields.MarkdownField(blank=True, null=True, validators=[core.validators.slug_hyperlinks], verbose_name='Summary'), ), ]
python
15
0.66
143
46.540984
61
starcoderdata
// // Decompiled by Procyon v0.5.30 // package com.bdoemu.gameserver.model.creature.player.itemPack.events; import com.bdoemu.core.network.sendable.SMExchangeItemSlotInInventory; import com.bdoemu.gameserver.model.creature.player.Player; import com.bdoemu.gameserver.model.creature.player.itemPack.ItemPack; import com.bdoemu.gameserver.model.creature.player.itemPack.PlayerBag; import com.bdoemu.gameserver.model.items.Item; import com.bdoemu.gameserver.model.items.enums.EItemStorageLocation; public class ExchangeItemSlotEvent implements IBagEvent { private Player player; private EItemStorageLocation storageType; private int oldSlot; private int nextSlot; private PlayerBag playerBag; private ItemPack pack; private Item oldItem; public ExchangeItemSlotEvent(final Player player, final EItemStorageLocation storageType, final int oldSlot, final int nextSlot) { this.player = player; this.storageType = storageType; this.oldSlot = oldSlot; this.nextSlot = nextSlot; this.playerBag = player.getPlayerBag(); } @Override public void onEvent() { this.pack.removeItem(this.oldSlot); final Item nextItem = this.pack.removeItem(this.nextSlot); this.pack.addItem(this.oldItem, this.nextSlot); this.oldItem.setSlotIndex(this.nextSlot); this.pack.addItem(nextItem, this.oldSlot); if (nextItem != null) { nextItem.setSlotIndex(this.oldSlot); } this.player.sendPacket(new SMExchangeItemSlotInInventory(this.player, this.storageType, this.oldSlot, this.nextSlot)); } @Override public boolean canAct() { if (this.player.hasTrade() || !this.storageType.isPlayerInventories()) { return false; } this.pack = this.playerBag.getItemPack(this.storageType); if (this.pack == null || this.oldSlot > this.pack.getExpandSize()) { return false; } if (this.oldSlot == this.nextSlot || this.oldSlot < this.pack.getDefaultSlotIndex() || this.nextSlot < this.pack.getDefaultSlotIndex()) { return false; } this.oldItem = this.pack.getItem(this.oldSlot); return this.oldItem != null; } }
java
12
0.693563
145
36.8
60
starcoderdata
using RetSim.Data; using RetSim.Simulation; using RetSim.Simulation.Tactics; using RetSim.Units.Enemy; using RetSim.Units.Player; using RetSim.Units.Player.Static; using RetSimDesktop.Model; using RetSimDesktop.Model.SimWorker; using RetSimDesktop.ViewModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; namespace RetSimDesktop.View { public class WeaponSim : BackgroundWorker { private static Thread[] threads = new Thread[Environment.ProcessorCount]; private static WeaponSimExecuter[] simExecuter = new WeaponSimExecuter[Environment.ProcessorCount]; public WeaponSim() { DoWork += BackgroundWorker_DoWork; } static void BackgroundWorker_DoWork(object? sender, DoWorkEventArgs e) { if (e.Argument is (RetSimUIModel, List int)) { Tuple<RetSimUIModel, IEnumerable int> input = (Tuple<RetSimUIModel, IEnumerable int>)e.Argument; var race = input.Item1.PlayerSettings.SelectedRace; var shattrathFaction = input.Item1.PlayerSettings.SelectedShattrathFaction; var encounterID = input.Item1.EncounterSettings.EncounterID; var numberOfSimulations = input.Item1.SimSettings.SimulationCount; var minDuration = input.Item1.EncounterSettings.MinFightDurationMilliseconds; var maxDuration = input.Item1.EncounterSettings.MaxFightDurationMilliseconds; var talents = input.Item1.SelectedTalents.GetTalentList(); var groupTalents = input.Item1.SelectedBuffs.GetGroupTalents(); groupTalents.AddRange(input.Item1.SelectedDebuffs.GetGroupTalents()); var buffs = input.Item1.SelectedBuffs.GetBuffs(); var debuffs = input.Item1.SelectedDebuffs.GetDebuffs(); var consumables = input.Item1.SelectedConsumables.GetConsumables(); var cooldowns = input.Item1.SelectedCooldowns.GetCooldowns(); List heroismUsage = new(); if (input.Item1.SelectedBuffs.HeroismEnabled) { int time = 8000; if (minDuration < 8000) { time = 0; } while (time < maxDuration) { heroismUsage.Add(time); time += 600000; } } foreach (var item in input.Item2) { if (!item.EnabledForGearSim) { continue; } Equipment playerEquipment = input.Item1.SelectedGear.GetEquipment(); playerEquipment.PlayerEquipment[input.Item3] = item.Weapon; int freeThread = -1; while (freeThread == -1) { for (int i = 0; i < threads.Length; i++) { if (threads[i] == null || !threads[i].IsAlive) { freeThread = i; break; } } Thread.Sleep(100); } simExecuter[freeThread] = new() { Race = Collections.Races[race.ToString()], ShattrathFaction = shattrathFaction, Encounter = Collections.Bosses[encounterID], PlayerEquipment = playerEquipment, Talents = talents, GroupTalents = groupTalents, Buffs = buffs, Debuffs = debuffs, Consumables = consumables, Cooldowns = cooldowns, HeroismUsage = heroismUsage, MinFightDuration = minDuration, MaxFightDuration = maxDuration, NumberOfSimulations = numberOfSimulations, Item = item }; threads[freeThread] = new(new ThreadStart(simExecuter[freeThread].Execute)); threads[freeThread].Start(); } foreach (var thread in threads) { if (thread != null) thread.Join(); } input.Item1.SimButtonStatus.IsSimButtonEnabled = true; } } } public class WeaponSimExecuter : SimExecuter { public DisplayWeapon Item { get; init; } = new(); public override void Execute() { float overallDPS = 0; for (int i = 0; i < NumberOfSimulations; i++) { FightSimulation fight = new(new Player("Brave Hero", Race, ShattrathFaction, PlayerEquipment, Talents), new Enemy(Encounter), new EliteTactic(0), GroupTalents, Buffs, Debuffs, Consumables, MinFightDuration, MaxFightDuration, Cooldowns, HeroismUsage); fight.Run(); overallDPS += fight.CombatLog.DPS; Item.DPS = overallDPS / (i + 1); } Item.DPS = overallDPS / NumberOfSimulations; } } }
c#
23
0.520267
266
39.224638
138
starcoderdata
package crawler; import java.io.*; import java.net.URL; import java.util.*; /** * @author Vadzimko */ public class SimpleWebCrawler implements WebCrawler { private Map<String, Page> visited; private Map<String, Image> images; private Map<String, URL> pageURLs; private Downloader downloader; private BufferedReader input; private int ch; private URL pageUrl; private Queue nextQueue; private List links; SimpleWebCrawler(Downloader downloader) throws IOException { this.downloader = downloader; } public Page crawl(String url, int depth) { visited = new HashMap<>(); images = new HashMap<>(); pageURLs = new HashMap<>(); links = new ArrayList<>(); nextQueue = new ArrayDeque<>(); Queue currQueue = new ArrayDeque<>(); currQueue.add(url); while (depth > 0) { for (String s : currQueue) { if (!visited.containsKey(s)) { crawlPage(s); } } currQueue = nextQueue; nextQueue = new ArrayDeque<>(); depth--; } for (String link : currQueue) { visited.put(link, new Page(link, "")); } for (List l : links) { Page page = visited.get(l.get(0)); for (int i = 1; i < l.size(); i++) { page.addLink(visited.get(l.get(i))); } } return visited.get(url); } private void crawlPage(String link) { try { input = new BufferedReader(new InputStreamReader(downloader.download(link), "utf-8")); } catch (IOException e) { visited.put(link, new Page(link, "")); System.err.println(link); return; } List linksFromPage = new ArrayList<>(); linksFromPage.add(link); try { do { findBeginOfTag(); } while (!readOpenTag().equals("title")); Page page = new Page(link, findTitle()); visited.put(link, page); if (!pageURLs.containsKey(link)) { pageURLs.put(link, new URL(link)); } pageUrl = pageURLs.get(link); while (true) { if (!findBeginOfTag()) { break; } String tag = readOpenTag(); switch (tag) { case "!--": { skipComment(); break; } case "a": { findLink(page, linksFromPage); break; } case "img": { findImage(page); break; } } } links.add(linksFromPage); } catch (IOException e) { System.err.println("Error crawling " + link + ": " + e.getMessage()); } } private boolean findBeginOfTag() throws IOException { while (ch != -1) { if (ch == '<') { nextChar(); if (ch != '/') { break; } } nextChar(); } return ch != -1; } private String readOpenTag() throws IOException { StringBuilder word = new StringBuilder(); while (!Character.isWhitespace(ch) && ch != '>') { word.append((char) ch); nextChar(); } return word.toString().toLowerCase(); } private void nextChar() throws IOException { ch = input.read(); } private void skipSpaces() throws IOException { while (Character.isWhitespace(ch)) { nextChar(); } } private void skipComment() throws IOException { int ch1 = ch; int ch2 = input.read(); int ch3 = input.read(); while (!(ch1 == '-' && ch2 == '-' && ch3 == '>')) { ch1 = ch2; ch2 = ch3; ch3 = input.read(); } } private String findTitle() throws IOException { while (ch != '>') { nextChar(); } nextChar(); StringBuilder sb = new StringBuilder(); while (sb.length() <= 7 || !sb.substring(sb.length() - 7).equals("</title")) { sb.append((char) ch); nextChar(); } sb.delete(sb.length() - 7, sb.length()); return sb.toString() .replaceAll("&lt;", "<") .replaceAll("&gt;", ">") .replaceAll("&nbsp;", "\u00A0") .replaceAll("&mdash;", "\u2014") .replaceAll("&reg;", "\u2014") .replaceAll("&amp;", "\u00AE"); } private String findBracketsInput() throws IOException{ while (!isBracket(ch)) { nextChar(); } nextChar(); skipSpaces(); StringBuilder sb = new StringBuilder(); while (!isBracket(ch) && !Character.isWhitespace(ch)) { sb.append((char) ch); nextChar(); } return sb.toString() .replaceAll("&mdash;", "\u2014") .replaceAll("&amp;", "&"); } private boolean isBracket(int c) { return c == '"' || c == '\''; } private void findImage(Page page) throws IOException{ int ch1 = ch; int ch2 = input.read(); int ch3 = input.read(); while (!(ch1 == 's' && ch2 == 'r' && ch3 == 'c')) { ch1 = ch2; ch2 = ch3; ch3 = input.read(); } String link = findBracketsInput(); URL url; try { url = new URL(pageUrl, link); } catch (IOException e) { System.err.println(link); images.put(link, new Image(link, "")); return; } link = url.toString(); if (images.containsKey(link)) { page.addImage(images.get(link)); } else { Image image = new Image(link, String.valueOf(link.hashCode()) + extension(link)); page.addImage(image); images.put(link, image); try (InputStream in = downloader.download(link); FileOutputStream fos = new FileOutputStream(new File(image.getFile()))){ int ch; while ((ch = in.read()) != -1) { fos.write(ch); } } catch (FileNotFoundException e) { System.err.println("Cannot create or rewrite " + image.getFile() + ": " + e.getMessage()); } catch (IOException e) { System.err.println("Error while downloading " + link + ": " + e.getMessage()); } } } private String extension(String link) { int i = link.length() - 1; while (i >= 0 && link.charAt(i) != '.' && link.charAt( i) != '/') { i--; } if (link.charAt(i) == '.') { return link.substring(i); } else { return ""; } } private void findLink(Page page, List list) throws IOException { int ch1 = ch; int ch2 = input.read(); int ch3 = input.read(); int ch4 = input.read(); if (ch1 == '>' || ch2 == '>' || ch3 == '>') { return; } while(!(ch1 == 'h' && ch2 == 'r' && ch3 == 'e' && ch4 == 'f' || ch1 == 'H' && ch2 == 'R' && ch3 == 'E' && ch4 == 'F') && ch4 != '>') { ch1 = ch2; ch2 = ch3; ch3 = ch4; ch4 = input.read(); } if (ch4 == '>') { return; } String link = findBracketsInput(); URL url; try { url = new URL(pageUrl, link); } catch (IOException e) { System.err.println(link); visited.put(link, new Page(link, "")); list.add(link); return; } link = url.toString(); int index = link.length() - 1; while (index > 0 && link.charAt(index) != '/' && link.charAt(index) != '#') { index--; } if (link.charAt(index) == '#') { link = link.substring(0, index); } pageURLs.put(page.getUrl(), url); if (!visited.containsKey(link)) { nextQueue.add(link); } list.add(link); } }
java
18
0.454599
106
28.638889
288
starcoderdata
a,b = map(int, input().split()) A=0 B=0 for i in range(b): A += a*10**i for i in range(a): B += b*10**i if a==b: print(A) elif a>b: print(B) else: print(A)
python
9
0.533333
31
8.764706
17
codenet
using System.Diagnostics; namespace Alluvial { /// /// A projection. /// /// <typeparam name="TValue">The type of the value. [DebuggerDisplay("{ToString()}")] public class Projection { private static readonly string projectionName = typeof (Projection /// /// Gets or sets the value of the projection. /// /// /// The value of the projection. /// public TValue Value { get; set; } /// /// Returns a <see cref="System.String" /> that represents this instance. /// /// /// A <see cref="System.String" /> that represents this instance. /// public override string ToString() { string valueString; var v = Value; if (v != null) { valueString = v.ToString(); } else { valueString = "null"; } return $"{ProjectionName}: {valueString}"; } /// /// Gets the name of the projection. /// /// /// The name of the projection. /// protected virtual string ProjectionName => projectionName; } }
c#
14
0.51731
99
26.833333
54
starcoderdata
#pragma once #include "utils/Optional.h" #include #include #include #include #include #include namespace bridge { struct RtpMap { enum class Format : uint16_t { VP8 = 100, VP8RTX = 96, OPUS = 111, EMPTY = 4096 }; static const RtpMap& opus(); static const RtpMap& vp8(); RtpMap() : _format(Format::EMPTY), _payloadType(4096), _sampleRate(0) {} RtpMap(const Format format, const uint32_t payloadType, const uint32_t sampleRate) : _format(format), _payloadType(payloadType), _sampleRate(sampleRate) { } RtpMap(const Format format, const uint32_t payloadType, const uint32_t sampleRate, const utils::Optional channels) : _format(format), _payloadType(payloadType), _sampleRate(sampleRate), _channels(channels) { } RtpMap(const RtpMap& rtpMap) = default; Format _format; uint32_t _payloadType; uint32_t _sampleRate; utils::Optional _channels; std::unordered_map<std::string, std::string> _parameters; std::vector<std::pair<std::string, utils::Optional _rtcpFeedbacks; }; } // namespace bridge
c
12
0.623485
86
22.157895
57
starcoderdata
def _get_ss_params(self, method='linear', cfit_method='average'): # type: (str, str) -> Tuple[List[str], List[str], Dict[str, Dict[str, List[LinearInterpolator]]]] tb_type = 'tb_sp' tb_specs = self.specs[tb_type] layout_params = self.specs['layout_params'] dsn_name_base = self.specs['dsn_name_base'] fg = layout_params['fg'] char_freq = tb_specs['tb_params']['sp_freq'] axis_names = ['corner', 'vbs', 'vds', 'vgs'] ss_swp_names = None # type: List[str] corner_list = None corner_sort_arg = None # type: Sequence[int] total_dict = {} for val_list in self.get_combinations_iter(): dsn_name = self.get_instance_name(dsn_name_base, val_list) results = self.get_sim_results(tb_type, val_list) ibias = results['ibias'] if not self.is_nmos(val_list): ibias *= -1 ss_dict = mos_y_to_ss(results, char_freq, fg, ibias, cfit_method=cfit_method) if corner_list is None: ss_swp_names = [name for name in axis_names[1:] if name in results] corner_list = results['corner'] corner_sort_arg = np.argsort(corner_list) # type: Sequence[int] corner_list = corner_list[corner_sort_arg].tolist() cur_scales = [] for name in ss_swp_names: cur_xvec = results[name] cur_scales.append((cur_xvec[0], cur_xvec[1] - cur_xvec[0])) # rearrange array axis sweep_params = results['sweep_params'] swp_vars = sweep_params['ibias'] order = [swp_vars.index(name) for name in axis_names if name in swp_vars] # just to be safe, we create a list copy to avoid modifying dictionary # while iterating over view. for key in list(ss_dict.keys()): new_data = np.transpose(ss_dict[key], axes=order) fun_list = [] for idx in corner_sort_arg: fun_list.append(interpolate_grid(cur_scales, new_data[idx, ...], method=method, extrapolate=True, delta=1e-5)) ss_dict[key] = fun_list # derived ss parameters self._add_derived_ss_params(ss_dict) total_dict[dsn_name] = ss_dict return corner_list, ss_swp_names, total_dict
python
15
0.5389
105
44.481481
54
inline
#pragma once //! Type: Array #define RBE_JSON_DOC_RubberbandSteps "RubberBandSteps" // ############################################################## // Step //! Type: Integer (value > 0) #define RBE_JSON_STEP_Step "Step" //! Type: Boolean #define RBE_JSON_STEP_MayEndWithout "MayEndWithout" //! Type: String (UV, W) #define RBE_JSON_STEP_Projection "Projection" //! Type: Array #define RBE_JSON_STEP_Limits "Limits" //! Type: Array #define RBE_JSON_STEP_Points "Points" //! Type: Array #define RBE_JSON_STEP_Connections "Connections" // ############################################################## // Point //! Type: Integer (value > 0) #define RBE_JSON_Point_ID "ID" //! Type: String (Formula, see documentation) #define RBE_JSON_Point_U "U" //! Type: String (Formula, see documentation) #define RBE_JSON_Point_V "V" //! Type: String (Formula, see documentation) #define RBE_JSON_Point_W "W" // ############################################################## // Connection //! Type: String (Line, Circle) #define RBE_JSON_CONNECTION_Type "Type" //! (OPTIONAL) Type: Boolean #define RBE_JSON_CONNECTION_IgnoreInHistory "IgnoreInHistory" //! Type: String (Reference to Point) #define RBE_JSON_CONNECTION_LINE_From "From" //! Type: String (Reference to Point) #define RBE_JSON_CONNECTION_LINE_To "To" //! Type: String (Reference to Point) #define RBE_JSON_CONNECTION_CIRCLE_Midpoint "Midpoint" //! Type: String (Formula, see documentation) #define RBE_JSON_CONNECTION_CIRCLE_Radius "Radius" //! Type: String (UV, UW, VW) #define RBE_JSON_CONNECTION_CIRCLE_Orientation "Orientation" // ############################################################## // Limits //! Type: String (Umin, Umax, Vmin, Vmax, Wmin, Wmax) #define RBE_JSON_LIMIT_Axis "Axis" //! Type: String (Formula, see documentation) #define RBE_JSON_LIMIT_Value "Value" // ############################################################## // Constant values //! Used to specify a step projection for the UV axis #define RBE_JSON_VALUE_ProjectionUV "UV" //! Used to specify a step projection for the W axis #define RBE_JSON_VALUE_ProjectionW "W" //! Used to specify the connection type as a line connection #define RBE_JSON_VALUE_ConnectionType_Line "Line" //! Used to specify the connection type as a cicle connection #define RBE_JSON_VALUE_ConnectionType_Circle "Circle" //! Used to specify the connection type as a history connection #define RBE_JSON_VALUE_ConnectionType_History "History" //! Used to specify the circle orientation to the UV axis #define RBE_JSON_VALUE_CircleOrientation_UV "UV" //! Used to specify the circle orientation to the UW axis #define RBE_JSON_VALUE_CircleOrientation_UW "UW" //! Used to specify the circle orientation to the VW axis #define RBE_JSON_VALUE_CircleOrientation_VW "VW" //! Used to specify the axis limit #define RBE_JSON_VALUE_AxisLimit_Umin "Umin" //! Used to specify the axis limit #define RBE_JSON_VALUE_AxisLimit_Umax "Umax" //! Used to specify the axis limit #define RBE_JSON_VALUE_AxisLimit_Vmin "Vmin" //! Used to specify the axis limit #define RBE_JSON_VALUE_AxisLimit_Vmax "Vmax" //! Used to specify the axis limit #define RBE_JSON_VALUE_AxisLimit_Wmin "Wmin" //! Used to specify the axis limit #define RBE_JSON_VALUE_AxisLimit_Wmax "Wmax" // ############################################################## //! Used to indicate a reference to a point #define RBE_JSON_INDICATOR_Reference "$"
c
8
0.650957
65
26.147287
129
starcoderdata
protected Object invokeMethod(ServiceRequest request, InvocationContext context, Object service) throws Throwable { MethodDescriptor methodDescriptor = context.getMethodDescriptor(); TimeChecker time = (debug || methodDescriptor.isDebug()) && LOG.isDebugEnabled() ? new TimeChecker(request + " INVOKE ", LOG) : null; try { Object result = context.getMethod().invoke(service, context.getParams()); // If method must return reference, bind result to service register and set result to service locator ValueDescriptor returnDescriptor = methodDescriptor != null ? methodDescriptor.getReturnDescriptor() : null; if (returnDescriptor != null && returnDescriptor.getTransfer() == ValueTransfer.REF) result = ServiceLocator.relative(bindDynamicService(request, result)); // If method must close dynamic service, remove it from repository if (methodDescriptor.isClose()) request.getSession().getServiceRegistry().unbind(request.getServiceName()); // Close dynamic services, passed as parameters for (int i = 0; i < context.getRawParams().length; i++) { ParamDescriptor paramDescriptor = methodDescriptor.getParameterDescriptor(i); if (paramDescriptor != null && paramDescriptor.getTransfer() == ValueTransfer.REF && paramDescriptor.isClose()) request.getSession().getServiceRegistry().unbind(((ServiceLocator) context.getRawParams()[i]).getServiceName()); } if (time != null) time.printDifference(result); return result; } catch (InvocationTargetException e) { Throwable target = ((InvocationTargetException) e).getTargetException(); if (LOG.isDebugEnabled()) LOG.debug(request + (context != null ? '[' + context.toString() + ']' : "") + " invocation error" + context, target); throw target; } catch (Exception e) { LOG.info(request + (context != null ? '[' + context.toString() + ']' : "") + " service error", e); throw new ServiceException(request.toString() + ", invocation " + context + " error", e); } }
java
19
0.632743
141
71.935484
31
inline
TEST_F(JsonSerializerTest, serializeDeserializeTypeWithEnumList) { using namespace infrastructure::DacTypes; std::vector<TrustLevel::Enum> possibleTrustLevels; possibleTrustLevels.push_back(TrustLevel::LOW); possibleTrustLevels.push_back(TrustLevel::MID); possibleTrustLevels.push_back(TrustLevel::HIGH); std::vector<Permission::Enum> possiblePermissions; possiblePermissions.push_back(Permission::NO); possiblePermissions.push_back(Permission::ASK); possiblePermissions.push_back(Permission::YES); infrastructure::DacTypes::MasterAccessControlEntry expectedMac(R"(*)", R"(unittest)", R"(vehicle/radio)", TrustLevel::LOW, possibleTrustLevels, TrustLevel::HIGH, possibleTrustLevels, R"(*)", Permission::YES, possiblePermissions); // Serialize std::string serializedContent = joynr::serializer::serializeToJson(expectedMac); JOYNR_LOG_DEBUG(logger(), "Serialized expectedMac: {}", serializedContent); // Deserialize the result infrastructure::DacTypes::MasterAccessControlEntry mac; joynr::serializer::deserializeFromJson(mac, serializedContent); // Check that the object serialized/deserialized correctly EXPECT_EQ(expectedMac, mac); }
c++
9
0.509091
88
49.444444
36
inline
<?php namespace Sprain\SwissQrBill\PaymentPart\Output\HtmlOutput\Template; class TextElementTemplate { public const TEMPLATE = <<<EOT text }} EOT; }
php
7
0.721212
68
15.5
10
starcoderdata
using System; using System.Reflection; namespace Easy.Endpoints { internal static class GenericTypeHelper { public static bool MatchExpectedGeneric(Type target, Type expectedGenericType) { try { return target.GenericTypeArguments.Length == expectedGenericType.GetTypeInfo().GenericTypeParameters.Length && target == expectedGenericType.MakeGenericType(target.GenericTypeArguments); } catch (ArgumentException) { return false; } } } }
c#
16
0.597315
123
27.380952
21
starcoderdata
/** * 공통 기능 함수 정의 ver1.0 * 작성자 : InnoKim(김정환) * 최초 작성일 : 2021-04-15 * 최종 수정일 : 2021-06-03 * * ### DESCRIPTION ### * - Modify History * - 2020-06-03 : 개발 중인 기능일 경우 알림창 띄우는 함수 추가 */ /** * 문자열이 빈 문자열인지 체크하여 결과값을 리턴 * @param str : 체크할 문자열 */ function isEmpty(str){ if(typeof str == "undefined" || str == null || str == "") return true; else return false ; } /** * 문자열이 빈 문자열인지 체크하여 기본 문자열로 리턴 * @param str : 체크할 문자열 * @param defaultStr : 문자열이 비어있을경우 리턴할 기본 문자열 */ function nvl(str, defaultStr){ if(typeof str == "undefined" || str == null || str == "") str = defaultStr ; return str ; } // 개발 중인 기능일 경우 알림창 띄움 function alertDeveloping() { alert('현재 개발 중입니다.'); return false; }
javascript
9
0.543791
61
18.615385
39
starcoderdata
void SheetManager::addRectangleBorders(SDL_Surface*& target, surfaceType line){ /**UP DOWN lines**/ //Upper line blitSurface(0,0,target->w,1,line,target); //Bottom line blitSurface(0,target->h-1,target->w,1, line,target); /** RIGHT&LEFT LINES **/ //Left blitSurface(0,1,1,target->h-2, line,target); //Right blitSurface(target->w-1,1,1,target->h-2, line,target); }
c++
8
0.607981
79
21.777778
18
inline
import numpy as np from backend.GA.genetic_algorithm import GeneticAlgorithm from backend.GA.genomes import Genome1D from backend.helpers import translate_bits_to_float def fitness_function(genome): interval = [0, 512] x = translate_bits_to_float(bit_string=genome.genes[::-1], interval=interval) return abs(x*np.sin(np.sqrt(abs(x)))) ga = GeneticAlgorithm( pop_size=20, fitness_function=fitness_function, num_generations=5000, genome_type=Genome1D ) best_genome = ga.run() results = {'best_fitness': ga.best_fitness, 'best_x': translate_bits_to_float(ga.best_genome.genes[::-1], [0, 512])} print(results)
python
13
0.689088
116
25.875
24
starcoderdata
const express = require('express'); const router = express.Router(); const todos = require('../models/todos'); router.get('/', function (req, res) { todos.getAll() .then(data => { res.status(200).json(data).end(); }) .catch(err => { res.status(500).end(err.message); }); }); router.get('/:id', (req, res) => { todos.getOne(req.params.id) .then(data => { if (data) { res.status(200).json(data).end(); } else { res.status(404).end(); } }) .catch(err => { console.warn(err.stack); res.status(500).end(err.message); }); }); router.post('/', (req, res) => { if (!req.body.text) { res.status(400).end('Field `text` not set'); return; /* Remember to end the handler itself, otherwise Node will continue execute code below, although `res` has ended. */ } todos.add(req.body.text) .then((id) => { res.status(201).location(`${req.baseUrl}/${id.toHexString()}`).end(); }) .catch(err => { console.warn(err.stack); res.status(500).end(err.message); }); }); router.put('/:id', (req, res) => { if (!req.body.text) { res.status(400).end('Field `text` not set'); return; } todos.update(req.params.id, req.body.text) .then(r => { if (r.modifiedCount === 1) { res.status(200).end(); } else { res.status(404).end(); } }) .catch(err => { console.warn(err.stack); res.status(500).end(err.message); }); }); router.delete('/:id', (req, res) => { todos.remove(req.params.id) .then(r => { res.status(204).end(); }) .catch(err => { console.warn(err.stack); res.status(500).end(err.message); }); }); module.exports = router;
javascript
22
0.507285
75
21.455696
79
starcoderdata
/* * tclspeedbag.c -- * */ #include #include "speedbag.h" #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLEXPORT /* *---------------------------------------------------------------------- * * Speedbag_Init -- * * Initialize the speedbag extension. The string "speedbag" * in the function name must match the PACKAGE declaration at the top of * configure.in. * * Results: * A standard Tcl result * * Side effects: * *---------------------------------------------------------------------- */ EXTERN int Speedbag_Init(Tcl_Interp *interp) { Tcl_Namespace *namespace; /* * This may work with 8.0, but we are using strictly stubs here, * which requires 8.1. */ if (Tcl_InitStubs(interp, "8.1", 0) == NULL) { return TCL_ERROR; } if (Tcl_PkgRequire(interp, "Tcl", "8.1", 0) == NULL) { return TCL_ERROR; } if (Tcl_PkgProvide(interp, "Speedbag", PACKAGE_VERSION) != TCL_OK) { return TCL_ERROR; } namespace = Tcl_CreateNamespace (interp, "speedbag", (ClientData)NULL, (Tcl_NamespaceDeleteProc *)NULL); Tcl_CreateObjCommand (interp, "speedbag::tsv_to_array", speedbag_TsvToArrayObjCmd, (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL); if (Tcl_Export (interp, namespace, "*", 0) == TCL_ERROR) { return TCL_ERROR; } return TCL_OK; } /* *---------------------------------------------------------------------- * * Speedbag_SafeInit -- * * Initialize the speedbag extension in a safe interpreter. * * Results: * A standard Tcl result * * Side effects: * Very little * *---------------------------------------------------------------------- */ EXTERN int Speedbag_SafeInit(Tcl_Interp *interp) { return Speedbag_Init (interp); } // vim: set ts=8 sw=4 sts=4 noet :
c
10
0.521531
108
19.445652
92
starcoderdata
//,temp,sample_6798.java,2,14,temp,sample_5824.java,2,13 //,3 public class xxx { private ArrayList locatedToBlocks(final List locatedBlks, List positionsToRemove) { ArrayList newList = new ArrayList for (int i = 0; i < locatedBlks.size(); i++) { if (positionsToRemove != null && positionsToRemove.contains(i)) { if(LOG.isDebugEnabled()) { log.info("block to be omitted"); } } } } };
java
13
0.724426
113
25.666667
18
starcoderdata
Number.java import java.util.*; import java.lang.*; import java.io.*; /*Math.pow() is import using java.lang package*/ class Main { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); System.out.print("Enter the number :"); double n = sc.nextInt(); double d=0; double m=n; double sum=0; while(n!=0) { d=n%10; sum=sum+ Math.pow(d, 3); n=n/10; } if(d==m) {System.out.println("Armstrong Number");} else {System.out.println("Not an Armstrong Number");} } }
java
12
0.614618
67
19.066667
30
starcoderdata
// NPM IMPORTS import os from 'os' // SERVER IMPORTS import MetricsRecord from '../base/metrics_record' // const context = 'server/metrics/host/metrics_host_record' /** * @file Host information metric class. * @author * @license Apache-2.0 */ export default class MetricsHostRecord extends MetricsRecord { /** * Metrics host record constructor. * * @returns {nothing} */ constructor() { super('host') /** * Class test flag. * @type {boolean} */ this.is_metrics_record_host = true /** * Metrics record values. * @type {object} */ this.values = {} } /** * Executed before request processing. * * @returns {nothing} */ before() { const cpus = os.cpus() const cpus_user_mean = cpus.reduce( (prev = 0, current/*, index, all*/) => prev + current.times.user, 0) / cpus.length const cpus_nice_mean = cpus.reduce( (prev = 0, current/*, index, all*/) => prev + current.times.nice, 0) / cpus.length const cpus_sys_mean = cpus.reduce( (prev = 0, current/*, index, all*/) => prev + current.times.sys, 0) / cpus.length const cpus_idle_mean = cpus.reduce( (prev = 0, current/*, index, all*/) => prev + current.times.idle, 0) / cpus.length const cpus_irq_mean = cpus.reduce( (prev = 0, current/*, index, all*/) => prev + current.times.irq, 0) / cpus.length this.values = { metric:'host', hostname:os.hostname(), ts:new Date().getTime(), cpus_arch:os.arch(), cpus_count:cpus.length, cpus_user:cpus_user_mean, cpus_nice:cpus_nice_mean, cpus_sys:cpus_sys_mean, cpus_idle:cpus_idle_mean, cpus_irq:cpus_irq_mean } } /** * Executed at each request processing iteration. * * @returns {nothing} */ iteration() { this.before() } /** * Executed after request processing. * * @returns {nothing} */ after() { } }
javascript
15
0.601053
120
18.802083
96
starcoderdata
<!doctype html> <html lang="en"> <meta charset="utf-8" /> awesome news aggregation <style type="text/css"> body { font-family: Tahoma,Arial, sans-serif; } h1,h2,h3,strong { color: #666; } blockquote { background: #bbb; border-radius: 3px; } li { border: 2px solid #ccc; border-radius: 5px; list-style-type: none; margin-bottom: 10px; } a { color: #1b9be0; } awesome news aggregation site News @if(count($news)) {{-- We loop all news feed items --}} @foreach($news as $each) from {{$each->title}}: {{-- for each feed item, we get and parse its feed alements --}} <?php $feeds = Str::parse_feed($each->feed); ?> @if(count($feeds)) {{-- In a loop, we show all feed elements one by one --}} @foreach($feeds as $eachfeed) /> {{$eachfeed->pubDate}} /> {{HTML::link($eachfeed->link,Str::limit($eachfeed->link,35))}} @endforeach @else News found for {{$each->title}}. @endif @endforeach @else News found @endif <hr /> Sports News @if(count($sports)) {{-- We loop all news feed items --}} @foreach($sports as $each) New from {{$each->title}}: {{-- for each feed item, we get and parse its feed elements --}} <?php $feeds = Str::parse_feed($each->feed); ?> @if(count($feeds)) {{-- In a loop, we show all feed elements one by one --}} @foreach($feeds as $eachfeed) /> {{$eachfeed->pubDate}} /> {{HTML::link($eachfeed->link,Str::limit($eachfeed->link,35))}} @endforeach @else Sports News found for {{$each->title}} @endif @endforeach @else Sports News found @endif <hr /> Technology News @if(count($technology)) {{-- We loop all news feed items --}} @foreach($technology as $each) New from {{$each->title}}: {{-- For each feed item, we get and parse its feed elements --}} <?php $feeds = Str::parse_feed($each->feed); ?> @if(count($feeds)) {{-- In a loop, we show all feed elements onr by one --}} @foreach($feeds as $eachfeed) /> {{$eachfeed->pubDate}} /> {{HTML::link($eachfeed->link,Str::limit($eachfeed->link,35))}} @endforeach @else Technology News found for {{$each->title}} @endif @endforeach @else Technology News found @endif
php
8
0.590923
96
31.060606
99
starcoderdata
package com.aaa.project.system.policeproject.mapper; import com.aaa.project.system.policeproject.domain.Policeproject; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 项目 数据层 * * @author aaa * @date 2019-04-23 */ public interface PoliceprojectMapper { /** * 查询项目信息 * * @param policeproject 含有项目分类id * @return 项目信息 */ public List selectPoliceprojectByMission(Policeproject policeproject); /** * 查询项目信息 * * @param projectId 项目ID * @return 项目信息 */ public Policeproject selectPoliceprojectById(Integer projectId); /** * 查询项目列表 * * @param policeproject 项目信息 * @return 项目集合 */ public List selectPoliceprojectList(Policeproject policeproject); /** * 新增项目 * * @param policeproject 项目信息 * @return 结果 */ public int insertPoliceproject(Policeproject policeproject); /** * 修改项目 * * @param policeproject 项目信息 * @return 结果 */ public int updatePoliceproject(Policeproject policeproject); /** * 删除项目 * * @param projectId 项目ID * @return 结果 */ public int deletePoliceprojectById(Integer projectId); /** * 批量删除项目 * * @param projectIds 需要删除的数据ID * @return 结果 */ public int deletePoliceprojectByIds(String[] projectIds); /** * 审查规范 * * */ public List selectProjectGuiFan(); /*** * 返回某个任务不及格的项目 * */ public List getPoint(@Param("fmissionid") Integer fmissionid); /** * 项目条数 */ public Integer selectProjectCount(); }
java
10
0.653074
86
17.681818
88
starcoderdata
public JsonObject callProcedure(Connection connection, JsonObject body, JsonObject configuration) throws SQLException { Map<String, ProcedureParameter> procedureParams = ProcedureFieldsNameProvider .getProcedureMetadata(configuration).stream() .collect(Collectors.toMap(ProcedureParameter::getName, Function.identity())); CallableStatement stmt = prepareCallableStatement(connection, configuration.getString("procedureName"), procedureParams, body); ResultSet functionResultSet = null; try { functionResultSet = stmt.executeQuery(); } catch (SQLException e) { if (e.getErrorCode() != 0) { // Ensuring that procedure was executed, but functionResultSet is empty throw e; } } JsonObjectBuilder resultBuilder = Json.createObjectBuilder(); if (functionResultSet != null) { addResultSetToJson(resultBuilder, functionResultSet, "@RETURN_VALUE"); } procedureParams.values().stream() .filter(param -> param.getDirection() == Direction.OUT || param.getDirection() == Direction.INOUT) .forEach(param -> { try { addValueToResultJson(resultBuilder, stmt, procedureParams, param.getName()); } catch (SQLException e) { e.printStackTrace(); } }); stmt.close(); return resultBuilder.build(); }
java
15
0.66907
106
33.7
40
inline
def diff_skipped_lines(request, id_before, id_after, where, column_width, tab_spaces=None): """/<issue>/diff/<patchset>/<patch> - Returns a fragment of skipped lines. *where* indicates which lines should be expanded: 'b' - move marker line to bottom and expand above 't' - move marker line to top and expand below 'a' - expand all skipped lines """ patch = request.patch if where == 'a': context = None else: context = _get_context_for_user(request) or 100 column_width = _clean_int(column_width, django_settings.DEFAULT_COLUMN_WIDTH, django_settings.MIN_COLUMN_WIDTH, django_settings.MAX_COLUMN_WIDTH) tab_spaces = _clean_int(tab_spaces, django_settings.DEFAULT_TAB_SPACES, django_settings.MIN_TAB_SPACES, django_settings.MAX_TAB_SPACES) try: rows = _get_diff_table_rows(request, patch, None, column_width, tab_spaces) except FetchError as err: return HttpTextResponse('Error: %s; please report!' % err, status=500) return _get_skipped_lines_response(rows, id_before, id_after, where, context)
python
11
0.635823
79
42.666667
27
inline
using System; using System.ComponentModel.DataAnnotations; namespace NG.ViewModels { public class SchoolAttendaceVM { [Required(ErrorMessage = "* Id es requerido : 0 registro nuevo , < 0 id registro a manipular")] public int Id { get; set; } [Required(ErrorMessage = "* Id de materia es requerido")] public int IdSchoolSubject { get; set; } public bool StatusItem { get; set; } = true; [DataType(DataType.DateTime, ErrorMessage = "* Fecha invalida")] public DateTime AttendanceRecord { get; set; } public string MAKER { get; set; } = "MASTER"; } }
c#
11
0.642643
103
24.615385
26
starcoderdata
//#include "watchdog_zygote.h" #include #include #include //#include //#include //#include #define LOG_TAG "Zygote watchdog" #define RESULT_PATH "/data/local/tmp/strace.txt" /* watchAndStraceZygote: find zygote process and traces its system calls returns: void */ struct process { int pid; char *name; int ppid; }; typedef struct process MONITORED_PROCESSES; void strace(int pid, char *outputFile) { char straceCommand[100]; snprintf(straceCommand, 100, "su -c \"strace -p %d -o %s\" &", pid, outputFile); if(!fork()){ system(straceCommand); } } /* getProcName: gets the process name from /proc/ returns: char* process name */ char* getProcName(int pid) { char path[40], line[100], *p; FILE* statusf; snprintf(path, 40, "/proc/%d/status", pid); printf("opening proc %s\n", path); statusf = fopen(path, "r"); //file not found if(!statusf){ printf("not found file.\n"); return NULL; } while(fgets(line, 100, statusf)) { if(strncmp(line, "Name:", 5) != 0) continue; // Ignore "State:" and whitespace p = line + 6; while(isspace(*p)) ++p; //printf("%6d %s", pid, p); break; } fclose(statusf); //printf("length of p is %d\n",strlen(p)); printf("name is %s\n", p); return strdup(p); } void watchAndStraceZygote() { system("rm -f %s", "/data/local/tmp/strace.txt"); int pid = findZygote(); char *straceResult = RESULT_PATH; strace(pid, straceResult); printf("zygote pid is %d\n", pid); } /* monitorProcessForkIfExist: trace the system call of targeted process returns: void */ void monitorProcessForkIfExist() { const char resultPath[] = "/data/local/tmp/strace.txt"; char path[40], line[100], *p; FILE* stracef; snprintf(path, 40, resultPath); stracef = fopen(path, "r"); if(!stracef) return; while(fgets(line, 100, stracef)) { if (strncmp(line, "fork()", 6) != 0) continue; p = line + 6; while(isspace(*p)) ++p; //remove "= " ++p; ++p; printf("found process. PID %s\n", p); int isWhitelisted = checkAgainstWhitelist(p); if (!isWhitelisted ) { //check if it's not whitelisted and not monitored at the moment char straceProcessResult[100]; char *procName = getProcName(atoi(p)); snprintf(straceProcessResult, 100, "/data/local/tmp/strace_%s", procName); strace(atoi(p), straceProcessResult); //other monitors will be started here. } //break; } fclose(stracef); } int checkAgainstWhitelist(char *pid) { printf("checking against white list for %s...\n", pid); char *processName = getProcName(atoi(pid)); if (processName == NULL){ return 0; } //read from whitelist file and compare process name char path[40], line[100], *p; FILE* whitelistf; snprintf(path, 40, "/data/local/tmp/whitelist.txt"); whitelistf = fopen(path, "r"); if(!whitelistf){ printf("whitelist file not found\n"); return NULL; } while(fgets(line, 100, whitelistf)){ if(strncmp(line, processName, strlen(processName)) != 0){ continue; }else { return 1; } } //printf("checkAgainstWhitelist function, process name is %s\n", processName); return 0; } /* strdup: Allocate memory for char* return returns: char* */ char* strdup(const char* org) { if(org == NULL) return NULL; char* newstr = malloc(strlen(org)+1); char* p; if(newstr == NULL) return NULL; p = newstr; while(*org) *p++ = *org++; /* copy the string. */ return newstr; } int findZygote() { int i = 1; char* output; for (i=1; i<1000; i++){ output = getProcName(i); printf("output is %s\n", output); char process[] = "zygote"; if (output != NULL && strncmp(output, process, strlen(process)) == 0) { printf("found zygote\n"); return i; } /* if (output == 1) { return i; }*/ } } int main(int argc, char **argv) { //LOGI("Zygote watchdog started"); watchAndStraceZygote(); while(1){ printf("watching...\n"); sleep(3); monitorProcessForkIfExist(); } //findZygotePid(); }
c
13
0.576373
94
19.736111
216
starcoderdata
package com.github.yglll.funlive.view.EventBus; /** * 作者:YGL * 版本号:1.0 * 类描述: * 备注消息:一个消息,发送到MainActivity,以选择Fragment * 创建时间:2018/02/10 14:20 **/ public class SelectPageViewEvent { private int pageNum; public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } }
java
8
0.643617
47
16.904762
21
starcoderdata
package com.github.rakawestu.mvptemplate.domain.repository.api; /** * Api utility class. * Can be used to store configuration * of the api. * * @author rakawm */ public class ApiUtils { public static final String PARAM_KEY = "apikey"; public static final String PARAM_TIMESTAMP = "ts"; public static final String PARAM_HASH = "hash"; private ApiUtils() { //you shall not pass } }
java
8
0.668213
63
18.590909
22
starcoderdata
HRESULT CSoundManager::Initialize( HWND hWnd, DWORD dwCoopLevel ) { HRESULT hr; SAFE_RELEASE( m_pDS ); HRESULT hr00=DSERR_ALLOCATED; HRESULT hr01=DSERR_INVALIDPARAM; HRESULT hr02=DSERR_NOAGGREGATION; HRESULT hr03=DSERR_NODRIVER; HRESULT hr04=DSERR_OUTOFMEMORY; // Create IDirectSound using the primary sound device hr = DirectSoundCreate8( NULL, &m_pDS, NULL ); if (hr) return hr; assert(hr==S_OK); // Set DirectSound coop level hr = m_pDS->SetCooperativeLevel( hWnd, dwCoopLevel ); if (hr) return hr; assert(hr==S_OK); return S_OK; }
c++
8
0.67953
66
23.875
24
inline
private static java.sql.Clob stringToClob(String source) { try { return new javax.sql.rowset.serial.SerialClob(source.toCharArray()); } catch (Exception e) { //log("Could not convert string to a CLOB",e); return null; } }
java
11
0.585714
76
21.5
12
inline
public static string StripCrewFromRawLine(string line) { // Strip out ship-crew links, name, icon and member tags Match crewStart = Regex.Match(line, "CrewMembers="); Match CrewEnd = Regex.Match(line, ",Members="); // +1 and -1 to dispose of leading and trailing brackets int crewStartIndex = crewStart.Index + crewStart.Length + 1; int crewEndIndex = CrewEnd.Index - 1; int length = crewEndIndex - crewStartIndex; return line.Substring(crewStartIndex, length); }
c#
12
0.610727
72
40.357143
14
inline
package models; import com.diogonunes.jcolor.Attribute; import jugadores.Ordenador; import jugadores.Persona; import java.util.ArrayList; import static com.diogonunes.jcolor.Ansi.colorize; public class Juego { //Instancia private static Juego instace = null; //Constantes private final int TAM_FILA=3; private final int TAM_COL=4; //Variables private StringBuilder resPersona; private StringBuilder resOrdenador; //Clases private final ArrayList tableroJuego = new ArrayList<>(); private final Persona personaje= new Persona(); private final Ordenador ordenador = new Ordenador(); /** * Instancia * @return siempre el mismo juego. */ public static Juego getInstance() { if (instace == null) { instace = new Juego(); } return instace; } /** * Constructor */ public Juego() { iniciarTablero(); mostrarCasillas(); ocuparCasillas(); } /** * Nos dice si ya se puede acabar el juego o no * @return boolean */ public boolean acabarJuego() { if (personaje.todoMasVeinte()){ System.out.println("\n Ha ganado la Persona"); }else if(ordenador.todoMasVeinte()){ System.out.println("\n Ha ganado el Ordenador");} return (personaje.todoMasVeinte() || ordenador.todoMasVeinte()); } /** * Ocupar con jugadores las casillas. */ private void ocuparCasillas() { int ocupadas =0; do { pedirCasillaPersona(); pedirCasillaOrdenador(); mostrarCasillas(); ocupadas += 2; }while (ocupadas!=12); } /** * Añadir a casilla Ordenador. */ private void pedirCasillaOrdenador() { int fila; int col; do { fila = (int) (Math.random()*3); col= (int) (Math.random()*4); }while (tableroJuego.get(fila).get(col).getJugadorCasilla()!=null); tableroJuego.get(fila).get(col).setJugadorCasilla(new Ordenador()); } /** * Añadir a casilla Persona. */ private void pedirCasillaPersona() { int fila; int col; do { fila = Input.pedirFila(); col= Input.pedirCol(); }while (tableroJuego.get(fila).get(col).getJugadorCasilla()!=null); tableroJuego.get(fila).get(col).setJugadorCasilla(new Persona()); } /** * Inicializamos cada casilla con su número y su recurso. */ private void iniciarTablero() { for (int i = 0; i < TAM_FILA; i++) { // Creamos cada columna, que es un nuevo arrayList ArrayList fila = new ArrayList<>(); for (int j = 0; j < TAM_COL; j++) { fila.add(new Casillas()); } tableroJuego.add(fila); } } /** * Comienzo del juego */ public void comienzoJuego() { int dado = (int) (Math.random()*6+1); System.out.println(colorize("\nHa salido el " +dado+ " 🎲\n", Attribute.BRIGHT_MAGENTA_TEXT())); verResultados(dado); } /** * Mostrar los resultados de cada ronda. * @param dado para saber que dado ha salido. */ private void verResultados(int dado) { resOrdenador = new StringBuilder("Ordenador "); resPersona = new StringBuilder("Persona "); for (ArrayList juego : tableroJuego) { for (Casillas casillas : juego) { if (casillas.getNumero() == dado) { if (casillas.getJugadorCasilla() instanceof Persona) { personaje.addValorNumero(casillas.getRecurso()); resPersona.append("1 item de ").append(casillas.getRecurso()).append(" "); } else { ordenador.addValorNumero(casillas.getRecurso()); resOrdenador.append("1 item de ").append(casillas.getRecurso()).append(" "); } } } } mostrar(); } /** * Saber que resultados de ordenador y persona mostramos. */ private void mostrar() { if (resPersona.toString().equals("Persona ")){ resPersona = new StringBuilder("Persona 0 items"); }else if (resOrdenador.toString().equals("Ordenador ")){ resOrdenador= new StringBuilder("Ordenador 0 items"); } System.out.println(resPersona); System.out.println(resOrdenador); } /** * Enseñar las casillas. */ private void mostrarCasillas() { for (ArrayList juego : tableroJuego) { for (Casillas casillas : juego) { System.out.print("[ " + casillas + " ] "); } System.out.println(); } } }
java
19
0.556023
103
26.262295
183
starcoderdata
def sent_to_idxs(self, line, explicit_bos=False, explicit_eos=True): """Convert from list of strings to list of token indices.""" tidxs = [] if explicit_bos: tidxs.append(self.TOKENS["<bos>"]) for tok in line.split(): tidxs.append(self._map.get(tok, self.TOKENS["<unk>"])) if explicit_eos: # Append <eos> tidxs.append(self.TOKENS["<eos>"]) return tidxs
python
12
0.550885
68
29.2
15
inline
import time import torch from ..helpers import AverageMeter, ProgressMeter, accuracy, MultiConfusionMatrices, init_module_logger logger = init_module_logger(__name__) def validate(val_loader, model, lossfunc, args, cfgs): """ Validate the model's performance. Args: val_loader (DataLoader): loading data for validation. model (Model): PyTorch model, model to be validated. lossfunc (Loss): loss function. args (ArgumentParser): arguments from commandline inputs. cfgs (dict): configurations from config file. Returns: top-1 accuracy top-5 accuracy loss confusion matrices """ batch_time = AverageMeter('Time', ':6.3f', 's') losses = AverageMeter('Loss', ':.4e') topk_options = cfgs['basic'].get('topk_accs', [1]) topk_accs = [AverageMeter(f'Acc@{k}', ':6.2f', '%') for k in topk_options] progress = ProgressMeter( len(val_loader), [batch_time, losses] + topk_accs, prefix='Test: ') num_classes = cfgs["model"]["kwargs"].get("num_classes") mcms = MultiConfusionMatrices(num_classes) # switch to evaluate mode model.eval() with torch.no_grad(): end = time.time() for i, (inputs, targets) in enumerate(val_loader): # compute outputs outputs = model(inputs) targets = targets.to(outputs.device, non_blocking=True) loss = lossfunc(outputs, targets) # measure accuracy and record loss accs = accuracy(outputs, targets, topk=topk_options) batch_size = targets.size(0) losses.update(loss.item(), batch_size) for accs_idx in range(len(topk_accs)): topk_accs[accs_idx].update(accs[accs_idx] * 100, batch_size) # update all classes' confusion matrices scores, predictions = outputs.max(dim=1) mcms.update(predictions, targets) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.log_freq == 0: logger.info(progress.batch_str(i)) return topk_accs, losses, mcms
python
14
0.599545
103
32.333333
66
starcoderdata
import React from "react"; import { render } from "react-dom"; import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; import { Provider } from "react-redux"; import store from "./store"; import App from "./components/App"; import NotFound from "./components/NotFound"; import HomeContainer from "./containers/HomePage"; import UserManageAppointmentsContainer from "./containers/UserManageAppointments"; import AdminPage from "./containers/AdminPage"; import "./styles/styles.scss"; render( <Provider store={store}> <Route exact path="/" component={HomeContainer} /> <Route exact path="/myappointments" component={UserManageAppointmentsContainer} /> <Route exact path="/admin" component={AdminPage} /> <Route component={NotFound} /> document.getElementById("app") );
javascript
9
0.653734
82
26.864865
37
starcoderdata
package ie.nuig.i3market.semantic.engine.MyPackage; import ie.nuig.i3market.semantic.engine.domain.DataProvider; import ie.nuig.i3market.semantic.engine.exceptions.BindingException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import javax.validation.Valid; import java.util.function.Function; import java.util.function.Predicate; @RestController @RequestMapping("/api/registration/provider") class ResController { @Autowired private DTOservice dtOservice; @Operation( // summary = "${api.i3market-semantic-engine.save-data-provider.description}", summary = "Dummy Provider post API", description = "${api.i3market-semantic-engine.save-data-provider.notes}") @PostMapping public DataProvider saveDataProvider(@RequestBody DataProvider dataProviderTemplate) throws ClassNotFoundException, BindingException { if(provider.test(dataProviderTemplate) ){ throw new RuntimeException("field is empty"); } dtOservice.saveDataProvider(dataProviderTemplate); return dataProviderTemplate; } Predicate provider = e-> e.getProviderId().isEmpty() || e.getName().isEmpty() || e.getDescription().isEmpty() || e.getOrganization().isEmpty(); }
java
12
0.753756
161
37.275
40
starcoderdata
using UnityEngine; using System.Collections; using GDGeek; using UnityEngine.SceneManagement; class MenuLogic { private FSM fsm_ = null; public static string RootState = "menu"; private State getRoot(){ State state = new State (); return state; } public static string CheckState = RootState + "_check"; private State getCheck(){ State state = TaskState.Create (delegate() { return new Task(); }, this.fsm_, delegate { if(UserModel.Instance.hasInfo){ return LoginState; }else{ return RegisterInputState; } }); return state; } public static string LoginState = RootState + "_login"; private State getLogin(){ bool error = false; State state = TaskState.Create (delegate() { //得到用户数据 User data = UserModel.Instance.data; //创建网络任务 WebLoaderTask web = WebAction.Instance.login(data.id, data.password); //错误处理 web.onError += delegate(string msg) { error = true; }; //成功处理 web.onSucceed += delegate(UserInfo info) { error = false; }; return web; }, this.fsm_, delegate { if(error){ //登陆错误,删除用户信息,回到检查状态 UserModel.Instance.clear(); return CheckState; }else{ //成功去Start状态 return StartState; } }); return state; } public static string RegisterInputState = RootState + "_register_input"; private State getRegisterInput(){ State state = new State (); state.onStart += delegate() { //打开注册菜单 MenuView.Instance._rigister.gameObject.SetActive(true); MenuView.Instance._top.gameObject.SetActive(false); }; //当接收到register消息之后 state.addAction ("register", delegate(FSMEvent evt) { string error; if(UserModel.Instance.checkName(out error)){ //如果昵称正确,关闭警告,进入联网注册状态 MenuView.Instance._rigister.warning(null); return RegisterWWWState; }else{ //否则,提示错误 MenuView.Instance._rigister.warning(error); Debug.Log(error); } return ""; }); return state; } public static string RegisterWWWState = RootState + "_register_www"; private State getRegisterWWW(){ bool error = true; State state = TaskState.Create (delegate() { //建立联网任务 WebLoaderTask register = WebAction.Instance.register(UserModel.Instance.userName); register.onError += delegate(string msg) { //如果错误,提示警告 MenuView.Instance._rigister.warning(msg); error = true; }; register.onSucceed += delegate(UserInfo info) { //如果正确检查信息是否成功 if(info.succeed){ //成功,保存用户信息 error = false; UserModel.Instance.data = info.user; }else{ //失败提示警告 error = true; MenuView.Instance._rigister.warning(info.message); } }; TaskList tl = new TaskList(); //显示Loading界面 tl.push(Loading.Instance.show(0.5f)); tl.push(register); //关闭Loading界面 tl.push(Loading.Instance.hide()); return tl; }, fsm_, delegate(FSMEvent evt) { if(error){ //如果错误,回去输入界面 return RegisterInputState; } //否则进入游戏开始 return StartState; }); return state; } public static string StartState = RootState + "_input"; private State getStart(){ State state = new State (); state.onStart += delegate() { //关闭注册窗口 MenuView.Instance.closeRegister(); //显示最高排行按钮 MenuView.Instance.top(); TaskSet ts = new TaskSet(); //飞机飞进来 ts.push(MenuView.Instance._fly.comein ()); TaskManager.Run(ts); }; state.onOver += delegate() { TaskManager.Run(MenuView.Instance._fly.goout ()); }; return state; } private string exit_; private string exitTop_; public State setup(FSM fsm){ fsm_ = fsm; State root = getRoot (); fsm_.addState (RootState, root); fsm_.addState (CheckState, getCheck (), RootState); fsm_.addState (LoginState, getLogin (), RootState); fsm_.addState (RegisterInputState, getRegisterInput (), RootState); fsm_.addState (RegisterWWWState, getRegisterWWW (), RootState); fsm_.addState (StartState, getStart (), RootState); return root; } }
c#
25
0.661511
95
20.434783
184
starcoderdata
import Axios from 'axios'; import React, { Component } from 'react'; import Swal from 'sweetalert2' class AddDistributor extends Component { constructor(props) { super(props); this.state={ fname:'', lname:'', company_name:'', phone:'', email:'', credit_limit:'', address:'', country:'', city:'', gst:'', gst_check:true } } componentDidMount(){ let senderdata = { id:this.props.match.params.id } Axios.post('/api/get_distributor_by_id',senderdata).then(res=>{ console.log(res); let data = res.data; this.setState({ fname:data.fname, lname:data.lname, company_name:data.company, phone:data.phone, email:data.email, credit_limit:data.credit_limit, address:data.address, country:data.country, city:data.city, gst:data.gst }) }) } fname(e){ this.setState({ fname:e.target.value }) } lname(e){ this.setState({ lname:e.target.value }) } company_name(e){ this.setState({ company_name:e.target.value }) } phone(e){ this.setState({ phone:e.target.value }) } email(e){ this.setState({ email:e.target.value }) } credit_limit(e){ this.setState({ credit_limit:e.target.value }) } address(e){ this.setState({ address:e.target.value }) } country(e){ this.setState({ country:e.target.value }) } city(e){ this.setState({ city:e.target.value }) } gst(e){ this.setState({ gst:e.target.value }) } gst_check(e){ this.setState({ gst_check:!this.state.gst_check }) } create_distributor(){ let senderdata = { fname:this.state.fname, lname:this.state.lname, company_name:this.state.company_name, phone:this.state.phone, email:this.state.email, credit_limit:this.state.credit_limit, address:this.state.address, country:this.state.country, city:this.state.city, gst:this.state.gst, id:this.props.match.params.id } Axios.post('/api/update_distributor',senderdata).then(res=>{ if(res.data.status == 200){ Swal.fire({ icon: 'success', title: res.data.msg, showConfirmButton: false, timer: 1500 }) }else{ Swal.fire({ icon: 'error', title: res.data.msg, showConfirmButton: false, timer: 1500 }) } }) } render() { return ( <div className="top_section_title_div"> <h2 className="section_title">Update Distributor <div className="container"> <div className="card mt-3"> <div className="row col-md-12"> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">First Name <input value={this.state.fname || ""} onChange={this.fname.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="First Name" /> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">Last Name <input value={this.state.lname || ""} onChange={this.lname.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Last Name" /> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">Company Name <input value={this.state.company_name || ""} onChange={this.company_name.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Company Name" /> <div className="row col-md-12"> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">Phone Number <input value={this.state.phone || ""} onChange={this.phone.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Phone Number" /> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">Email Address <input value={this.state.email || ""} disabled onChange={this.email.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Email Address" /> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">Credit Limit <input value={this.state.credit_limit || ""} onChange={this.credit_limit.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Credit Limit" /> <div className="row col-md-12"> <div class="form-group input_div col-md-12"> <label className="input_label" for="exampleInputEmail1">Bussiness Address <input value={this.state.address || ""} onChange={this.address.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Bussiness Address" /> <div className="row col-md-12"> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">Country <input value={this.state.country || ""} onChange={this.country.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="Country " /> <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">City <input value={this.state.city || ""} onChange={this.city.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="City" /> {/* <div className="row col-md-12"> <div class="form-group input_div col-md-1"> <input value={this.state.fname || ""} onChange={this.gst_check.bind(this)} checked={this.state.gst_check} type="radio" className="mr-1" name="gst" aria-describedby="emailHelp" />GST <div class="form-group input_div col-md-2"> <input value={this.state.fname || ""} onChange={this.gst_check.bind(this)} checked={this.state.gst_check == false} type="radio" className="mr-1" name="gst" aria-describedby="emailHelp" />Non GST */} <div class="form-group input_div col-md-4"> <label className="input_label" for="exampleInputEmail1">GST <input value={this.state.gst || ""} onChange={this.gst.bind(this)} type="email" class="form-control " aria-describedby="emailHelp" placeholder="GST " /> <button onClick={this.create_distributor.bind(this)} className="btn btn-success ml-3 mb-4 col-md-1">save ); } } export default AddDistributor;
javascript
18
0.475502
227
43.64532
203
starcoderdata
import React from 'react' import { useStaticQuery, graphql } from 'gatsby' import styled from 'styled-components' import Heading from 'elements/heading' import Avatar from 'svg/icon-bljw.svg' import Github from 'svg/icon-github.svg' import Linkedin from 'svg/icon-linkedin.svg' import { baseStyling } from './styles' const Social = ({ className, showAvatar }) => { const data = useStaticQuery(graphql` query SocialQuery { site { siteMetadata { author { name } social { github linkedin } } } } `) const author = data.site.siteMetadata?.author const social = data.site.siteMetadata?.social return ( <div className={className}> {Avatar && showAvatar && ( <Avatar className='social__avatar' /> )} {author?.name && ( <Heading as='h5'>Find me on <a className='social__anchor' href={`https://www.github.com/${social?.github || ''}`} target='_blank' rel='noopener noreferrer' > <Github className='social__anchor__github' /> <a className='social__anchor' href={`https://www.linkedin.com/in/${social?.linkedin || ''}`} target='_blank' rel='noopener noreferrer' > <Linkedin className='social__anchor__linkedin' /> )} ) } export default styled(Social)` ${baseStyling} .social__avatar { width: 3rem; } .social__anchor { display: flex; box-sizing: content-box; max-width: ${({ theme }) => theme.spacingM}; padding: ${({ theme }) => theme.spacingXS}; background-color: ${({ theme }) => theme.offWhiteLight}; border-radius: ${({ theme }) => `0 ${theme.spacingS} ${theme.spacingS}`}; transition: ${({ theme }) => theme.transition}; &:hover { background-color: ${({ theme }) => theme.tertiaryColor}; box-shadow: 0 6px 0 0 ${({ theme }) => theme.tertiaryColor}; } svg { width: 2rem; height: 2rem; } } `
javascript
22
0.503606
78
24.074468
94
starcoderdata
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// /// AlipayCommerceGreenItemenergySendModel Data Structure. /// [Serializable] public class AlipayCommerceGreenItemenergySendModel : AopObject { /// /// 支付宝用户ID /// [XmlElement("alipay_uid")] public string AlipayUid { get; set; } /// /// 绿色能量发放归属方信息, 说明: (1)如果该复杂对象不填,根据openAPI标准流程决定能量发放归属方 -商户自研, 那么能量发放归属方就是商户. -第三方应用授权, 那么能量发放归属方就是授权的商户. 参考https://opendocs.alipay.com/isv/10467/xldcyq (2)如果填写,则认为能量发放归属方就是merchant_pid对应的商户. /// [XmlElement("belong_merchant_info")] public BelongGreenMerchantInfo BelongMerchantInfo { get; set; } /// /// 商品69码,被扫商品的69码 /// [XmlElement("goods_id")] public string GoodsId { get; set; } /// /// 商品名称 /// [XmlElement("goods_name")] public string GoodsName { get; set; } /// /// 行业类型。枚举: 快消:FMCG; 酒店:HOTEL; 智能售卖:AUTOMAT; 景区:RESORT;高校:HIGHSCHOOL;品牌:FASHION; 商圈综合体:MALL; 充电宝:POWERBANK; 物流:LOGISTICS; 餐饮:CATERING; /// [XmlElement("industry_type")] public string IndustryType { get; set; } /// /// 支付宝绿色阵地订单详情跳转链接,商户可自定义跳转到自己的小程序(落地页)如果是小程序链接且带有参数,如示例中page=pages%2Fmap%2Findex%3FchInfo%3D%2520locationcard部分需要encode,否则page后面的参数会丢失。 /// [XmlElement("order_link")] public string OrderLink { get; set; } /// /// 被扫码的二维码ID /// [XmlElement("qr_code_id")] public string QrCodeId { get; set; } /// /// 扫码时间 /// [XmlElement("scan_time")] public string ScanTime { get; set; } } }
c#
11
0.58316
205
31.066667
60
starcoderdata
/* Copyright 2017 Long Range Systems, LLC * * 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. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * 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.lrsus.ttgatewaydiscovery; import android.content.Context; import android.net.nsd.NsdManager; import android.net.nsd.NsdServiceInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.HashSet; public class MainActivity extends AppCompatActivity { private String TAG = "GatewayDiscovery"; private ListView gatewayList; // Gateway will be advertising with type "_tracker-http._tcp" private String SERVICE_TYPE = "_tracker-http._tcp"; // DiscoveryListener will look for advertisements. It is not possible to get advertiser's // host information unless passing service info to resolve listener. private NsdManager.DiscoveryListener mDiscoveryListener; // ResolveListener will resolve services that are discovered from discovery listener. private NsdManager.ResolveListener mResolveListener; // Manager is a service that manages listeners related to network discovery. private NsdManager mNsdManager; // Vector of NsdServiceInfo will hold all the gateways discovered. private HashSet mServices = new HashSet<>(); // Adapter for list view. private ArrayAdapter adapter; class GatewayResolveListener implements NsdManager.ResolveListener { @Override public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { // Called when the resolve fails. Use the error code to debug. Log.e(TAG, "Resolve failed" + errorCode); } @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { final String hostAddress = serviceInfo.getHost().getHostAddress(); // To prevent duplicate items, we'll add it to set. if (!mServices.contains(hostAddress)) { Log.e(TAG, "Resolve Succeeded. " + serviceInfo); if (serviceInfo.getServiceType().equals(SERVICE_TYPE)) { Log.d(TAG, "Same IP."); return; } // Add to set mServices.add(hostAddress); // Update UI ListView with host address. runOnUiThread(new Runnable() { @Override public void run() { adapter.add(hostAddress); } }); } } }; class GatewayDiscoveryListener implements NsdManager.DiscoveryListener { @Override public void onDiscoveryStarted(String regType) { Log.d(TAG, "Service discovery started."); } @Override public void onServiceFound(NsdServiceInfo service) { // Check if advertisement matches tag. if (!service.getServiceType().equals(SERVICE_TYPE)) {; mNsdManager.resolveService(service, mResolveListener); } } @Override public void onServiceLost(NsdServiceInfo service) { Log.e(TAG, "Service lost: " + service.getServiceName()); } @Override public void onDiscoveryStopped(String serviceType) { Log.i(TAG, "Discovery stopped: " + serviceType); mDiscoveryListener = null; } @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery start failed - " + serviceType + " code: " + errorCode); mDiscoveryListener = null; } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery stop failed - " + serviceType + " code: " + errorCode); mDiscoveryListener = null; } } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gatewayList = (ListView) findViewById(R.id.gateway_addresses); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); gatewayList.setAdapter(adapter); mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE); } @Override protected void onStart() { super.onStart(); if (mResolveListener == null) { mResolveListener = new GatewayResolveListener(); } if (mDiscoveryListener == null) { mDiscoveryListener = new GatewayDiscoveryListener(); // Give listener to NSD system service mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); } } @Override protected void onResume() { super.onResume(); if (mResolveListener == null) { mResolveListener = new GatewayResolveListener(); } if (mDiscoveryListener == null) { mDiscoveryListener = new GatewayDiscoveryListener(); // Give listener to NSD system service mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); } } @Override protected void onPause() { // Stop discovery since we don't want it to be running in the background. if (mDiscoveryListener != null) { mNsdManager.stopServiceDiscovery(mDiscoveryListener); mDiscoveryListener = null; } super.onPause(); } @Override protected void onStop() { if (mDiscoveryListener != null) { mNsdManager.stopServiceDiscovery(mDiscoveryListener); mDiscoveryListener = null; } super.onStop(); } }
java
19
0.659857
103
36.597938
194
starcoderdata
def modify_document(self, doc): ''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found. ''' if self._lifecycle_handler.failed: return # Note: we do NOT copy self._theme, which assumes the Theme # class is immutable (has no setters) if self._theme is not None: doc.theme = self._theme if self._template is not None: doc.template = self._template # This internal handler should never add a template self._main_handler.modify_document(doc)
python
8
0.617219
78
35
21
inline
NTSTATUS vJoySetFeature( IN WDFREQUEST Request ) /*++ Routine Description This routine sets the state of the Feature: in this case Segment Display on the USB FX2 board. Arguments: Request - Wdf Request Return Value: NT status value --*/ { NTSTATUS status = STATUS_SUCCESS; //UCHAR commandData = 0; PHID_XFER_PACKET transferPacket = NULL; WDF_REQUEST_PARAMETERS params; //WDFDEVICE device; //UCHAR featureUsage = 0; PUCHAR TmpBfr; PAGED_CODE(); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "vJoySetFeature Enter\n"); WDF_REQUEST_PARAMETERS_INIT(&params); WdfRequestGetParameters(Request, &params); // // IOCTL_HID_SET_FEATURE & IOCTL_HID_GET_FEATURE are not METHOD_NIEHTER // IOCTLs. So you cannot retreive UserBuffer from the IRP using Wdf // function. As a result we have to escape out to WDM to get the UserBuffer // directly from the IRP. // if (params.Parameters.DeviceIoControl.InputBufferLength < sizeof(HID_XFER_PACKET)) { status = STATUS_BUFFER_TOO_SMALL; TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL,"Userbuffer is small 0x%x\n", status); return status; } // // This is a kernel buffer so no need for try/except block when accesssing // Irp->UserBuffer. // transferPacket = (PHID_XFER_PACKET) WdfRequestWdmGetIrp(Request)->UserBuffer; if (transferPacket == NULL) { status = STATUS_INVALID_DEVICE_REQUEST; TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "Irp->UserBuffer is NULL 0x%x\n", status); return status; } if (transferPacket->reportBufferLen == 0){ status = STATUS_BUFFER_TOO_SMALL; TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "HID_XFER_PACKET->reportBufferLen is 0, 0x%x\n", status); return status; } if (transferPacket->reportBufferLen < sizeof(UCHAR)){ status = STATUS_BUFFER_TOO_SMALL; TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, "HID_XFER_PACKET->reportBufferLen is too small, 0x%x\n", status); return status; } // Get the REPORT_ID of this feature report //if (transferPacket->reportId != FEATURE_COLLECTION_REPORT_ID){ // status = STATUS_INVALID_DEVICE_REQUEST; // TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, // "Incorrect report ID, 0x%x\n", status); // return status; //} TmpBfr = (UCHAR *)transferPacket->reportBuffer; //featureUsage = featureReport->FeatureData; //if ((featureUsage >= sizeof(UsageToCommandDataMappingTable)) || // (featureUsage == 0)) { // status = STATUS_INVALID_DEVICE_REQUEST; // TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTL, // "Incorrect Usage provided: %d\n", featureUsage); // return status; //} //// //// The Usage IDs 1 through 8 map to number displays on 7-segment display. //// and Usage IDs 9 thorugh 18 map to LED display on Bar Graph. //// //commandData = UsageToCommandDataMappingTable[featureUsage]; //if (featureUsage <= 8) { // status = SendVendorCommand( // device, // HIDFX2_SET_7SEGMENT_DISPLAY, // &commandData // ); //} //else if(featureUsage <= 18){ // status = SendVendorCommand( // device, // HIDFX2_SET_BARGRAPH_DISPLAY, // &commandData // ); //} TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTL, "vJoySetFeature Exit\n"); return status; }
c
9
0.610695
115
30.666667
114
inline
Vec3 PixelBuffer::getColor(float u, float v) const { int y = _width - 1; int x = (int) (u * y); // do positive modulo so you can get texture wrapping outside [0, 1] int i = (x % y + y) % y; y = _height - 1; x = (int) (v * y); int j = (x % y + y) % y; int index = 3 * (j * _width + i); return Vec3(_pixels[index], _pixels[index+1], _pixels[index+2]); }
c++
9
0.546196
69
27.384615
13
inline
@Override public void onItemClick(ActionItem item) { //here we can filter which action item was clicked with pos or actionId parameter String title = item.getTitle(); Toast.makeText(SampleActivity.this, title + " selected", Toast.LENGTH_SHORT).show(); if (!item.isSticky()) quickAction.remove(item); }
java
9
0.669565
92
48.428571
7
inline
<main class="container"> <?php if($_SESSION['isLoggedIn'] == 1){ echo ' '.$_SESSION['user']['fname'].' } else{ foreach($setting as $settingObj){ if($settingObj['tkey'] == 'company'){ echo ' to '.$settingObj['value'].' } } } ?>
php
13
0.346743
76
20.791667
24
starcoderdata
package com.fasterxml.jackson.databind.ser.impl; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; /** * Simple serializer that will call configured type serializer, passing * in configured data serializer, and exposing it all as a simple * serializer. */ public final class TypeWrappedSerializer extends JsonSerializer { final protected TypeSerializer _typeSerializer; final protected JsonSerializer _serializer; @SuppressWarnings("unchecked") public TypeWrappedSerializer(TypeSerializer typeSer, JsonSerializer ser) { super(); _typeSerializer = typeSer; _serializer = (JsonSerializer ser; } @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { _serializer.serializeWithType(value, jgen, provider, _typeSerializer); } @Override public void serializeWithType(Object value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException { /* Is this an erroneous call? For now, let's assume it is not, and * that type serializer is just overridden if so */ _serializer.serializeWithType(value, jgen, provider, typeSer); } @Override public Class handledType() { return Object.class; } /* /********************************************************** /* Extended API for other core classes /********************************************************** */ public JsonSerializer valueSerializer() { return _serializer; } public TypeSerializer typeSerializer() { return _typeSerializer; } }
java
10
0.667874
109
30.688525
61
starcoderdata
/** * @Author: * @Date: 2018-03-22T11:01:33+01:00 * @Email: * @Filename: script.js * @Last modified by: * @Last modified time: 2018-03-22T11:59:48+01:00 * @License: Apache 2.0 * @Copyright: Copyright © 2017-2018 Artevelde University College Ghent */ // Declaratie van lijst let recipeOverview = document.getElementById('recipes'); // functie expressie om JSON-request via url uit te voeren const getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function() { var status = xhr.status; if (status === 200) { callback(null, xhr.response); } else { callback(status, xhr.response); } }; xhr.send(); }; // get json data getJSON('https://evelienrutsaert.github.io/recourses/recipes.json', function(error, data) { // show error if(error) { // do something here return false; } for(let i = 0; i < data.length; i++) { let recipe = data[i]; // Aanmaken van col-4 div let col = document.createElement('div'); col.classList.add('col-4'); //Toevoegen aan pagina recipeOverview.appendChild(col); //Aanmaken van card let card = document.createElement('div'); card.classList.add('card'); //Toevoegen aan col-4 col.appendChild(card); //Aanmaken img card-top let img = document.createElement('img'); img.src= recipe.image; img.classList.add('card-img-top'); //Toevoegen aan card card.appendChild(img); //Aanmaken card-block let block = document.createElement('div'); block.classList.add('card-block'); //Toevoegen aan card card.appendChild(block); //Aanmaken titel recept let title = document.createElement('h4'); title.classList.add('card-title'); //Aanmaken TextNode voor Titel let titleContent = document.createTextNode(recipe.name); //Toevoegen text aan Titel title.appendChild(titleContent); //Toevoegen titel aan block block.appendChild(title); //Aanmaken ingredienten let ingredientDiv = document.createElement('div'); ingredientDiv.classList.add('card-ingredients'); //Toevoegen div aan block block.appendChild(ingredientDiv); //Aanmaken ingrediententext let titleSpan = document.createElement('span'); titleSpan.classList.add('text-bold'); //Aanmaken Titel let ingredientTitle = document.createTextNode('Ingrediënten: '); //Toevoegen text aan titleSpan titleSpan.appendChild(ingredientTitle); //Toevoegen span aan ingredientDiv ingredientDiv.appendChild(titleSpan); for(let i = 0; i < recipe.ingredients.length; i++){ if(i == 0) { ingredientDiv.innerHTML += ' } ingredientDiv.innerHTML += recipe.ingredients[i] if(i < (recipe.ingredients.length - 1)) { ingredientDiv.innerHTML += ', ' } } //Aanmaken card-text div let bereiding = document.createElement('div'); bereiding.classList.add('card-text'); //Toevoegen div aan block block.appendChild(bereiding); //Aanmaken span voor Bereidingswijze let berSpan = document.createElement('span'); berSpan.classList.add('text-bold'); //Aanmaken text let berTitle = document.createTextNode('Bereidingswijze: '); //Toevoegen aan berSpan berSpan.appendChild(berTitle); bereiding.appendChild(berSpan); //Toevoegen text voor Bereidingswijze let berP = document.createElement('p'); //Aanmaken TextNode let berTxt = document.createTextNode(recipe.directions); //Samenvoegen berP.appendChild(berTxt); //Toevoegen aan bereiding bereiding.appendChild(berP); } });
javascript
17
0.615519
92
30.3125
128
starcoderdata
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/base/media_log.h" #include #include "base/atomic_sequence_num.h" #include "base/json/json_writer.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "base/values.h" namespace media { const char MediaLog::kEventKey[] = "event"; const char MediaLog::kStatusText[] = "pipeline_error"; // A count of all MediaLogs created in the current process. Used to generate // unique IDs. static base::AtomicSequenceNumber g_media_log_count; MediaLog::MediaLog() : MediaLog(new ParentLogRecord(this)) {} MediaLog::MediaLog(scoped_refptr parent_log_record) : parent_log_record_(std::move(parent_log_record)), id_(g_media_log_count.GetNext()) {} MediaLog::~MediaLog() { // If we are the underlying log, then somebody should have called // InvalidateLog before now. Otherwise, there could be concurrent calls into // this after we're destroyed. Note that calling it here isn't really much // better, since there could be concurrent calls into the now destroyed // derived class. // // However, we can't DCHECK on it, since lots of folks create a base Medialog // implementation temporarily. So, the best we can do is invalidate the log. // We could get around this if we introduce a new NullMediaLog that handles // log invalidation, so we could dcheck here. However, that seems like a lot // of boilerplate. if (parent_log_record_->media_log == this) InvalidateLog(); } // Default *Locked implementations void MediaLog::AddLogRecordLocked(std::unique_ptr event) {} std::string MediaLog::GetErrorMessageLocked() { return ""; } void MediaLog::AddMessage(MediaLogMessageLevel level, std::string message) { std::unique_ptr record( CreateRecord(MediaLogRecord::Type::kMessage)); record->params.SetStringPath(MediaLogMessageLevelToString(level), std::move(message)); AddLogRecord(std::move(record)); } void MediaLog::NotifyError(PipelineStatus status) { std::unique_ptr record( CreateRecord(MediaLogRecord::Type::kMediaStatus)); record->params.SetIntPath(MediaLog::kStatusText, status); AddLogRecord(std::move(record)); } void MediaLog::NotifyError(Status status) { DCHECK(!status.is_ok()); std::string output_str; base::JSONWriter::Write(MediaSerialize(status), &output_str); AddMessage(MediaLogMessageLevel::kERROR, output_str); } void MediaLog::OnWebMediaPlayerDestroyedLocked() {} void MediaLog::OnWebMediaPlayerDestroyed() { AddEvent base::AutoLock auto_lock(parent_log_record_->lock); // Forward to the parent log's implementation. if (parent_log_record_->media_log) parent_log_record_->media_log->OnWebMediaPlayerDestroyedLocked(); } std::string MediaLog::GetErrorMessage() { base::AutoLock auto_lock(parent_log_record_->lock); // Forward to the parent log's implementation. if (parent_log_record_->media_log) return parent_log_record_->media_log->GetErrorMessageLocked(); return ""; } std::unique_ptr MediaLog::Clone() { // Protected ctor, so we can't use std::make_unique. return base::WrapUnique(new MediaLog(parent_log_record_)); } void MediaLog::AddLogRecord(std::unique_ptr record) { base::AutoLock auto_lock(parent_log_record_->lock); // Forward to the parent log's implementation. if (parent_log_record_->media_log) parent_log_record_->media_log->AddLogRecordLocked(std::move(record)); } std::unique_ptr MediaLog::CreateRecord( MediaLogRecord::Type type) { auto record = std::make_unique record->id = id_; record->type = type; record->time = base::TimeTicks::Now(); return record; } void MediaLog::InvalidateLog() { base::AutoLock auto_lock(parent_log_record_->lock); // It's almost certainly unintentional to invalidate a parent log. DCHECK(parent_log_record_->media_log == nullptr || parent_log_record_->media_log == this); parent_log_record_->media_log = nullptr; // Keep |parent_log_record_| around, since the lock must keep working. } MediaLog::ParentLogRecord::ParentLogRecord(MediaLog* log) : media_log(log) {} MediaLog::ParentLogRecord::~ParentLogRecord() = default; LogHelper::LogHelper(MediaLogMessageLevel level, MediaLog* media_log) : level_(level), media_log_(media_log) { DCHECK(media_log_); } LogHelper::LogHelper(MediaLogMessageLevel level, const std::unique_ptr media_log) : LogHelper(level, media_log.get()) {} LogHelper::~LogHelper() { media_log_->AddMessage(level_, stream_.str()); } } //namespace media
c++
14
0.721258
79
33.730496
141
starcoderdata
/*coderanant*/ #include using namespace std; #define int long long #define ll long long #define f1(i,a,b) for(i=a;i<b;i++) #define f2(i,a,b) for(i=a;i>=b;i--) #define endl '\n' #define pb push_back #define gp " " #define ff first #define ss second #define mp make_pair const int mod=1000000007; int maxn=(1ll<<32)-1; ll temp; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("/home/akmittal/Desktop/Competitive Programming/in.txt","r",stdin); freopen("/home/akmittal/Desktop/Competitive Programming/out.txt","w",stdout); #endif stack a; int n; cin>>n; string temp; int i; f1(i,0,n) { cin>>temp; if(temp[0]=='a') { a.push(mp(1,1)); } else if(temp[0]=='f') { int num; cin>>num; a.push(mp(0,num)); } else { pair s; int num=0; while(1) { s=a.top(); a.pop(); if(s.ff==0) { if(s.ss*num>maxn) { cout<<"OVERFLOW!!!"; return 0; } a.push(mp(1,s.ss*num)); break; } else { num+=s.ss; if(num>maxn) { cout<<"OVERFLOW!!!"; return 0; } } } } } int ans=0; while(a.empty()!=1) { ans+=a.top().ss; a.pop(); if(ans>maxn) { cout<<"OVERFLOW!!!"; return 0; } } cout<<ans; return 0; }
c++
20
0.472964
82
16.258427
89
starcoderdata
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ml.job.config; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.test.AbstractSerializingTestCase; import org.elasticsearch.xcontent.XContentParser; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; public class BlockedTests extends AbstractSerializingTestCase { @Override protected Blocked doParseInstance(XContentParser parser) throws IOException { return Blocked.STRICT_PARSER.apply(parser, null); } @Override protected Writeable.Reader instanceReader() { return Blocked::new; } @Override protected Blocked createTestInstance() { return createRandom(); } public static Blocked createRandom() { Blocked.Reason reason = randomFrom(Blocked.Reason.values()); TaskId taskId = (reason != Blocked.Reason.NONE && randomBoolean()) ? new TaskId(randomAlphaOfLength(10) + ":" + randomNonNegativeLong()) : null; return new Blocked(reason, taskId); } public void testReasonFromString() { assertThat(Blocked.Reason.fromString("NonE"), equalTo(Blocked.Reason.NONE)); assertThat(Blocked.Reason.fromString("dElETe"), equalTo(Blocked.Reason.DELETE)); assertThat(Blocked.Reason.fromString("ReSEt"), equalTo(Blocked.Reason.RESET)); assertThat(Blocked.Reason.fromString("reVERt"), equalTo(Blocked.Reason.REVERT)); } public void testReasonToString() { List asStrings = Arrays.stream(Blocked.Reason.values()).map(Blocked.Reason::toString).collect(Collectors.toList()); assertThat(asStrings, contains("none", "delete", "reset", "revert")); } }
java
12
0.723648
131
35.366667
60
starcoderdata
TEST_F(Test_ContactData, Serialize) { const auto& data1 = contactData_.AddItem(activeContactItem_); // Serialize without ids. opentxs::proto::ContactData protoData = data1.Serialize(false); ASSERT_EQ(data1.Version(), protoData.version()); ASSERT_EQ(1, protoData.section_size()); opentxs::proto::ContactSection protoSection = protoData.section(0); ASSERT_EQ(opentxs::proto::CONTACTSECTION_IDENTIFIER, protoSection.name()); ASSERT_EQ( data1.Section(opentxs::proto::CONTACTSECTION_IDENTIFIER)->Size(), protoSection.item_size()); opentxs::proto::ContactItem protoItem = protoSection.item(0); ASSERT_EQ(activeContactItem_->Value(), protoItem.value()); ASSERT_EQ(activeContactItem_->Version(), protoItem.version()); ASSERT_EQ(activeContactItem_->Type(), protoItem.type()); ASSERT_EQ(activeContactItem_->Start(), protoItem.start()); ASSERT_EQ(activeContactItem_->End(), protoItem.end()); // Serialize with ids. protoData = data1.Serialize(true); ASSERT_EQ(data1.Version(), protoData.version()); ASSERT_EQ(1, protoData.section_size()); protoSection = protoData.section(0); ASSERT_EQ(opentxs::proto::CONTACTSECTION_IDENTIFIER, protoSection.name()); ASSERT_EQ( data1.Section(opentxs::proto::CONTACTSECTION_IDENTIFIER)->Size(), protoSection.item_size()); protoItem = protoSection.item(0); ASSERT_EQ(activeContactItem_->ID().str(), protoItem.id()); ASSERT_EQ(activeContactItem_->Value(), protoItem.value()); ASSERT_EQ(activeContactItem_->Version(), protoItem.version()); ASSERT_EQ(activeContactItem_->Type(), protoItem.type()); ASSERT_EQ(activeContactItem_->Start(), protoItem.start()); ASSERT_EQ(activeContactItem_->End(), protoItem.end()); }
c++
12
0.694944
78
43.525
40
inline
private void init(){ setFocusable(true); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); Shader s = new BitmapShader(bm, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint.setShader(s);//通过BitmapShader设置Paint的Shader float w = bm.getWidth(); float h = bm.getHeight(); // construct our mesh setXY(mTexs, 0, w/2, h/2); setXY(mTexs, 1, 0, 0); setXY(mTexs, 2, w, 0); setXY(mTexs, 3, w, h); setXY(mTexs, 4, 0, h); //初始化图片纹理映射坐标 setXY(mVerts, 0, w/2, h/2); setXY(mVerts, 1, 0, 0); setXY(mVerts, 2, w, 0); setXY(mVerts, 3, w, h); setXY(mVerts, 4, 0, h);//初始化顶点数据数组 mMatrix.setScale(0.8f, 0.8f); mMatrix.preTranslate(20, 20); mMatrix.invert(mInverse); //初始化变形矩阵 }
java
9
0.541057
64
30.785714
28
inline
package local import ( "context" "github.com/cortexproject/cortex/pkg/chunk" ) type tableClient struct{} // NewTableClient returns a new TableClient. func NewTableClient() (chunk.TableClient, error) { return &tableClient{}, nil } func (c *tableClient) ListTables(ctx context.Context) ([]string, error) { return nil, nil } func (c *tableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error { return nil } func (c *tableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) { return chunk.TableDesc{ Name: name, }, true, nil } func (c *tableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error { return nil }
go
9
0.742025
120
21.53125
32
starcoderdata
--TEST-- Go a hello world routine --FILE-- <?php use \Go\Scheduler; go(function(){ echo "Hello World"; }); Scheduler::join(); ?> --EXPECT-- Hello World
php
9
0.566474
24
8.8125
16
starcoderdata
def process_item(self, item: Mapping, spider: Spider) -> Mapping: """Check whether each item scraped matches the schema :param item: Item to be processed, ignored if not Meeting :param spider: Spider object being run :return: Item with modifications for validation """ if not hasattr(item, "jsonschema"): return item item_dict = dict(item) item_dict["start"] = item_dict["start"].isoformat()[:19] item_dict["end"] = item_dict["end"].isoformat()[:19] validator = Draft7Validator(item.jsonschema) props = list(item.jsonschema["properties"].keys()) errors = list(validator.iter_errors(item_dict)) error_props = self._get_props_from_errors(errors) for prop in props: self.error_count[prop] += 1 if prop in error_props else 0 self.item_count += 1 return item
python
11
0.616998
69
44.35
20
inline
# Input data loading from aocd import get_data start = get_data(year=2017, day=1) total: int = 0 for index_1, char_1 in enumerate(start): index_2 = (index_1 + 1) % len(start) char_2 = start[index_2] if char_1 == char_2: total += int(char_1) print(total)
python
9
0.616487
40
17.6
15
starcoderdata
<?php namespace App\Http\Controllers; use App\blog; use App\category; use App\comments; use Carbon\Carbon; use Illuminate\Http\Request; use Image; class blogController extends Controller { function blogadd(){ $cat = category::all(); return view('backend.blog.blogadd',compact('cat')); } function blogPost(Request $data){ $data->validate([ 'title'=> 'required', 'category_id'=> 'required', 'description'=> 'required', 'blog_image'=> 'required', ]); $slug = str_replace(' ', '_', $data->title); $slug = strtolower($slug); if(blog::where('blog_slug',$slug)->exists()){ $slug = $slug.time(); } if($data->hasFile('blog_image')){ $img = $data->file('blog_image'); $ext = $img->getClientOriginalExtension(); $img_name = $slug.'.'.$ext; Image::make($img)->resize(500, 364)->save(public_path('img/blog'.'/'.$img_name)); } blog::insert([ 'title' => $data->title, 'user_name' => $data->user_name, 'category_id' => $data->category_id, 'description' => $data->description, 'blog_image' => $img_name, 'blog_slug' => $slug, 'created_at' => Carbon::now(), ]); return back()->with('msg', 'Your blog has been published'); } function blogVeiw(){ $blogs = blog::orderBy('created_at', 'desc')->paginate(10); return view('backend.blog.blogVeiw', compact('blogs')); } function blogUpdate($id){ $blog = blog::findOrFail($id); $cat = category::all(); return view('backend.blog.blogUpdate', compact('blog', 'cat')); } function blogUpdatePost(Request $data){ if($data->hasFile('blog_image')){ $blog = blog::findOrFail($data->id); if(file_exists(public_path('img/blog'.'/'.$blog->blog_image))){ unlink(public_path('img/blog'.'/'.$blog->blog_image)); $img = $data->file('blog_image'); $ext = $img->getClientOriginalExtension(); $img_name = $blog->blog_slug.'.'.$ext; Image::make($img)->resize(500,364)->save(public_path('img/blog'.'/'.$img_name)); } } blog::findOrFail($data->id)->update([ 'title' => $data->title, 'category_id' => $data->category_id, 'description' => $data->description, ]); return back()->with('msg', 'Blog is successfully updated'); } function blogComments(){ $comments = comments::orderBy('created_at', 'desc')->paginate(8); return view('backend.blog.blogComments', compact('comments')); } function commentToBlog($id){ $comments = comments::findOrFail($id); if($comments->status == 1){ $comments->increment('status'); } $post_slug = $comments->get_post->blog_slug; return redirect('singleBlog/'.$post_slug.'#'.$id); } function deleteComments($id){ comments::findOrFail($id)->delete(); return back(); } function blogDelete($id){ $blog = blog::findOrFail($id); if(file_exists(public_path('img/blog'.'/'.$blog->blog_image))){ unlink(public_path('img/blog'.'/'.$blog->blog_image)); } $blog->delete(); return back()->with('msg', 'Blog has been deleted'); } }
php
19
0.526404
96
33.413462
104
starcoderdata
# Ep05 - APLICAÇÃO CLIENTE COM UDP from socket import * servidor = "127.0.0.1" # localhost, 192.168.0.1, 10.0.0.1 porta = 43210 obj_socket = socket(AF_INET, SOCK_DGRAM) obj_socket.connect((servidor, porta)) saida = "" while saida != "X": msg = input("Sua mensagem: ") obj_socket.sendto(msg.encode(), (servidor, porta)) dados, origem = obj_socket.recvfrom(65535) print("Resposta do Servidor: ", dados.decode()) saida = input("Digite para sair: "). upper() obj_socket.close()
python
10
0.626186
58
23.095238
21
starcoderdata
<?php if ( ! defined( 'ABSPATH' ) ) exit; /** * Upload page functions * * @author * @package dronespov */ if ( ! class_exists( 'DRONESPOV_UPLOAD' ) ) { class DRONESPOV_UPLOAD { public function get_user_list() { $list = array(); $args = array( 'role' => 'dronespov_client', ); $users = get_users( $args ); foreach ( $users as $user ) { $fname = get_user_meta($user->ID, 'first_name', true); $lname = get_user_meta($user->ID, 'last_name', true); $company = get_user_meta($user->ID, '_company', true); $list[] = array( 'id' => $user->ID, 'name' => $fname . ' ' . $lname, 'company' => $company); } return $list; } public function get_project_list() { $projects = array(); global $wpdb; $table = $wpdb->prefix . 'dronespov_invoices'; $fetch = $wpdb->get_results( $wpdb->prepare( "SELECT project FROM $table" ), ARRAY_A ); foreach ($fetch as $item) { $projects[] = base64_decode($item['project']); } return array_unique($projects); } public function get_items_list() { $items = array(); global $wpdb; $table = $wpdb->prefix . 'dronespov_invoices'; $fetch = $wpdb->get_results( $wpdb->prepare( "SELECT row FROM $table" ), ARRAY_A ); foreach ($fetch as $item) { $row = maybe_unserialize($item['row']); if (is_array($row)) { foreach ($row as $key => $value) { foreach ($value as $i => $elem) { $items[] = $i; } } } } return array_unique($items); } public function get_tax_list() { $items = array(); global $wpdb; $table = $wpdb->prefix . 'dronespov_invoices'; $fetch = $wpdb->get_results( $wpdb->prepare( "SELECT tax FROM $table" ), ARRAY_A ); foreach ($fetch as $item) { $items[] = $item['tax']; } return array_unique($items); } public function editable_data() { if (isset($_REQUEST['edit'])) { $invoice_id = $_REQUEST['edit']; } if (!$invoice_id) { return false; } global $wpdb; $table = $wpdb->prefix . 'dronespov_invoices'; $fetch = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $table WHERE ID = %d", $invoice_id), ARRAY_A ); if (isset($fetch[0]) && !empty($fetch[0])) { return $fetch[0]; } else { return false; } } } }
php
19
0.544092
109
18.147541
122
starcoderdata
package command import ( "context" "errors" "go.minekube.com/brigodier" "go.minekube.com/common/minecraft/component" "go.minekube.com/gate/pkg/util/permission" "strings" ) // Manager is a command manager for // registering and executing proxy commands. type Manager struct{ brigodier.Dispatcher } // Source is the invoker of a command. // It could be a player or the console/terminal. type Source interface { permission.Subject // SendMessage sends a message component to the invoker. SendMessage(msg component.Component) error } // SourceFromContext retrieves the Source from a command's context. func SourceFromContext(ctx context.Context) Source { s := ctx.Value(sourceCtxKey) if s == nil { return nil } src, _ := s.(Source) return src } // ContextWithSource returns a new context including the specified Source. func ContextWithSource(ctx context.Context, src Source) context.Context { return context.WithValue(ctx, sourceCtxKey, src) } // Context wraps the context for a brigodier.Command. type Context struct { *brigodier.CommandContext Source } func createContext(c *brigodier.CommandContext) *Context { return &Context{ CommandContext: c, Source: SourceFromContext(c), } } // RequiresContext wraps the context for a brigodier.RequireFn. type RequiresContext struct { context.Context Source } // Command wraps the context for a brigodier.Command. func Command(fn func(c *Context) error) brigodier.Command { return brigodier.CommandFunc(func(c *brigodier.CommandContext) error { return fn(createContext(c)) }) } // Requires wraps the context for a brigodier.RequireFn. func Requires(fn func(c *RequiresContext) bool) func(context.Context) bool { return func(ctx context.Context) bool { return fn(&RequiresContext{ Context: ctx, Source: SourceFromContext(ctx), }) } } // ParseResults are the parse results of a parsed command input. // // It overlays brigodier.ParseResults to make clear that Manager.Execute // must only get parse results returned by Manager.Parse. type ParseResults brigodier.ParseResults // Parse stores a required command invoker Source in ctx, // parses the command and returns parse results for use with Execute. func (m *Manager) Parse(ctx context.Context, src Source, command string) *ParseResults { return m.ParseReader(ctx, src, &brigodier.StringReader{String: command}) } // ParseReader stores a required command invoker Source in ctx, // parses the command and returns parse results for use with Execute. func (m *Manager) ParseReader(ctx context.Context, src Source, command *brigodier.StringReader) *ParseResults { ctx = ContextWithSource(ctx, src) return (*ParseResults)(m.Dispatcher.ParseReader(ctx, command)) } var ErrForward = errors.New("forward command") // Do does a Parse and Execute. func (m *Manager) Do(ctx context.Context, src Source, command string) error { return m.Execute(m.Parse(ctx, src, command)) } // Execute ensures parse context has a Source and executes it. func (m *Manager) Execute(parse *ParseResults) error { if SourceFromContext(parse.Context) == nil { return errors.New("context misses command source") } return m.Dispatcher.Execute((*brigodier.ParseResults)(parse)) } // Has indicates whether the specified command/alias is registered. func (m *Manager) Has(command string) bool { _, ok := m.Dispatcher.Root.Children()[strings.ToLower(command)] return ok } // CompletionSuggestions returns completion suggestions. func (m *Manager) CompletionSuggestions(parse *ParseResults) (*brigodier.Suggestions, error) { return m.Dispatcher.CompletionSuggestions((*brigodier.ParseResults)(parse)) } // OfferSuggestions returns completion suggestions. func (m *Manager) OfferSuggestions(ctx context.Context, source Source, cmdline string) ([]string, error) { suggestions, err := m.CompletionSuggestions(m.Parse(ctx, source, cmdline)) if err != nil { return nil, err } s := make([]string, 0, len(suggestions.Suggestions)) for _, suggestion := range suggestions.Suggestions { s = append(s, suggestion.Text) } return s, nil } type sourceCtx struct{} var sourceCtxKey = &sourceCtx{}
go
18
0.755828
111
29.595588
136
starcoderdata
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation */ @interface NSExtensionContext : NSObject <NSCopying, NSSecureCoding, NSXPCListenerDelegate, _NSExtensionAuxHostingBase> { NSUUID * __UUID; NSXPCConnection * __auxiliaryConnection; NSXPCListener * __auxiliaryListener; BOOL __dummyExtension; * __extensionHostProxy; * __extensionVendorProxy; id __principalObject; id __requestCleanUpBlock; NSObject * __transaction; NSArray * _inputItems; } @property (atomic, readwrite, copy) NSUUID *_UUID; @property (setter=_setAuxiliaryConnection:, atomic, readwrite, retain) NSXPCConnection *_auxiliaryConnection; @property (setter=_setAuxiliaryListener:, atomic, readwrite, retain) NSXPCListener *_auxiliaryListener; @property (getter=_isDummyExtension, setter=_setDummyExtension:, atomic, readwrite) BOOL _dummyExtension; @property (setter=_setExtensionHostProxy:, atomic, readwrite, retain) *_extensionHostProxy; @property (setter=_setExtensionVendorProxy:, atomic, readwrite, retain) *_extensionVendorProxy; @property (setter=_setPrincipalObject:, atomic, readwrite) id _principalObject; @property (setter=_setRequestCleanUpBlock:, atomic, readwrite, copy) id _requestCleanUpBlock; @property (getter=_transaction, setter=_setTransaction:, atomic, readwrite, retain) NSObject *_transaction; @property (atomic, readonly, copy) NSString *debugDescription; @property (atomic, readonly, copy) NSString *description; @property (atomic, readonly) unsigned long long hash; @property (setter=_setInputItems:, atomic, readwrite, copy) NSArray *inputItems; @property (atomic, readonly) Class superclass; + (id)_allowedErrorClasses; + (id)_defaultExtensionContextProtocol; + (id)_defaultExtensionContextVendorProtocol; + (id)_extensionAuxiliaryHostProtocol; + (id)_extensionAuxiliaryVendorProtocol; + (id)_extensionContextHostProtocolAllowedClassesForItems; + (id)_extensionContextHostProtocolWithAllowedErrorClasses:(id)arg1; + (id)_extensionContextVendorProtocolWithAllowedErrorClasses:(id)arg1; + (void)initialize; + (BOOL)supportsSecureCoding; - (id)_UUID; - (void)___nsx_pingHost:(id)arg1; - (id)_auxiliaryConnection; - (id)_auxiliaryListener; - (void)_completeRequestReturningItemsSecondHalf:(id)arg1; - (id)_derivedExtensionAuxiliaryHostProtocol; - (id)_extensionHostProxy; - (id)_extensionVendorProxy; - (BOOL)_isDummyExtension; - (BOOL)_isHost; - (void)_loadItemForPayload:(id)arg1 completionHandler:(id)arg2; - (void)_loadPreviewImageForPayload:(id)arg1 completionHandler:(id)arg2; - (void)_openURL:(id)arg1 completion:(id)arg2; - (id)_principalObject; - (id)_requestCleanUpBlock; - (void)_setAuxiliaryConnection:(id)arg1; - (void)_setAuxiliaryListener:(id)arg1; - (void)_setDummyExtension:(BOOL)arg1; - (void)_setExtensionHostProxy:(id)arg1; - (void)_setExtensionVendorProxy:(id)arg1; - (void)_setInputItems:(id)arg1; - (void)_setPrincipalObject:(id)arg1; - (void)_setRequestCleanUpBlock:(id)arg1; - (void)_setTransaction:(id)arg1; - (id)_transaction; - (void)_willPerformHostCallback:(id)arg1; - (void)cancelRequestWithError:(id)arg1; - (void)completeRequestReturningItems:(id)arg1 completionHandler:(id)arg2; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (void)dealloc; - (id)description; - (void)didConnectToVendor:(id)arg1; - (void)encodeWithCoder:(id)arg1; - (id)init; - (id)initWithCoder:(id)arg1; - (id)initWithInputItems:(id)arg1; - (id)initWithInputItems:(id)arg1 contextUUID:(id)arg2; - (id)initWithInputItems:(id)arg1 listenerEndpoint:(id)arg2 contextUUID:(id)arg3; - (id)inputItems; - (void)invalidate; - (BOOL)listener:(id)arg1 shouldAcceptNewConnection:(id)arg2; - (void)openURL:(id)arg1 completionHandler:(id)arg2; - (void)set_UUID:(id)arg1; // NSExtensionContext (NSVendorSupport) + (id)_extensionContextForIdentifier:(id)arg1; @end
c
7
0.772615
126
42.505376
93
starcoderdata
package csp //#include "common.h" import "C" import ( "unsafe" ) // CertInfo encapsulates certificate properties type CertInfo struct { pCertInfo C.PCERT_INFO } // Info extracts CertInfo from Cert func (c Cert) Info() CertInfo { return CertInfo{c.pCert.pCertInfo} } // SignatureAlgorithm returns certificate signature algorithm as object ID // string func (ci CertInfo) SignatureAlgorithm() string { return C.GoString((*C.char)(unsafe.Pointer(ci.pCertInfo.SignatureAlgorithm.pszObjId))) } // PublicKeyAlgorithm returns certificate subject public key algorithm as // object ID string func (ci CertInfo) PublicKeyAlgorithm() string { return C.GoString((*C.char)(unsafe.Pointer(ci.pCertInfo.SubjectPublicKeyInfo.Algorithm.pszObjId))) } // PublicKeyBytes returns certificate subject public key as byte slice func (ci CertInfo) PublicKeyBytes() []byte { pb := ci.pCertInfo.SubjectPublicKeyInfo.PublicKey return C.GoBytes(unsafe.Pointer(pb.pbData), C.int(pb.cbData)) } func nameToStr(src C.PCERT_NAME_BLOB) (string, error) { slen := C.CertNameToStr(C.X509_ASN_ENCODING, src, C.CERT_X500_NAME_STR, nil, 0) data := make([]byte, slen) cStrPtr := (*C.CHAR)(unsafe.Pointer(&data[0])) if n := C.CertNameToStr(C.X509_ASN_ENCODING, src, C.CERT_X500_NAME_STR, cStrPtr, slen); n == 0 { return "", getErr("Error converting RDN to string") } return C.GoString((*C.char)(cStrPtr)), nil } // SubjectStr returns certificate subject converted to Go string func (ci CertInfo) SubjectStr() (string, error) { return nameToStr(&ci.pCertInfo.Subject) } // IssuerStr returns certificate issuer converted to Go string func (ci CertInfo) IssuerStr() (string, error) { return nameToStr(&ci.pCertInfo.Issuer) }
go
15
0.744431
99
29.464286
56
starcoderdata
// jhcObjList.h : manages a collection of visible objects // // Written by // /////////////////////////////////////////////////////////////////////////// // // Copyright 2011-2015 IBM Corporation // // 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. // /////////////////////////////////////////////////////////////////////////// #ifndef _JHCOBJLIST_ /* CPPDOC_BEGIN_EXCLUDE */ #define _JHCOBJLIST_ /* CPPDOC_END_EXCLUDE */ #include "jhcGlobal.h" #include "Data/jhcBlob.h" #include "Data/jhcImg.h" #include "Data/jhcParam.h" #include "Processing/jhcDraw.h" #include "Objects/jhcVisObj.h" //= Manages a collection of visible objects. class jhcObjList : private jhcDraw { // PRIVATE MEMBER VARIABLES private: jhcVisObj *item, *prev, *tell; int iw, ih; // PUBLIC MEMBER VARIABLES public: // qualitative color jhcParam cps; int clim[6]; double agree; // PUBLIC MEMBER FUNCTIONS public: // creation and configuration jhcObjList (); ~jhcObjList (); int Defaults (const char *fname =NULL); int SaveVals (const char *fname) const; void Reset (); // main functions int ParseObjs (const jhcBlob& blob, const jhcImg& comps, const jhcImg& src); // object properties int ObjCount (); void Rewind (); jhcVisObj *Next (); jhcVisObj *GetObj (int n); jhcVisPart *ObjPart (int n, const char *sub =NULL); const jhcImg *GetMask (int n =1, const char *sub =NULL); const jhcImg *GetCrop (int n =1, const char *sub =NULL); const jhcArr *GetHist (int n =1, const char *sub =NULL); const jhcArr *GetCols (jhcArr& dest, int n =1, const char *sub =NULL); const char *MainColor (int cnum, int n =1, const char *sub =NULL); const char *SubColor (int cnum, int n =1, const char *sub =NULL); int GraspPoint (double &x, double& y, double& wid, double& ang, int n =1); int ModelVec (jhcArr& mod, int n =1, const char *sub =NULL); int ModelVec (jhcArr& mod, jhcVisObj *t, const char *sub =NULL); // object status int NumChoices (); int TopMark (); int TargetID (); char *TargetName (); jhcVisObj *TargetObj (); int SwapTop (); void ClearObjs (); int RestoreObjs (); // object rejection int MarkNearest (int x, int y); int KeepColor (const char *want, int alt =0); int HasOnlyColor (const char *want, int rem =1); int HasMainColor (const char *want, int rem =1); int HasColor (const char *want, int rem =1); // object preferences int PickOne (int inc =1); int MostColor (const char *want, int inc =1); int Biggest (int inc =1); int Littlest (int inc =1); int MediumSized (int inc =1); int Leftmost (int inc =1); int Rightmost (int inc =1); int InMiddle (int inc =1); // debugging graphics int DrawGrasp (jhcImg& dest, int n =1, int tail =20, int t =1, int r =255, int g =0, int b =255); int ColorObj (jhcImg& dest, int n); // PRIVATE MEMBER FUNCTIONS private: int col_params (const char *fname); void backup_items (); void clr_list (jhcVisObj *head); void track_names (); int get_grasp (double &x, double& y, double& wid, double& ang, const jhcBlob& blob, const jhcImg& comps, int i); int color_bin (int hue); }; #endif // once
c
11
0.644782
78
26.551471
136
starcoderdata
@Override public boolean isDone() { // If we have a delegate, just delegate. Future<T> delegate = this.delegate; if (delegate != null) { return delegate.isDone(); } // If we don't have a delegate, use the cancel state. Note: We could have a delegate by the time we assess the cancel // state, but customers cannot rely on that strict of ordering, anyway. return cancelState != CancelState.NOT_CANCELLED; }
java
8
0.622407
125
39.25
12
inline
/*------------------------------------------------------------------------- * * pg_tidycat.h * * Copyright (c) 2011 Greenplum inc. * * WARNING: DO NOT MODIFY THIS FILE: * Generated by ./tidycat.pl version 31 * on Thu Sep 1 16:43:17 2011 *------------------------------------------------------------------------- */ #include "catalog/pg_attribute_encoding.h" #include "catalog/pg_auth_time_constraint.h" #include "catalog/pg_compression.h" #include "catalog/pg_foreign_data_wrapper.h" #include "catalog/pg_foreign_server.h" #include "catalog/pg_foreign_table.h" #include "catalog/pg_proc_callback.h" #include "catalog/pg_partition_encoding.h" #include "catalog/pg_type_encoding.h"
c
3
0.562232
75
30.772727
22
starcoderdata
@Override public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator) { return PlanRewriter.rewriteWith(new PlanRewriter<Void>() { @Override public PlanNode visitJoin(JoinNode node, RewriteContext<Void> context) { if (node.getType() != JoinNode.Type.RIGHT) { return context.defaultRewrite(node); } // return a new join node with "left" swapped with "right" return new JoinNode(node.getId(), JoinNode.Type.LEFT, context.rewrite(node.getRight()), context.rewrite(node.getLeft()), node.getCriteria().stream() .map(criteria -> new JoinNode.EquiJoinClause(criteria.getRight(), criteria.getLeft())) .collect(toImmutableList()), node.getRightHashSymbol(), node.getLeftHashSymbol()); } }, plan); }
java
21
0.52253
151
45.2
25
inline
/* * Copyright (c) 2020-Now Asako Studio. All rights reseved. * @fileoverview | 图表种类配置,http://doc.ucharts.cn/1172125 * @Author: mukuashi | * @version 0.1 | 2020-06-10 // Initial version. * @Date: 2020-06-10 10:20:27 * @Last Modified by: mukuashi * @Last Modified time: 2021-03-01 17:20:40 */ import app from './index'; const { colors } = app.theme; // 所有图表全局默认配置 const chartsTpl = { fontSize: 10, padding: [0, 4, 0, 0], colors, animation: true, // 是否动画展示 duration: 500, dataLabel: true, // 是否在图表中显示数据标签内容值 dataPointShape: false, // 是否在图表中显示数据点图形标识 legend: { position: 'top', float: 'right', fontSize: 12, margin: 24, }, extra: { tooltip: { showBox: true, gridColor: '#E7E8E7', }, }, xAxis: { disableGrid: true, // 不绘制X轴网格 axisLine: false, }, yAxis: { splitNumber: 4, data: [ { axisLine: false, // 不绘制y轴,仅显示数据刻度 }, ], fontColor: 'rgba(0,0,0,0.65)', gridColor: 'rgba(0,0,0,0.04)', }, }; export default { /** * column 柱状图 */ column: { ...chartsTpl, type: 'column', yAxis: { ...chartsTpl.yAxis, data: [ { disabled: true, }, ], }, }, /** * 折线图 */ line: { ...chartsTpl, type: 'line', dataLabel: false, }, /** * 环状图 */ ring: { ...chartsTpl, type: 'ring', dataLabel: false, extra: { pie: { offsetAngle: 0, ringWidth: 40, labelWidth: 15, }, }, legend: { float: 'center', position: 'right', lineHeight: 30, }, }, };
javascript
12
0.519208
59
16.354167
96
starcoderdata
public static List<FoodItem> intersectLists(List<List<FoodItem>> foodLists) { Iterator<List<FoodItem>> iterator = foodLists.iterator(); List<FoodItem> intersectedList; if(iterator.hasNext()) { intersectedList = new ArrayList<FoodItem>(iterator.next()); //need to copy list to avoid changing what was passed in while(iterator.hasNext()) { List<FoodItem> curList = iterator.next(); intersectedList.retainAll(curList); } return intersectedList; } return new ArrayList<FoodItem>(); }
java
11
0.69145
77
29.764706
17
inline
let markdown = require('markdown').markdown; let fs = require('fs'); let read = fs.readFile('./1.md','utf8',function (err, result) { let html = markdown.toHTML(result,'Maruku'); fs.writeFileSync('./2.html', html, 'utf8'); }); // console.log(markdown.toHTML(read,null,'utf8'));
javascript
12
0.65035
63
30.888889
9
starcoderdata
import logging import sys import argparse import time import orwell.shooter.scenario as scen def main(argv=sys.argv[1:]): parser = argparse.ArgumentParser(description='Scenario shooter.') parser.add_argument('scenario_file', help='YAML scenario file.') parser.add_argument( '--delay', '-d', help='Delay between steps.', default=0, action="store", metavar="DELAY", type=int) parser.add_argument( '--verbose', '-v', help='Verbose mode', default=False, action="store_true") arguments = parser.parse_args() log = logging.getLogger(__name__) handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) log.addHandler(handler) if arguments.verbose: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) scen.configure_logging(arguments.verbose) scenario_file = arguments.scenario_file delay = arguments.delay log.debug('Open file "{}" as YAML scenario.'.format(scenario_file)) log.debug('Time to wait between steps (-d): {}'.format(delay)) with open(scenario_file, 'r') as yaml_scenario: yaml_content = yaml_scenario.read() with scen.Scenario(yaml_content) as scenario: scenario.build() while scenario.has_more_steps: log.debug("step") scenario.step() time.sleep(delay) if "__main__" == __name__: sys.exit(main(sys.argv[1:])) # pragma: no coverage
python
13
0.623214
71
31.307692
52
starcoderdata
void Region::append(SP_surface s, bool sense) { Require(s); SP_node n(new CSG_Primitive(s, sense)); // Surfaces are only added via intersection, as sense contains enough append_node(d_node, n, INTERSECTION); }
c++
8
0.714286
71
30.142857
7
inline
/** * @class HowItWorks * @description App features explainer. * - Made for * @extends HTMLElement */ class HowItWorks extends HTMLElement { connectedCallback() { this.renderInnerHTML(); } renderInnerHTML() { this.innerHTML = /*html*/` does it work? <img src="/static/img/lightning.svg" alt="Lightning bolt" aria-hidden="true"/> Provide a file containing EEG data where each row is a sequence of <a href="/static/img/data-format.png" title="More information on the Expected data format">500 samples at 100 Hz Try the app with a <a href="/static/samples/sample_149_sequences_with_seizures.csv" title="Get a sample EEG file">sample CSV file <img src="/static/img/server.svg" alt="Server" aria-hidden="true"/> The app will read the file and send it by chunks to our server, where our learning algorithm runs. Nothing is stored on our end. <img src="/static/img/graph.svg" alt="Chart" aria-hidden="true"/> Once the whole file has been processed, the app generates a visualization allowing editing and export of the results `; } } customElements.define('how-it-works', HowItWorks);
javascript
5
0.603532
240
31.215686
51
starcoderdata
'use strict'; /** * Module dependencies. */ var validator = require('validator'); var crypto = require('crypto'); var _ = require('lodash'); var uid = require('uid-safe'); var mongoose = require('mongoose'); /** * Hook a pre save method to hash the password */ var preSave = function (next) { if (this.password && this.isModified('password') && this.password.length >= 6) { this.salt = crypto.randomBytes(16).toString('base64'); this.password = this.hashPassword(this.password); } if (this.userGuid === undefined || this.userGuid.trim() === '') { this.userGuid = 'ESM-' + uid.sync(18); } next(); }; /** * Create instance method for hashing a password */ var newMethods = {}; var newStatics = {}; newMethods.hashPassword = function (password) { if (this.salt && password) { return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 64).toString('base64'); } else { return password; } }; /** * Create instance method for authenticating user */ newMethods.authenticate = function (password) { return this.password === this.hashPassword(password); }; newMethods.modRoles = function (method, rolearray) { if (method === 'add') { this.roles = _.union (this.roles, rolearray); } else if (method === 'remove') { _.remove (this.roles, function (code) { return _.indexOf (rolearray, code) !== -1; }); } else { this.roles = _.union ([], rolearray); } }; /** * Find possible not used username */ newStatics.findUniqueUsername = function (username, suffix, callback) { var _this = this; var possibleUsername = username.toLowerCase() + (suffix || ''); _this.findOne({ username: possibleUsername }, function (err, user) { if (!err) { if (!user) { callback(possibleUsername); } else { return _this.findUniqueUsername(username, (suffix || 0) + 1, callback); } } else { callback(null); } }); }; newStatics.validateEmail = function (email) { var _this = this; if (!_.isEmpty(email)) { if (validator.isEmail(email)) { // see if unique.. mongoose.model ('User').findOne({ email: new RegExp(email.trim(), 'i') }, function (err, user) { if (!err) { if (!user) { return true; } else { // not unique.. return _this._id.toString() === user._id.toString(); } } else { return false; } }); } else { return false; } } else { return true; } }; module.exports = require ('../../../core/server/controllers/core.schema.controller')('User', { __audit : true, firstName : { type: String, trim: true, default: ''}, middleName : { type: String, trim: true, default: null}, lastName : { type: String, trim: true, default: ''}, displayName : { type: String, trim: true }, email : { type: String, trim: true, default: '' }, username : { type: String, unique: 'Username already exists', required: 'Please fill in a username', lowercase: true, trim: true }, password : { type: String, default: '' }, salt : { type: String }, provider : { type: String }, providerData : {}, additionalProvidersData : {}, roles : [{ type: String}], oldroles : [{ type: String}], updated : { type: Date }, created : { type: Date, default: Date.now }, /* For reset password */ resetPasswordToken : { type: String }, resetPasswordExpires : { type: Date }, //contactName : { type:String, default: '' }, REPLACED WITH DISPLAYNAME //code : type:String, default: ''}, REPLACED WITH USERNAME org : { type:'ObjectId', ref:'Organization', default:null, index:true }, orgName : { type:String, default: '' }, personId : { type:Number, default: null }, // From ePIC title : { type:String, default: '' }, homePhoneNumber : { type:String, default: '' }, phoneNumber : { type:String, default: '' }, // if groupId = null, then this is a person (hack) eaoStaffFlag : { type:Boolean, default: false }, proponentFlag : { type:Boolean, default: false }, salutation : { type:String, default: '' }, department : { type:String, default: '' }, faxNumber : { type:String, default: '' }, cellPhoneNumber : { type:String, default: '' }, address1 : { type:String, default: '' }, address2 : { type:String, default: '' }, city : { type:String, default: '' }, province : { type:String, default: '' }, country : { type:String, default: '' }, postalCode : { type:String, default: '' }, notes : { type:String, default: '' }, signature : { type:'ObjectId', default: null, ref:'Document' }, // contact viaEmail : { type:Boolean, default: true }, viaMail : { type:Boolean, default: false }, // Siteminder User Guid - smgov_userguid header userGuid : { type: String, unique: 'User GUID already exists', lowercase: true, trim: true }, // Siteminder User Type - smgov_usertype header userType : { type: String, unique: false, lowercase: true, trim: true, default: '' }, presave__ : preSave, methods__ : newMethods, statics__ : newStatics });
javascript
21
0.540545
148
33.295858
169
starcoderdata
#include "LazyBuffer.h" #include #include #include CLazyBuffer::CLazyBuffer() : mAllocatedSize(0), mCurrentSize(0), mpBuffer(NULL) { } CLazyBuffer::~CLazyBuffer() { cleanUpBuffer(); } CLazyBuffer::CLazyBuffer( const CLazyBuffer& rhs ) : mAllocatedSize(0), mCurrentSize(0), mpBuffer(NULL) { } CLazyBuffer& CLazyBuffer::operator=( const CLazyBuffer& rhs) { mAllocatedSize = 0; mCurrentSize = 0; mpBuffer = NULL; return (*this); } void CLazyBuffer::Copy(const char* pBuffer, const int length) { const bool bValidBuffer = pBuffer != NULL; const bool bValidLength = length > 0; assert(bValidBuffer); assert(bValidLength); if (bValidBuffer && bValidLength) { Resize(length); mCurrentSize = length; std::memcpy(mpBuffer, pBuffer, length); } } void CLazyBuffer::SubCopy(const char* pBuffer, const int length, const int offset) { const bool bValidBuffer = pBuffer != NULL; const bool bValidLength = length > 0; const bool bValidSize = (offset + length) <= mCurrentSize; assert(bValidBuffer); assert(bValidLength); assert(bValidSize); if (bValidBuffer && bValidLength && bValidSize) { std::memcpy(mpBuffer + offset, pBuffer, length); } } void CLazyBuffer::Resize (const int length) { const bool bValidLength = length >= 0; assert(bValidLength); if (bValidLength) { if (mAllocatedSize < length) { cleanUpBuffer(); mpBuffer = new char[length]; mAllocatedSize = length; } } } void CLazyBuffer::SetCurrentSize(const int length) { Resize(length); mCurrentSize = length; } void CLazyBuffer::cleanUpBuffer() { if (mpBuffer) { delete[] (mpBuffer); } } char* CLazyBuffer::Pointer() const { return (mpBuffer); } int CLazyBuffer::Size() const { return (mCurrentSize); }
c++
11
0.697687
82
15.518182
110
starcoderdata
package com.ctrip.hermes.kafka.producer; import org.apache.kafka.clients.producer.RecordMetadata; import com.ctrip.hermes.core.result.CompletionCallback; import com.ctrip.hermes.core.result.SendResult; public class KafkaCallback implements org.apache.kafka.clients.producer.Callback { private CompletionCallback m_callback; public KafkaCallback(CompletionCallback callback) { this.m_callback = callback; } @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (m_callback != null) { if (exception != null) { m_callback.onFailure(exception); } else { KafkaSendResult result = new KafkaSendResult(); result.setTopic(metadata.topic()); result.setPartition(metadata.partition()); result.setOffset(metadata.offset()); m_callback.onSuccess(result); } } } }
java
14
0.762156
87
29.516129
31
starcoderdata
//===- OptionPool.h -------------------------------------------------------===// // // The ONNC Project // // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef ONNC_OPTION_OPTION_POOL_H #define ONNC_OPTION_OPTION_POOL_H #include #include namespace onnc { namespace cl { /** \class OptionPool * \brief OptionPool is a string map used to look up OptDefs. */ class OptionPool { public: typedef StringMap MapType; public: /// lookup - Look up the option specified by the specified option on /// the command line. This assumes the leading dashes are stripped. /// /// Normal options, such as kLong and kShort will be found first, the /// prefix options. /// /// @param [in] pArg The argument on the command line /// @param [out] pName The name of the argument /// @param [out] pValue The corresponding value /// @return OptDefs* The corresponding OptDefs OptDefs* lookup(StringRef pArg, StringRef& pName, StringRef& pValue); OptDefs* guess(StringRef& pName, StringRef& pValue); void record(OptDefs& pInfo); private: /// LookupSimple - Look up simple options OptDefs* LookupSimple(StringRef& pArg, StringRef& pValue); /// LookupPrefix - Look up options with specified prefix OptDefs* LookupPrefix(StringRef& pArg, StringRef& pValue); /// LookupNearest - Look up options who is nearest by the requests. OptDefs* LookupNearest(StringRef& pArg, StringRef& pValue); private: MapType m_Map; }; } // namespace of cl } // namespace of onnc #endif
c
14
0.633999
80
27.5
58
starcoderdata
#include #include #include #include "aux.h" #include "omp.h" #define MAX_THREADS 8 #define MAXIT 1000000 double sequential_minimization(double s, int p, double x0, double y0); double parallel_minimization(double s, int p, double x0, double y0); int main(int argc, char **argv){ long t_start, t_end; double s, x0, y0, z; int i, p; // Command line argument: array length if ( argc == 3 ) { p = atoi(argv[1]); /* the number of points to be evaluated */ s = atof(argv[2]); /* the step length */ } else { printf("Usage:\n\n ./main p s\n\nwhere p is the number of points around the current minimum where the function has to be evaluated\nand s is the step size.\n"); return 1; } /* No need to change this seetings unless for debugging */ x0 = 10; y0 = 10; t_start = usecs(); z = sequential_minimization(s, p, x0, y0); t_end = usecs(); printf("Sequential time : %8.2f msec.\n",((double)t_end-t_start)/1000.0); printf("\n\n"); t_start = usecs(); z = parallel_minimization(s, p, x0, y0); t_end = usecs(); printf("Parallel time : %8.2f msec.\n",((double)t_end-t_start)/1000.0); return 0; } double sequential_minimization(double s, int p, double x0, double y0){ int cnt, i; double z, x, y, nx, ny, nz; double xyz[MAX_THREADS][3]; xyz[0][0] = x0; xyz[0][1]=y0; xyz[0][2] = evaluate(xyz[0][0], xyz[0][1]); for(cnt=0;cnt<MAXIT;cnt++){ x = xyz[0][0]; y = xyz[0][1]; z = xyz[0][2]; /* Evaluate function on the 8 points around the current minimum */ /* The current minimum is included again in the evaluation for simplicipy; this makes a total of 9 evaluations */ for(i=0; i<p; i++){ nx = x+ s*cos(2.0*M_PI*i/((double)p)); ny = y+ s*sin(2.0*M_PI*i/((double)p)); nz = evaluate(nx,ny); /* printf("%f %f %f\n",nx,ny,nz); */ /* If the evaluation at this point is lower than the current minimum, set this point as the new minimum */ if(nz<xyz[0][2]){ xyz[0][2] = nz; xyz[0][0] = nx; xyz[0][1] = ny; } } /* Uncomment the line below if you want to debug */ /* printf("%4d -- %5.2f %5.2f %10.4f\n",cnt,xyz[0][0], xyz[0][1], xyz[0][2]); */ /* If no improvement over the old minimum, terminate */ if(xyz[0][2]>=z) break; } printf("Minimum found is %.10f at x=%.4f, y=%.4f in %d steps\n",xyz[0][2],xyz[0][0],xyz[0][1],cnt); return xyz[0][2]; } double parallel_minimization(double s, int p, double x0, double y0){ int cnt, i; double z, x, y, nx, ny, nz; double xyz[MAX_THREADS][3]; xyz[0][0] = x0; xyz[0][1]=y0; xyz[0][2] = evaluate(xyz[0][0], xyz[0][1]); { for(cnt=0;cnt<MAXIT;cnt++){ x = xyz[0][0]; y = xyz[0][1]; z = xyz[0][2]; /* Evaluate function on the 8 points around the current minimum */ /* The current minimum is included again in the evaluation for simplicipy; this makes a total of 9 evaluations */ #pragma omp parallel for private(nx, ny, nz) for(i=0; i<p; i++){ { nx = x+ s*cos(2.0*M_PI*i/((double)p)); ny = y+ s*sin(2.0*M_PI*i/((double)p)); nz = evaluate(nx,ny); /* printf("%f %f %f\n",nx,ny,nz); */ /* If the evaluation at this point is lower than the current minimum, set this point as the new minimum */ if(nz<xyz[0][2]){ xyz[0][2] = nz; xyz[0][0] = nx; xyz[0][1] = ny; } } } /* Uncomment the line below if you want to debug */ /* printf("%4d -- %5.2f %5.2f %10.4f\n",cnt,xyz[0][0], xyz[0][1], xyz[0][2]); */ /* If no improvement over the old minimum, terminate */ if(xyz[0][2]>=z) break; } } printf("Minimum found is %.10f at x=%.4f, y=%.4f in %d steps\n",xyz[0][2],xyz[0][0],xyz[0][1],cnt); return xyz[0][2]; }
c
19
0.561063
164
28.208955
134
starcoderdata
using COSXML.Model.Tag; using COSXML.Transfer; using System; using System.Collections.Generic; using System.Text; namespace COSXML.Model.Bucket { public sealed class GetBucketLoggingResult : CosDataResult { public BucketLoggingStatus bucketLoggingStatus { get{ return _data; } } } }
c#
10
0.711816
83
22.133333
15
starcoderdata
package fr.hozakan.materialdesigncolorpalette.dagger; import android.content.ClipboardManager; import android.content.Context; import com.squareup.otto.Bus; import com.squareup.otto.ThreadEnforcer; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import fr.hozakan.materialdesigncolorpalette.color_list.ColorPaletteActivity; import fr.hozakan.materialdesigncolorpalette.color_list.PaletteFragment; import fr.hozakan.materialdesigncolorpalette.preview.PreviewFragment; import fr.hozakan.materialdesigncolorpalette.service.PaletteService; /** * Created by gimbert on 2014-08-11. */ @Module(injects = { ColorPaletteActivity.class, PaletteFragment.class, PreviewFragment.class }, library = true) public class PaletteColorModule { private final BaseApplication mApp; public PaletteColorModule(BaseApplication app) { mApp = app; } @Provides public Context provideContext() { return mApp.getApplicationContext(); } @Provides public PaletteService providePaletteService(Context context, Bus bus) { return new PaletteService(context, bus); } @Provides @Singleton public Bus provideBus() { return new Bus(ThreadEnforcer.ANY); } @Provides public ClipboardManager provideClipboardManager() { return (ClipboardManager) mApp.getSystemService(Context.CLIPBOARD_SERVICE); } }
java
8
0.724205
83
25.052632
57
starcoderdata
(function () { function ModalCtrl($uibModal) { this.createRoom = function() { var modal = $uibModal.open({ templateUrl: 'templates/modal.html', controllerAs: 'modalInstance', controller: function($uibModalInstance) { this.roomName = ""; var addRoom = function(name) { Room.createRoom() console.log(name); }; this.ok = function(){ $uibModalInstance.close(this.roomName); }; this.cancel = function() { $uibModalInstance.dismiss('cancel') }; }, size: 'sm' }); modal.result.then(function (name) { firebase.database().ref().child("rooms").push({ "name": name }) }); } } angular .module('blocChat') .controller('ModalCtrl', ['$uibModal', ModalCtrl]) })();
javascript
29
0.521047
71
24.852941
34
starcoderdata
namespace BettingSystem.Application.Games.Teams { using System.IO; using System.Threading; using System.Threading.Tasks; using Common.Contracts; using Domain.Games.Models.Teams; public interface ITeamQueryRepository : IQueryRepository { Task GetThumbnailLogo( int teamId, CancellationToken cancellationToken = default); Task GetOriginalLogo( int teamId, CancellationToken cancellationToken = default); } }
c#
8
0.683746
66
27.3
20
starcoderdata