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
const debug = require('debug')('express-render-error') const path = require('path') const optionFromEnv = (app) => { const options = {} if (typeof process.env.SCRIPT_NAME !== 'undefined') { options.scriptName = process.env.SCRIPT_NAME } if (typeof process.env.PORT !== 'undefined') { options.port = process.env.PORT } if (typeof process.env.SHARED_PUBLIC_URL_PATH !== 'undefined') { options.sharedPublicUrlPath = process.env.SHARED_PUBLIC_URL_PATH } if (typeof process.env.DEFAULT_TITLE !== 'undefined') { options.defaultTitle = process.env.DEFAULT_TITLE } return options } const prepareOption = (app, option) => { if (!app.locals.option) { app.locals.option = {} } Object.assign(app.locals.option, { scriptName: '', port: 80, sharedPublicUrlPath: (option.scriptName || '') + '/public', defaultTitle: '(no title)' }, option) } const installSignalHandlers = () => { // Better handling of SIGINT and SIGTERM for docker process.on('SIGINT', function () { console.log('Received SIGINT. Exiting ...') process.exit() }) process.on('SIGTERM', function () { console.log('Received SIGTERM. Exiting ...') process.exit() }) } const prepareDebug = (app, debug) => { app.locals.debug = debug } const prepareErrorHandlers = (app) => { app.locals.mustache.overlay([path.join(__dirname, '..', 'views')]) } const setupErrorHandlers = (app) => { // Must be after other routes - Handle 404 app.get('*', (req, res) => { res.status(404) res.render('404', { title: 'Not Found' }) }) // Error handler has to be last app.use((err, req, res, next) => { app.locals.debug(app.locals.option) app.locals.debug(err) res.status(500) try { res.render('500', { title: 'Internal Server Error' }) } catch (e) { debug('Error during rendering 500 page:', e) app.locals.debug('Error during rendering 500 page:', e) res.send('Internal server error.') } }) } module.exports = { prepareDebug, optionFromEnv, installSignalHandlers, setupErrorHandlers, prepareOption, prepareErrorHandlers }
javascript
15
0.654253
160
29.208333
72
starcoderdata
<?php namespace App\Repositories; use App\User; use App\College; use App\settings; /** * Description of schoolRepository * * @author pawn */ class schoolRepository { protected $user; protected $college; public function __construct(College $college, User $user) { $this->college = $college; $this->user = $user; } public function store(Array $inputs) { $college = new $this->college; $user = new $this->user; $college->name = $inputs['name']; $college->email = $inputs['schoolmail']; $college->phoneno = $inputs['tel']; $college->po_box = $inputs['box']; $college->website = $inputs['website']; date_default_timezone_set('Africa/Douala'); $college->created_at = date('Y-m-d H:i:s'); $college->save(); $user->name = $inputs['username']; $user->email = $inputs['email']; $user->password = $user->role = 'admin'; $user->col_id = $college->id; $user->save(); $setting = new settings(); $setting->col_id = $college->id; $setting->intern_percent = 40; $setting->save(); return $college; } public function getPaginate($n) { return $this->college->paginate($n); } public function searching(Array $inputs) { $term = $inputs['term']; return $this->college::query()->whereRaw('LOWER(`name`) like ?', array($term)) ->get(); } public function getById($id) { return $this->college->findOrFail($id); } public function update($id, Array $inputs) { $college = $this->getById($id); $college->name = $inputs['name']; $college->email = $inputs['email']; $college->phoneno = $inputs['phoneno']; $college->po_box = $inputs['po_box']; $college->website = $inputs['website']; return $college->save(); } public function destroy($id) { return $this->getById($id)->delete(); } }
php
13
0.541148
86
24.487805
82
starcoderdata
# from io import StringIO from pathlib import Path import pytest from .block_manager import * def test_block_manager(tmp_path): input = StringIO("abcdef") manager = BlockManager(input, 4, tmp_path / "cache") with pytest.raises(Exception): manager.get_block(1) for i in range(10): assert manager.get_block(0) == "abcd" for i in range(10): assert manager.get_block(1) == "ef" for i in range(10): assert manager.get_block(0) == "abcd" for i in range(10): assert manager.get_block(1) == "ef" def test_lru_block_manager(tmp_path): input = StringIO("abcdef") manager = LRUBlockManager(input, 4, 2, tmp_path / "cache") with pytest.raises(Exception): manager.get_block(1) for i in range(10): assert manager.get_block(0) == "abcd" for i in range(10): assert manager.get_block(1) == "ef" for i in range(10): assert manager.get_block(0) == "abcd" for i in range(10): assert manager.get_block(1) == "ef" assert manager.io_count < 40 from random import choices def test_random(tmp_path): alphabet = [chr(x) for x in range(ord('a'), ord('z') + 1)] string = ''.join(choices(alphabet, k=1024)) input = StringIO(string) manager = LRUBlockManager(input, 4, 16, tmp_path / "cache") for i in range(1024 // 4): assert manager.get_block(i) == string[i * 4:(i + 1) * 4] for i in choices(range(1024 // 4), k=1024): assert manager.get_block(i) == string[i * 4:(i + 1) * 4]
python
13
0.609079
64
28.924528
53
starcoderdata
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Newtonsoft.Json; using System.Collections.Generic; using System.IO; namespace KiroTheBlueFox.Utils { /// /// Made by KiroTheBlueFox. /// Free to use and modify. /// public class Font { private string filePath; private Texture2D texture; private FontParameters fontParameters; private Dictionary<char, Rectangle> chars; public readonly Game Game; public string Name { get => fontParameters.Name; } public int Height { get => fontParameters.Height; } public Font(Game game, string filePath) { Game = game; this.filePath = filePath; } public void Load() { texture = Game.Content.Load var paramsPath = Path.Combine(Game.Content.RootDirectory, filePath+".json"); using (var stream = TitleContainer.OpenStream(paramsPath)) { StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); fontParameters = JsonConvert.DeserializeObject } if (fontParameters != null) { chars = new Dictionary<char, Rectangle>(); for (int i = 0; i < fontParameters.Characters.Length; i++) { for (int j = 0; j < fontParameters.Characters[i].Length; j++) { char character = fontParameters.Characters[i][j]; chars.Add(character, new Rectangle((i + fontParameters.MinimumCharacterWidth) * j, i * fontParameters.Height, i + fontParameters.MinimumCharacterWidth, fontParameters.Height)); } } } } public void Draw(SpriteBatch spriteBatch, string text, Vector2 position, FontOptions fontOptions) { int currentWidth = 0; int currentHeight = 0; for (int i = 0; i < text.Length; i++) { char character = text[i]; if (chars.ContainsKey(character)) { spriteBatch.Draw(texture, position + (new Vector2(currentWidth, currentHeight) * fontOptions.Size), chars[character], fontOptions.Color, 0, Vector2.Zero, fontOptions.Size, SpriteEffects.None, 0); currentWidth += chars[character].Width + fontOptions.CharSpacing; } else { switch (character) { case ' ': currentWidth += fontParameters.SpaceLength + fontOptions.CharSpacing; break; case '\n': currentWidth = 0; currentHeight += fontParameters.Height + fontOptions.LineSpacing; break; default: char missingChar = fontParameters.MissingCharacter[0]; spriteBatch.Draw(texture, position + (new Vector2(currentWidth, currentHeight) * fontOptions.Size), chars[missingChar], fontOptions.Color, 0, Vector2.Zero, fontOptions.Size, SpriteEffects.None, 0); currentWidth += chars[missingChar].Width + fontOptions.CharSpacing; break; } } } } public Vector2 TextSize(string text, FontOptions fontOptions) { List widths = new List int height = fontParameters.Height + fontOptions.LineSpacing, line = 0; widths.Add(0); for (int i = 0; i < text.Length; i++) { char character = text[i]; if (chars.ContainsKey(character)) { widths[line] += chars[character].Width + fontOptions.CharSpacing; } else { switch (character) { case ' ': widths[line] += fontParameters.SpaceLength + fontOptions.CharSpacing; break; case '\n': height += fontParameters.Height + fontOptions.LineSpacing; line++; widths.Add(0); break; default: widths[line] += chars[fontParameters.MissingCharacter[0]].Width + fontOptions.CharSpacing; break; } } } int maxWidth = 0; foreach (int width in widths) { if (width > maxWidth) maxWidth = width; } return new Vector2(maxWidth, height) * fontOptions.Size; } } class FontParameters { public string Name, MissingCharacter; public int Height, SpaceLength, MinimumCharacterWidth; public string[] Characters; } public class FontOptions { /// /// Size multiplicator of the font. 1 by default. /// public readonly float Size; /// /// Color of the font. White by default /// public readonly Color Color; /// /// Separation between characters (in pixels). 0 by default. /// public readonly int CharSpacing; /// /// Separation between lines (in pixels). 0 by default. /// public readonly int LineSpacing; public FontOptions() { Size = 1; Color = Color.White; CharSpacing = 0; LineSpacing = 0; } public FontOptions(float size, Color color, int charSpacing, int lineSpacing) { Size = size; Color = color; CharSpacing = charSpacing; LineSpacing = lineSpacing; } } }
c#
24
0.485385
225
35.931818
176
starcoderdata
import {call, put, takeEvery, takeLatest} from 'redux-saga/effects' import {loadPhotos} from '../reducers/index' const BASE_URL = 'http://cyberpolin.com:3002/photos/user/586d789259a804652b2edc32' export function* fetchPhotos(){ console.log('fetching photos'); var res = yield fetch(BASE_URL) .then(res => res.json()) .then(res => res.data) console.log(res); if(res){ yield put({type: 'LOAD_PHOTOS', photosAry:res}) } else { yield put({type: 'ALERT', msg:'Something went wrong'}) } // console.log('fetchoidas;lfkasd;lfj'); } function* mySaga(){ yield takeEvery('FETCH_ALL_IMAGES', fetchPhotos); console.log('this is saga'); } export default mySaga;
javascript
15
0.661745
82
26.592593
27
starcoderdata
#ifndef LINE_HPP #define LINE_HPP #include /** * Line between two given points * No need to override virtual methods from `Geometry` class, * as they only return field members, declared in base class (e.g. `Geometry::m_vertexes`), set in current constructor */ class Line : public Geometry { public: Line(const glm::vec3& point_start, const glm::vec3& point_end); private: glm::vec3 m_point_start; glm::vec3 m_point_end; void set_vertexes(); void set_indices(); void set_n_elements(); }; #endif // LINE_HPP
c++
9
0.705882
118
22.12
25
starcoderdata
tCIDLib::TBoolean TFacCIDOrbUC::bBindAll(tCIDOrbUC::TNSrvProxy& orbcNS) { // Reset the last check time stamp m_enctLastNSCheck = TTime::enctNow(); m_c8LastNSCookie = orbcNS->c8QueryCookie(); facCIDOrb().CheckNSCookie(m_c8LastNSCookie); TFundVector<tCIDOrb::ERebindRes> fcolFlags(m_colList.c4ElemCount()); if (!orbcNS->bRebindObjs(m_colList, fcolFlags, m_c8LastNSCookie)) { // // Pretty unlikely sine we just got the cookie, but theoretically // possible. // facCIDOrb().CheckNSCookie(m_c8LastNSCookie); return kCIDLib::False; } // Our list and the return flags list should be the same size CIDAssert ( m_colList.c4ElemCount() == fcolFlags.c4ElemCount() , L"The return binding flags list was not the right size" ); // // Go through the list and update them all for the next time. For those // that worked, make sure the initial binding flag is set. For those // that failed, we make sure we try a full one next time. For those // that failed becasue they were non-terminals, remove them because // they never will work. // tCIDLib::TCard4 c4Count = m_colList.c4ElemCount(); tCIDLib::TCard4 c4Index = 0; while (c4Index < c4Count) { TNSRebindInfo& nsrbiCur = m_colList[c4Index]; if (fcolFlags[c4Index] == tCIDOrb::ERebindRes::Success) { nsrbiCur.SetNextRenewal(); c4Index++; } else if (fcolFlags[c4Index] == tCIDOrb::ERebindRes::Exception) { if (nsrbiCur.c4IncErrCount() > CIDOrbUC_ThisFacility::c4MaxBindFails) { // It's failed too many times. Remove it LogRemoved(nsrbiCur.strFullPath(), kOrbUCErrs::errcRebind_MaxFails); m_colList.RemoveAt(c4Index); c4Count--; } else { nsrbiCur.SetNotBound(); c4Index++; } } else if (fcolFlags[c4Index] == tCIDOrb::ERebindRes::NotATerminal) { // It's not a terminal so clearly wrong. Remove it LogRemoved(nsrbiCur.strFullPath(), kOrbUCErrs::errcRebind_NotATerminal); m_colList.RemoveAt(c4Index); c4Count--; } else { CIDAssert2(L"Unknown bind result enum"); } } return kCIDLib::True; }
c++
16
0.587444
84
33.083333
72
inline
package com.freddy.kulachat.presenter.home; import com.freddy.kulachat.contract.home.HomeContract; import com.freddy.kulachat.model.home.HomeModel; import com.freddy.kulachat.presenter.BasePresenter; import javax.inject.Inject; /** * @author FreddyChen * @name * @date 2020/05/23 18:54 * @email * @github https://github.com/FreddyChen * @desc */ public class HomePresenter extends BasePresenter implements HomeContract.Presenter { @Inject HomeModel homeModel; @Inject public HomePresenter(HomeModel homeModel) { this.homeModel = homeModel; } @Override public void test() { homeModel.test(); } }
java
8
0.714495
103
21.032258
31
starcoderdata
<?php /* * Copyright (c) Ouzo contributors, https://github.com/letsdrink/ouzo * This file is made available under the MIT License (view the LICENSE file for more information). */ use Application\Model\Test\OrderProduct; use Ouzo\Db\ModelQueryBuilderHelper; use Ouzo\Db\Relation; use Ouzo\Db\RelationWithAlias; use Ouzo\Tests\Assert; use PHPUnit\Framework\TestCase; class ModelQueryBuilderHelperTest extends TestCase { /** * @test */ public function shouldExtractNestedRelations() { //given $root = OrderProduct::metaInstance(); //when $relations = ModelQueryBuilderHelper::extractRelations($root, 'product->category'); //then Assert::thatArray($relations)->containsExactly( new Relation('product', 'Test\Product', 'id_product', 'id', false), new Relation('category', 'Test\Category', 'id_category', 'id', false) ); } /** * @test */ public function shouldExtractInlineRelation() { //given $root = OrderProduct::metaInstance(); $inlineRelation = new Relation('orderProduct', 'Test\OrderProduct', 'id', 'id_product', false); //when $relations = ModelQueryBuilderHelper::extractRelations($root, $inlineRelation); //then Assert::thatArray($relations)->containsExactly( $inlineRelation ); } /** * @test */ public function shouldAssociateRelationsWithAliasesIfFewerAliases() { //given $relation1 = new Relation('relation1', 'Test\OrderProduct', 'id', 'id_product', false); $relation2 = new Relation('relation2', 'Test\OrderProduct', 'id', 'id_product', false); //when $relationToAlias = ModelQueryBuilderHelper::associateRelationsWithAliases([$relation1, $relation2], 'r1'); //then Assert::thatArray($relationToAlias)->containsExactly( new RelationWithAlias($relation1, 'r1'), new RelationWithAlias($relation2, null)); } /** * @test */ public function shouldAssociateRelationsWithNullAliases() { //given $relation1 = new Relation('relation1', 'Test\OrderProduct', 'id', 'id_product', false); $relation2 = new Relation('relation2', 'Test\OrderProduct', 'id', 'id_product', false); //when $relationToAlias = ModelQueryBuilderHelper::associateRelationsWithAliases([$relation1, $relation2], null); //then Assert::thatArray($relationToAlias)->containsExactly( new RelationWithAlias($relation1, null), new RelationWithAlias($relation2, null)); } /** * @test */ public function shouldAssociateRelationsWithAliasesByRelationNames() { //given $relation1 = new Relation('relation1', 'Test\OrderProduct', 'id', 'id_product', false); $relation2 = new Relation('relation2', 'Test\OrderProduct', 'id', 'id_product', false); //when $relationToAlias = ModelQueryBuilderHelper::associateRelationsWithAliases([ $relation1, $relation2 ], ['relation2' => 'r2']); //then Assert::thatArray($relationToAlias)->containsExactly( new RelationWithAlias($relation1, null), new RelationWithAlias($relation2, 'r2')); } }
php
13
0.624963
114
30.299065
107
starcoderdata
import random import sc2 from sc2.player import Bot, Computer import protoss_agent if __name__ == '__main__': enemy_race = random.choice([sc2.Race.Protoss, sc2.Race.Terran, sc2.Race.Zerg, sc2.Race.Random]) sc2.run_game(sc2.maps.get("Simple128"), [Bot(sc2.Race.Protoss, protoss_agent.ProtossRushBot()), Computer(enemy_race, sc2.Difficulty.Easy)], realtime=False)
python
11
0.635294
99
31.692308
13
starcoderdata
// // SensorsAnalyticsExceptionHandler.h // SensorsAnalyticsSDK // // Created by 王灼洲 on 2017/5/26. // Copyright © 2017年 SensorsData. All rights reserved. // #import @class SensorsAnalyticsSDK; @interface SensorsAnalyticsExceptionHandler : NSObject + (instancetype)sharedHandler; - (void)addSensorsAnalyticsInstance:(SensorsAnalyticsSDK *)instance; @end
c
6
0.796909
68
22.842105
19
starcoderdata
const fs = require('fs'); const path = require('path'); module.exports.getNewFileName = function (fileName) { const chunks = fileName.split('.') if (chunks.length > 1) { const ext = `.${chunks[chunks.length - 1]}` return chunks.slice(0, chunks.length - 1).join('.') + ' (' + Date.now() + ')' + ext; } return fileName + ' (' + Date.now() + ')'; } module.exports.saveFile = function (fileName, content) { return new Promise((resolve, reject) => { fs.writeFile(fileName, content, function (err) { if (err) { reject(err); } resolve(`${fileName} file was saved!`); }); }); } module.exports.isFileExist = function (fileName) { return new Promise((resolve, reject) => { fs.stat(fileName, (err) => { if (err) { resolve(false); } resolve(true); }) }); } module.exports.getParentDir = function (argv, baseDir, time) { const date = new Date(Number(time)); let dirPath = path.resolve(baseDir, 'files') if (argv.from) { dirPath = path.resolve(baseDir, 'files', argv.from) } if (argv.fy) { dirPath = path.resolve(dirPath, String(date.getFullYear())) } return dirPath }
javascript
17
0.596138
88
24.340426
47
starcoderdata
import React, { useState, useEffect } from "react"; import { useRouter } from "next/router"; import { useDispatch, useSelector } from "react-redux"; import { StarOutlined, StarFilled, FlagOutlined, CloseCircleOutlined, } from "@ant-design/icons"; import { addFavorite, removeFavorite } from "../../../actions/counters"; import { ToolbarContainer, ToolbarButton, ToolbarButtonClose } from "./style"; import ReportModal from "./ReportModal"; const index = ({ postId, isModalView, authorId }) => { const [isFavorite, setFavorite] = useState(false); const [isReportOpen, setReportOpen] = useState(false); const [isPostAuthor, setPostAuthor] = useState(false); const dispatch = useDispatch(); const isAuthenticated = useSelector((state) => state.auth.isAuthenticated); const user = useSelector((state) => state.auth.user); const router = useRouter(); //disable favorite button for post owner useEffect(() => { if (user && authorId) { if (user._id.toString() === authorId.toString()) { setPostAuthor(true); } } }, [user]); useEffect(() => { //check if user has favorited post if (user) { setFavorite( user.favorites.filter((post) => post._id === postId).length > 0 ? true : false ); } }, [user]); function closeModal() { router.push("/"); } return ( {isAuthenticated && !isFavorite && !isPostAuthor && ( <ToolbarButton onClick={() => { dispatch(addFavorite(postId)); setFavorite(true); }} > <StarOutlined /> {" Favorite"} )} {isAuthenticated && isFavorite && !isPostAuthor && ( <ToolbarButton onClick={() => { dispatch(removeFavorite(postId)); setFavorite(false); }} > <StarFilled /> {" Unfavorite"} )} {!isPostAuthor && ( <ToolbarButton onClick={() => setReportOpen(!isReportOpen)}> <FlagOutlined /> {" Report"} )} <span style={{ flex: 1 }} /> {isModalView && ( <ToolbarButtonClose onClick={() => closeModal()}> <CloseCircleOutlined /> {" Close"} )} {isReportOpen && ( <ReportModal postId={postId} setReportOpen={setReportOpen} /> )} ); }; export default index;
javascript
26
0.576251
78
26.709677
93
starcoderdata
/* * Copyright (c) 1998-2018 and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.grib.collection; import ucar.nc2.constants.DataFormatType; import thredds.featurecollection.FeatureCollectionConfig; import ucar.nc2.grib.grib1.*; import ucar.nc2.grib.grib1.tables.Grib1Customizer; import ucar.nc2.grib.grib1.tables.Grib1ParamTables; import ucar.nc2.grib.*; import ucar.unidata.io.RandomAccessFile; import ucar.unidata.io.http.HTTPRandomAccessFile; import java.io.IOException; import java.util.Formatter; /** * Grib-1 Collection IOSP. * Handles both collections and single GRIB files. * * @author caron * @since 4/6/11 */ public class Grib1Iosp extends GribIosp { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Grib2Iosp.class); @Override public String makeVariableName(GribCollectionImmutable.VariableIndex v) { return makeVariableNameFromTables(gribCollection.getCenter(), gribCollection.getSubcenter(), v.getTableVersion(), v.getParameter(), v.getLevelType(), v.isLayer(), v.getIntvType(), v.getIntvName()); } public static String makeVariableName(Grib1Customizer cust, FeatureCollectionConfig.GribConfig gribConfig, Grib1SectionProductDefinition pds) { return makeVariableNameFromTables(cust, gribConfig, pds.getCenter(), pds.getSubCenter(), pds.getTableVersion(), pds.getParameterNumber(), pds.getLevelType(), cust.isLayer(pds.getLevelType()), pds.getTimeRangeIndicator(), null); } private String makeVariableNameFromTables(int center, int subcenter, int version, int paramNo, int levelType, boolean isLayer, int intvType, String intvName) { return makeVariableNameFromTables(cust, config.gribConfig, center, subcenter, version, paramNo, levelType, isLayer, intvType, intvName); } private static String makeVariableNameFromTables(Grib1Customizer cust, FeatureCollectionConfig.GribConfig gribConfig, int center, int subcenter, int version, int paramNo, int levelType, boolean isLayer, int timeRangeIndicator, String intvName) { try (Formatter f = new Formatter()) { Grib1Parameter param = cust.getParameter(center, subcenter, version, paramNo); // code table 2 if (param == null) { f.format("VAR%d-%d-%d-%d", center, subcenter, version, paramNo); } else { if (param.useName()) { f.format("%s", param.getName()); } else { f.format("%s", GribUtils.makeNameFromDescription(param.getDescription())); } } if (gribConfig.useTableVersion) { f.format("_TableVersion%d", version); } if (gribConfig.useCenter) { f.format("_Center%d", center); } if (levelType != GribNumbers.UNDEFINED) { // satellite data doesnt have a level f.format("_%s", cust.getLevelNameShort(levelType)); // code table 3 if (isLayer) { f.format("_layer"); } } if (timeRangeIndicator >= 0) { GribStatType stat = cust.getStatType(timeRangeIndicator); if (stat != null) { if (intvName != null) { f.format("_%s", intvName); } f.format("_%s", stat.name()); } else { if (intvName != null) { f.format("_%s", intvName); } // f.format("_%d", timeRangeIndicator); } } return f.toString(); } } @Override public String makeVariableLongName(GribCollectionImmutable.VariableIndex v) { return makeVariableLongName(gribCollection.getCenter(), gribCollection.getSubcenter(), v.getTableVersion(), v.getParameter(), v.getLevelType(), v.isLayer(), v.getIntvType(), v.getIntvName(), v.getProbabilityName()); } private String makeVariableLongName(int center, int subcenter, int version, int paramNo, int levelType, boolean isLayer, int intvType, String intvName, String probabilityName) { return makeVariableLongName(cust, center, subcenter, version, paramNo, levelType, isLayer, intvType, intvName, probabilityName); } static String makeVariableLongName(Grib1Customizer cust, int center, int subcenter, int version, int paramNo, int levelType, boolean isLayer, int intvType, String intvName, String probabilityName) { try (Formatter f = new Formatter()) { boolean isProb = (probabilityName != null && !probabilityName.isEmpty()); if (isProb) { f.format("Probability "); } Grib1Parameter param = cust.getParameter(center, subcenter, version, paramNo); if (param == null) { f.format("Unknown Parameter %d-%d-%d-%d", center, subcenter, version, paramNo); } else { f.format("%s", param.getDescription()); } if (intvType >= 0) { GribStatType stat = cust.getStatType(intvType); if (stat != null) { f.format(" (%s %s)", intvName, stat.name()); } else if (intvName != null && !intvName.isEmpty()) { f.format(" (%s)", intvName); } } if (levelType != GribNumbers.UNDEFINED) { // satellite data doesnt have a level f.format(" @ %s", cust.getLevelDescription(levelType)); if (isLayer) { f.format(" layer"); } } return f.toString(); } } @Override protected String makeVariableUnits(GribCollectionImmutable.VariableIndex vindex) { return makeVariableUnits(gribCollection.getCenter(), gribCollection.getSubcenter(), vindex.getTableVersion(), vindex.getParameter()); } private String makeVariableUnits(int center, int subcenter, int version, int paramNo) { Grib1Parameter param = cust.getParameter(center, subcenter, version, paramNo); String val = (param == null) ? "" : param.getUnit(); return (val == null) ? "" : val; } static String makeVariableUnits(Grib1Customizer cust, GribCollectionImmutable gribCollection, GribCollectionImmutable.VariableIndex vindex) { Grib1Parameter param = cust.getParameter(gribCollection.getCenter(), gribCollection.getSubcenter(), vindex.getTableVersion(), vindex.getParameter()); String val = (param == null) ? "" : param.getUnit(); return (val == null) ? "" : val; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private Grib1Customizer cust; @Override public boolean isValidFile(RandomAccessFile raf) throws IOException { if (raf instanceof HTTPRandomAccessFile) { // only do remote if memory resident if (raf.length() > raf.getBufferSize()) return false; } else { // wont accept remote index GribCdmIndex.GribCollectionType type = GribCdmIndex.getType(raf); if (type == GribCdmIndex.GribCollectionType.GRIB1) return true; if (type == GribCdmIndex.GribCollectionType.Partition1) return true; } // check for GRIB1 data file return Grib1RecordScanner.isValidFile(raf); } @Override public String getFileTypeId() { return DataFormatType.GRIB1.getDescription(); } @Override public String getFileTypeDescription() { return "GRIB1 Collection"; } // public no-arg constructor for reflection public Grib1Iosp() { super(true, logger); } public Grib1Iosp(GribCollectionImmutable.GroupGC gHcs, GribCollectionImmutable.Type gtype) { super(true, logger); this.gHcs = gHcs; this.owned = true; this.gtype = gtype; } public Grib1Iosp(GribCollectionImmutable gc) { super(true, logger); this.gribCollection = gc; this.owned = true; } @Override protected ucar.nc2.grib.GribTables createCustomizer() throws IOException { Grib1ParamTables tables = (config.gribConfig.paramTable != null) ? Grib1ParamTables.factory(config.gribConfig.paramTable) : Grib1ParamTables.factory(config.gribConfig.paramTablePath, config.gribConfig.lookupTablePath); // so an // iosp // message // must be // received // before // the // open() cust = Grib1Customizer.factory(gribCollection.getCenter(), gribCollection.getSubcenter(), gribCollection.getMaster(), tables); return cust; } @Override protected String getVerticalCoordDesc(int vc_code) { return cust.getLevelDescription(vc_code); } @Override protected GribTables.Parameter getParameter(GribCollectionImmutable.VariableIndex vindex) { return cust.getParameter(gribCollection.getCenter(), gribCollection.getSubcenter(), gribCollection.getVersion(), vindex.getParameter()); } public Object getLastRecordRead() { return Grib1Record.lastRecordRead; } public void clearLastRecordRead() { Grib1Record.lastRecordRead = null; } public Object getGribCustomizer() { return cust; } }
java
18
0.618879
120
36.20155
258
starcoderdata
/** * The MIT License * Copyright © 2010 JmxTrans team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.googlecode.jmxtrans.scheduler; import com.google.common.collect.ImmutableSet; import com.googlecode.jmxtrans.cli.JmxTransConfiguration; import com.googlecode.jmxtrans.executors.ExecutorRepository; import com.googlecode.jmxtrans.jmx.ResultProcessor; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.monitoring.ManagedThreadPoolExecutor; import org.apache.commons.pool.KeyedObjectPool; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ServerSchedulerTest { @Mock private JmxTransConfiguration configuration; private DummyExecutorRepository queryExecutorRepository = new DummyExecutorRepository(); @Mock private ResultProcessor resultProcessor; private ServerScheduler serverScheduler; @Before public void setUp() { serverScheduler = new ServerScheduler(configuration, Executors.newScheduledThreadPool(2), queryExecutorRepository, resultProcessor); serverScheduler.start(); } @After public void tearDown() { serverScheduler.stop(); } @Test public void testSchedule() throws InterruptedException { // Given Server server = Server.builder() .setRunPeriodSeconds(2) .setPid("1") .setPool(mock(KeyedObjectPool.class)) .addQueries(sampleQueries()) .build(); ThreadPoolExecutor executor = queryExecutorRepository.initExecutor(server); // When serverScheduler.schedule(server); // Then verify(executor, timeout(6000L).atLeast(2)).submit(any(Runnable.class)); } @Test public void testScheduleWhenRunFails() throws InterruptedException { // Given Server server = Server.builder() .setRunPeriodSeconds(2) .setPid("2") .setPool(mock(KeyedObjectPool.class)) .addQueries(sampleQueries()) .build(); ThreadPoolExecutor executor = queryExecutorRepository.initExecutor(server); when(executor.submit(any(Runnable.class))).thenThrow(new IllegalStateException("Command failed")); // When serverScheduler.schedule(server); // Then verify(executor, timeout(6000L).atLeast(2)).submit(any(Runnable.class)); } private ImmutableSet sampleQueries() { return ImmutableSet. } @Test public void testScheduleWhenRunBlocks() throws InterruptedException { // Given when(configuration.getRunPeriod()).thenReturn(1); // Server 1 Server server1 = Server.builder() .setRunPeriodSeconds(2) .setHost("test1").setPort("9999") .setPool(mock(KeyedObjectPool.class)) .addQueries(sampleQueries()) .build(); ThreadPoolExecutor executor1 = queryExecutorRepository.initExecutor(server1); when(executor1.submit(any(Runnable.class))).then(new Answer { @Override public Future answer(InvocationOnMock invocationOnMock) throws Throwable { Thread.sleep(10000L); return null; } }); // Server 2 Server server2 = Server.builder() .setHost("test2").setPort("9999") .setPool(mock(KeyedObjectPool.class)) .addQueries(sampleQueries()) .build(); final ThreadPoolExecutor executor2 = queryExecutorRepository.initExecutor(server2); // When serverScheduler.schedule(server1); serverScheduler.schedule(server2); // Then verify(executor1, timeout(6000L).atLeast(1)).submit(any(Runnable.class)); verify(executor2, timeout(6000L).atLeast(2)).submit(any(Runnable.class)); } static class DummyExecutorRepository implements ExecutorRepository { Map<String, ThreadPoolExecutor> executorMap = new HashMap<>(); @Override public void remove(Server server) { executorMap.remove(getServerId(server)); } @Override public void put(Server server) { initExecutor(server); } @Override public Collection getExecutors() { return executorMap.values(); } @Override public ThreadPoolExecutor getExecutor(Server server) { return initExecutor(server); } @Override public Collection getMBeans() { return null; } public ThreadPoolExecutor initExecutor(Server server) { String serverId = getServerId(server); ThreadPoolExecutor executor = executorMap.get(serverId); if (executor == null) { executor = mock(ThreadPoolExecutor.class); executorMap.put(serverId, executor); } return executor; } private String getServerId(Server server) { return server.getPid() == null ? server.getHost() : server.getPid(); } } }
java
15
0.759689
134
32.155914
186
starcoderdata
@{ Layout = "~/Views/Shared/ChinookLayout.cshtml"; } <header class="page-header"> Denied do not have access to that page.
c#
6
0.630058
51
20.625
8
starcoderdata
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Pagination { using System; using Microsoft.Azure.Cosmos.CosmosElements; internal sealed class Record { private Record(long resourceIdentifier, long timestamp, Guid identifier, CosmosObject payload) { this.ResourceIdentifier = resourceIdentifier < 0 ? throw new ArgumentOutOfRangeException(nameof(resourceIdentifier)) : resourceIdentifier; this.Timestamp = timestamp < 0 ? throw new ArgumentOutOfRangeException(nameof(timestamp)) : timestamp; this.Identifier = identifier; this.Payload = payload ?? throw new ArgumentNullException(nameof(payload)); } public long ResourceIdentifier { get; } public long Timestamp { get; } public Guid Identifier { get; } public CosmosObject Payload { get; } public static Record Create(long previousResourceIdentifier, CosmosObject payload) { return new Record(previousResourceIdentifier + 1, DateTime.UtcNow.Ticks, Guid.NewGuid(), payload); } } }
c#
17
0.615264
150
37.515152
33
starcoderdata
/** * @fileoverview Disallows or enforces spaces inside computed properties. * @author */ "use strict"; const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "layout", docs: { description: "enforce consistent spacing inside computed property brackets", recommended: false, url: "https://eslint.org/docs/rules/computed-property-spacing" }, fixable: "whitespace", schema: [ { enum: ["always", "never"] }, { type: "object", properties: { enforceForClassMembers: { type: "boolean", default: true } }, additionalProperties: false } ], messages: { unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", missingSpaceBefore: "A space is required before '{{tokenValue}}'.", missingSpaceAfter: "A space is required after '{{tokenValue}}'." } }, create(context) { const sourceCode = context.getSourceCode(); const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never" const enforceForClassMembers = !context.options[1] || context.options[1].enforceForClassMembers; //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- /** * Reports that there shouldn't be a space after the first token * @param {ASTNode} node The node to report in the event of an error. * @param {Token} token The token to use for the report. * @param {Token} tokenAfter The token after `token`. * @returns {void} */ function reportNoBeginningSpace(node, token, tokenAfter) { context.report({ node, loc: { start: token.loc.end, end: tokenAfter.loc.start }, messageId: "unexpectedSpaceAfter", data: { tokenValue: token.value }, fix(fixer) { return fixer.removeRange([token.range[1], tokenAfter.range[0]]); } }); } /** * Reports that there shouldn't be a space before the last token * @param {ASTNode} node The node to report in the event of an error. * @param {Token} token The token to use for the report. * @param {Token} tokenBefore The token before `token`. * @returns {void} */ function reportNoEndingSpace(node, token, tokenBefore) { context.report({ node, loc: { start: tokenBefore.loc.end, end: token.loc.start }, messageId: "unexpectedSpaceBefore", data: { tokenValue: token.value }, fix(fixer) { return fixer.removeRange([tokenBefore.range[1], token.range[0]]); } }); } /** * Reports that there should be a space after the first token * @param {ASTNode} node The node to report in the event of an error. * @param {Token} token The token to use for the report. * @returns {void} */ function reportRequiredBeginningSpace(node, token) { context.report({ node, loc: token.loc, messageId: "missingSpaceAfter", data: { tokenValue: token.value }, fix(fixer) { return fixer.insertTextAfter(token, " "); } }); } /** * Reports that there should be a space before the last token * @param {ASTNode} node The node to report in the event of an error. * @param {Token} token The token to use for the report. * @returns {void} */ function reportRequiredEndingSpace(node, token) { context.report({ node, loc: token.loc, messageId: "missingSpaceBefore", data: { tokenValue: token.value }, fix(fixer) { return fixer.insertTextBefore(token, " "); } }); } /** * Returns a function that checks the spacing of a node on the property name * that was passed in. * @param {string} propertyName The property on the node to check for spacing * @returns {Function} A function that will check spacing on a node */ function checkSpacing(propertyName) { return function(node) { if (!node.computed) { return; } const property = node[propertyName]; const before = sourceCode.getTokenBefore(property, astUtils.isOpeningBracketToken), first = sourceCode.getTokenAfter(before, { includeComments: true }), after = sourceCode.getTokenAfter(property, astUtils.isClosingBracketToken), last = sourceCode.getTokenBefore(after, { includeComments: true }); if (astUtils.isTokenOnSameLine(before, first)) { if (propertyNameMustBeSpaced) { if (!sourceCode.isSpaceBetweenTokens(before, first) && astUtils.isTokenOnSameLine(before, first)) { reportRequiredBeginningSpace(node, before); } } else { if (sourceCode.isSpaceBetweenTokens(before, first)) { reportNoBeginningSpace(node, before, first); } } } if (astUtils.isTokenOnSameLine(last, after)) { if (propertyNameMustBeSpaced) { if (!sourceCode.isSpaceBetweenTokens(last, after) && astUtils.isTokenOnSameLine(last, after)) { reportRequiredEndingSpace(node, after); } } else { if (sourceCode.isSpaceBetweenTokens(last, after)) { reportNoEndingSpace(node, after, last); } } } }; } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- const listeners = { Property: checkSpacing("key"), MemberExpression: checkSpacing("property") }; if (enforceForClassMembers) { listeners.MethodDefinition = listeners.PropertyDefinition = listeners.Property; } return listeners; } };
javascript
25
0.466889
123
35.609756
205
starcoderdata
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.alexkang.x3matrixcalculator; public final class R { public static final class array { public static final int dimensions=0x7f070001; public static final int operations=0x7f070000; } public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f050000; public static final int activity_vertical_margin=0x7f050001; } public static final class drawable { public static final int background=0x7f020000; public static final int ic_action_cancel=0x7f020001; public static final int icon_final=0x7f020002; } public static final class id { public static final int a1=0x7f0a0004; public static final int a2=0x7f0a0005; public static final int a3=0x7f0a0010; public static final int a4=0x7f0a0019; public static final int action_clear=0x7f0a0043; public static final int action_settings=0x7f0a0044; public static final int b1=0x7f0a0006; public static final int b2=0x7f0a0007; public static final int b3=0x7f0a0011; public static final int b4=0x7f0a001a; public static final int c1=0x7f0a0012; public static final int c2=0x7f0a0013; public static final int c3=0x7f0a0014; public static final int c4=0x7f0a001b; public static final int calculate=0x7f0a000e; public static final int d1=0x7f0a0008; public static final int d2=0x7f0a000a; public static final int d3=0x7f0a0015; public static final int d4=0x7f0a001c; public static final int det_result=0x7f0a002c; public static final int e1=0x7f0a000b; public static final int e2=0x7f0a000c; public static final int e3=0x7f0a0016; public static final int e4=0x7f0a001d; public static final int edit_texts=0x7f0a0003; public static final int edit_texts_det=0x7f0a0027; public static final int edit_texts_inv=0x7f0a0039; public static final int f1=0x7f0a000d; public static final int f2=0x7f0a0017; public static final int f3=0x7f0a0018; public static final int f4=0x7f0a001e; public static final int g1=0x7f0a001f; public static final int g2=0x7f0a0020; public static final int g3=0x7f0a0021; public static final int g4=0x7f0a0022; public static final int h1=0x7f0a0023; public static final int h2=0x7f0a0024; public static final int h3=0x7f0a0025; public static final int h4=0x7f0a0026; public static final int i1=0x7f0a0028; public static final int i2=0x7f0a0029; public static final int i3=0x7f0a002d; public static final int i4=0x7f0a0032; public static final int j1=0x7f0a002a; public static final int j2=0x7f0a002b; public static final int j3=0x7f0a002e; public static final int j4=0x7f0a0033; public static final int k1=0x7f0a002f; public static final int k2=0x7f0a0030; public static final int k3=0x7f0a0031; public static final int k4=0x7f0a0034; public static final int l1=0x7f0a0035; public static final int l2=0x7f0a0036; public static final int l3=0x7f0a0037; public static final int l4=0x7f0a0038; public static final int operation=0x7f0a0009; public static final int pager=0x7f0a0001; public static final int pager_title_strip=0x7f0a0002; public static final int result=0x7f0a0000; public static final int warning=0x7f0a000f; public static final int x1=0x7f0a003a; public static final int x2=0x7f0a003b; public static final int x3=0x7f0a003c; public static final int y1=0x7f0a003d; public static final int y2=0x7f0a003e; public static final int y3=0x7f0a003f; public static final int z1=0x7f0a0040; public static final int z2=0x7f0a0041; public static final int z3=0x7f0a0042; } public static final class layout { public static final int activity_display_result_2=0x7f030000; public static final int activity_display_result_3=0x7f030001; public static final int activity_display_result_4=0x7f030002; public static final int activity_main=0x7f030003; public static final int fragment_basic_2=0x7f030004; public static final int fragment_basic_3=0x7f030005; public static final int fragment_basic_4=0x7f030006; public static final int fragment_determinant_2=0x7f030007; public static final int fragment_determinant_3=0x7f030008; public static final int fragment_determinant_4=0x7f030009; public static final int fragment_inverse_2=0x7f03000a; public static final int fragment_inverse_3=0x7f03000b; public static final int fragment_inverse_4=0x7f03000c; } public static final class menu { public static final int display_result=0x7f090000; public static final int main=0x7f090001; } public static final class string { public static final int action_clear=0x7f060006; public static final int action_settings=0x7f060001; public static final int app_name=0x7f060000; public static final int calculate=0x7f060005; public static final int hello_world=0x7f06000a; /** Strings related to Settings Example General settings */ public static final int pref_description_rational=0x7f06000c; public static final int pref_title_rational=0x7f06000d; public static final int title_activity_display_result=0x7f060007; public static final int title_activity_main_activity3=0x7f060009; public static final int title_activity_settings=0x7f06000b; public static final int title_section1=0x7f060002; public static final int title_section2=0x7f060003; public static final int title_section3=0x7f060004; public static final int warning=0x7f060008; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f080000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f080001; } public static final class xml { public static final int pref_general=0x7f040000; } }
java
7
0.693045
82
43.630058
173
starcoderdata
'use strict'; angular.module('mentors').controller('MentorController', ['$scope', '$http', '$location', 'Authentication', 'Mentors', '$stateParams', function($scope, $http, $location, Authentication, Mentors, $stateParams) { $scope.authentication = Authentication; $scope.mentors = Mentors.query(); $scope.mentor = Mentors.get({ mentorId: $stateParams.mentorId }); } ]);
javascript
14
0.624413
134
31.769231
13
starcoderdata
def get_specified_bucket(sitename): """ Returns the bucket for the specified sitename. """ from widely.commands.auth import get_credentials get_credentials() conn = S3Connection() try: bucket = conn.get_bucket(sitename) bucket.get_website_configuration() except S3ResponseError: raise NoSuchBucket return bucket
python
9
0.671159
52
27.615385
13
inline
namespace ValidCode.Web { using System; using System.IO; using System.Threading.Tasks; public class Issue317 { public static async Task M1(string fileName) { var stream = File.OpenRead(fileName); await using var reader1 = new DefaultFalse(stream); await using var reader2 = new DefaultFalse(stream, false); await using var reader3 = new DefaultTrue(stream, false); } public static async Task M2(string fileName) { await using var stream = File.OpenRead(fileName); await using var reader1 = new DefaultTrue(stream); await using var reader2 = new DefaultTrue(stream, true); await using var reader3 = new DefaultFalse(stream, true); } private sealed class DefaultTrue : IAsyncDisposable { private readonly Stream stream; private readonly bool leaveOpen; public DefaultTrue(Stream stream, bool leaveOpen = true) { this.stream = stream; this.leaveOpen = leaveOpen; } public ValueTask DisposeAsync() { if (!this.leaveOpen) { return this.stream.DisposeAsync(); } return ValueTask.CompletedTask; } } private sealed class DefaultFalse : IAsyncDisposable { private readonly Stream stream; private readonly bool leaveOpen; public DefaultFalse(Stream stream, bool leaveOpen = false) { this.stream = stream; this.leaveOpen = leaveOpen; } public ValueTask DisposeAsync() { if (!this.leaveOpen) { return this.stream.DisposeAsync(); } return ValueTask.CompletedTask; } } } }
c#
16
0.526866
70
28.130435
69
starcoderdata
from ..mesh import * from ..model import * from .timer import * import copy,json import numpy as np from scipy.integrate import ode def res(x,y): return x - min(x,y) # Right hand sides -------------------------------------------------------- # curretly spending too much time inside this function. perhaps don't # use filter? def chvrhs_hybrid(t,y,model,sample_rate): for i in range(model.dimension): model.systemState[i].value[0] = y[i] for e in model.events: e.updaterate() #MIXED = filter(lambda e: e.hybridType == MIXED, model.events) agg_rate = 0. for i in range(model.dimension): if model.events[i].hybridType == SLOW or model.events[i].hybridType == MIXED: agg_rate = agg_rate + model.events[i].rate #for s in MIXED: # agg_rate = agg_rate + s.rate rhs = np.zeros(model.dimension+1) fast = filter(lambda e: e.hybridType == FAST, model.events) for e in fast: for i in range(model.dimension): name = model.systemState[i].name r = list(filter(lambda e: e[0].name == name, e.reactants)) p = list(filter(lambda e: e[0].name == name, e.products)) direction = 0. if r: direction = direction - float(r[0][1]) if p: direction = direction + float(p[0][1]) rhs[i] = rhs[i]+ direction*e.rate rhs[len(model.systemState)] = 1. rhs = rhs/(agg_rate+sample_rate) return rhs def chvrhs_coupled(t,y,model_hybrid,model_exact,sample_rate): for i in range(model_exact.dimension): model_hybrid.systemState[i].value[0] = y[i] for i in range(model_hybrid.dimension): model_exact.systemState[i].value[0] = y[i+model_exact.dimension] for e in model_exact.events: e.updaterate() for e in model_hybrid.events: e.updaterate() agg_rate = 0. for i in range(len(model_hybrid.events)): if model_hybrid.events[i].hybridType == SLOW or model_hybrid.events[i].hybridType == MIXED: hybrid_rate = model_hybrid.events[i].rate exact_rate = model_exact.events[i].rate agg_rate = agg_rate + res(hybrid_rate,exact_rate ) agg_rate = agg_rate + res(exact_rate,hybrid_rate ) agg_rate = agg_rate + min(hybrid_rate,exact_rate ) elif model_hybrid.events[i].hybridType == FAST or model_hybrid.events[i].hybridType == VITL: agg_rate = agg_rate + model_exact.events[i].rate rhs = np.zeros(2*model_exact.dimension+1) fast = filter(lambda e: e.hybridType == FAST, model_hybrid.events) for e in fast: for i in range(model_exact.dimension): name = model_exact.systemState[i].name r = list(filter(lambda e: e[0].name == name, e.reactants)) p = list(filter(lambda e: e[0].name == name, e.products)) direction = 0. if r: direction = direction - float(r[0][1]) if p: direction = direction + float(p[0][1]) rhs[i] = rhs[i] + direction*e.rate rhs[2*model_exact.dimension] = 1. rhs = rhs/(agg_rate+sample_rate) return rhs def rrerhs(t,y,model,sample_rate): """rhs of determistic part of equations, i.e. the rhs of reaction rate equations""" for i in range(model.dimension): model.systemState[i].value[0] = y[i] for e in model.events: e.updaterate() rhs = np.zeros(model.dimension) fast = filter(lambda e: e.hybridType == FAST, model.events) for e in fast: for i in range(model.dimension): name = model.systemState[i].name r = list(filter(lambda e: e[0].name == name, e.reactants)) p = list(filter(lambda e: e[0].name == name, e.products)) direction = 0. if r: direction = direction - float(r[0][1]) if p: direction = direction + float(p[0][1]) rhs[i] = rhs[i]+ direction*e.rate return rhs
python
17
0.579026
100
36.259259
108
starcoderdata
K, X = map(int, input().split()) blacks = {} blacks[X] = True for i in range(K): if -1000000 <= i and i <= 1000000: blacks[X - i] = True blacks[X + i] = True blacks_list = list(blacks.keys()) print(' '.join([str(x) for x in sorted(blacks_list)]))
python
10
0.563433
54
23.454545
11
codenet
package com.sequenceiq.cloudbreak.converter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.api.model.CloudGatewayJson; import com.sequenceiq.cloudbreak.api.model.PlatformGatewaysResponse; import com.sequenceiq.cloudbreak.cloud.model.CloudGateWay; import com.sequenceiq.cloudbreak.cloud.model.CloudGateWays; @Component public class CloudGatewayssToPlatformGatewaysResponseConverter extends AbstractConversionServiceAwareConverter<CloudGateWays, PlatformGatewaysResponse> { @Override public PlatformGatewaysResponse convert(CloudGateWays source) { Map<String, Set result = new HashMap<>(); for (Entry<String, Set entry : source.getCloudGateWayResponses().entrySet()) { Set cloudGatewayJsons = new HashSet<>(); for (CloudGateWay gateway : entry.getValue()) { CloudGatewayJson actual = new CloudGatewayJson(gateway.getName(), gateway.getId(), gateway.getProperties()); cloudGatewayJsons.add(actual); } result.put(entry.getKey(), cloudGatewayJsons); } return new PlatformGatewaysResponse(result); } }
java
15
0.747195
153
40.78125
32
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using Bhp.Wallets.BRC6; using Bhp.Wallets; using Bhp.Properties; using Bhp.IO.Json; namespace Bhp.UI { public partial class FrmCreateWallets : Form { public FrmCreateWallets() { InitializeComponent(); } string path = string.Empty; string password = "1"; private WalletIndexer indexer = null; private WalletIndexer GetIndexer() { if (indexer is null) indexer = new WalletIndexer(Settings.Default.Paths.Index); return indexer; } /// /// choose path /// /// <param name="sender"> /// <param name="e"> private void button1_Click(object sender, EventArgs e) { using (FolderBrowserDialog dialog = new FolderBrowserDialog()) { if(dialog.ShowDialog() == DialogResult.OK) { this.txt_dir.Text = dialog.SelectedPath; path = dialog.SelectedPath; } } } /// /// create wallets /// /// <param name="sender"> /// <param name="e"> private void button2_Click(object sender, EventArgs e) { int num = int.Parse(this.txt_num.Text.Trim()); if (num <= 0) return; if (String.IsNullOrEmpty(path)) return; listBox1.Items.Clear(); Task task = new Task(() => { CreateWallets(num); }); task.Start(); } /// /// create wallets /// /// <param name="num"> private void CreateWallets(int num) { List wss = new List for (int i = 0; i < num; i++) { string walletName = $"wallet{i}.json"; string spath = Path.Combine(path, walletName); if (File.Exists(spath)) continue; BRC6Wallet wallet = new BRC6Wallet(GetIndexer(), spath); wallet.Unlock(password); wallet.CreateAccount(); wallet.Save(); WalletSnapshot ws = new WalletSnapshot(); ws.walletName = walletName; ws.address = wallet.GetAccounts().ToArray()[0].Address; ws.priKey = wallet.GetAccount(ws.address.ToScriptHash()).GetKey().PrivateKey.ToHexString(); ws.pubKey = wallet.GetAccount(ws.address.ToScriptHash()).GetKey().PublicKey.ToString(); ws.script = wallet.GetAccounts().ToArray()[0].Contract.ScriptHash.ToString(); wss.Add(ws); this.Invoke(new Action(() => { listBox1.Items.Add($"{i} : {spath}"); })); } JObject json = new JObject(); json = new JArray(wss.Select(p => { JObject jobj = new JObject(); jobj["walletName"] = p.walletName; jobj["address"] = p.address; jobj["privKye"] = p.priKey; jobj["pubKye"] = p.pubKey; jobj["script"] = p.script; return jobj; })); File.WriteAllLines(Path.Combine(path, "walletsnapshot.txt"), new string[] { json.ToString()}); } private void FrmCreateWallets_FormClosing(object sender, FormClosingEventArgs e) { if(indexer != null) { indexer.Dispose(); } } }//end of class }
c#
24
0.490038
118
32.319328
119
starcoderdata
import pytest @pytest.mark.skip("skip until migrated to snappi") def test_json_config(serializer, api, tx_port, rx_port, b2b_devices): config = Config(ports=[tx_port, rx_port], devices=b2b_devices) state = State(ConfigState(config=config, state="set")) state = serializer.json(state) api.set_state(state) @pytest.mark.skip("skip until migrated to snappi") def test_dict_config(serializer, api, tx_port, rx_port, b2b_devices): config = Config(ports=[tx_port, rx_port], devices=b2b_devices) state = State(ConfigState(config=config, state="set")) state = serializer.json_to_dict(serializer.json(state)) api.set_state(state) @pytest.mark.skip("skip until migrated to snappi") def test_config(serializer, api, tx_port, rx_port, b2b_devices): config = Config(ports=[tx_port, rx_port], devices=b2b_devices) state = State(ConfigState(config=config, state="set")) api.set_state(state) if __name__ == "__main__": pytest.main(["-s", __file__])
python
12
0.690597
69
34.321429
28
starcoderdata
import itertools class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for x in list(itertools.combinations((nums), 2)): if x[0] == x[1]: count += 1 return count
python
11
0.526667
57
24.083333
12
starcoderdata
pub fn hit(&self, ray: &Ray, mut t_min: f64, mut t_max: f64) -> bool { // Maybe do this with SIMD intrinsics? // Check all directions at once for a in 0..3 { let inv_d = ray.inv_dir().get(a); let mut t0 = (self.min.get(a) - ray.origin().get(a)) * inv_d; let mut t1 = (self.max.get(a) - ray.origin().get(a)) * inv_d; if inv_d < 0.0 { ::std::mem::swap(&mut t0, &mut t1); } t_min = if t0 > t_min { t0 } else { t_min }; t_max = if t1 < t_max { t1 } else { t_max }; if t_max < t_min { return false; } } true }
rust
14
0.424419
73
37.277778
18
inline
package client; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import br.ufc.mdcc.hpcshelf.backend.BackEndPortType; import br.ufc.mdcc.hpcshelf.backend.BackEndService; import br.ufc.mdcc.hpcshelf.backend.Error; import br.ufc.mdcc.hpcshelf.backend.types.ProfilesIds; import br.ufc.mdcc.hpcshelf.backend.types.ProfilesIdsList; public class BackServicesClient { public static void main(String[] args) { try { String backEndServicesURL = "http://" + args[0] + ":8000/backendservices/wsdl"; System.out.println(backEndServicesURL); BackEndService service = new BackEndService(new URL(backEndServicesURL)); BackEndPortType port = service.getBackEndPort(); System.out.println("Available Profiles:"); ProfilesIdsList profileList = port.availableProfiles(); List item = profileList.getItem(); for (ProfilesIds profilesIds : item) { System.out.println(profilesIds.getProfileId() + ":" + profilesIds.getProfileName()); } System.out.println("Creating Profile: 321, Session ID: 104"); String profile0ID = port.deployContractCallback("321", "104"); System.out.println("Session ID:" + profile0ID); // System.out.println("Creating Profile: 1, Session ID: 105"); // String profile1ID = port.deployContractCallback("1", "105"); String status0 = port.platformDeploymentStatus(profile0ID); // String status1 = port.platformDeploymentStatus(profile1ID); while ( !status0.equals("CREATED") /* && !status1.equals("CREATED") */) { System.out.println("Status 0:" + status0); // System.out.println("Status 1:" + status1); Thread.sleep(15000); status0 = port.platformDeploymentStatus(profile0ID); // status1 = port.platformDeploymentStatus(profile1ID); } System.out.println("Destroying Profile: 0, Session ID: 104"); port.destroyPlatform(profile0ID); //System.out.println("Destroying Profile: 1, Session ID: 105"); //port.destroyPlatform(profile1ID); } catch (MalformedURLException e) { e.printStackTrace(); } catch (Error e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java
16
0.718166
88
35.225806
62
starcoderdata
const PageCalendar = require('../../../src/components/Calendar/pageObject'); const CALENDAR = '#calendar-1'; describe('Calendar', () => { beforeAll(() => { browser.url('/#!/Calendar/1'); }); beforeEach(() => { browser.refresh(); const component = $(CALENDAR); component.waitForExist(); }); it('should change selected month when clicked on left and right arrows', () => { const calendar = new PageCalendar(CALENDAR); expect(calendar.getSelectedMonth()).toBe('December'); calendar.clickPrevMonthButton(); expect(calendar.getSelectedMonth()).toBe('November'); calendar.clickNextMonthButton(); calendar.clickNextMonthButton(); expect(calendar.getSelectedMonth()).toBe('January'); }); it('should select the rigth day button element', () => { const calendar = new PageCalendar(CALENDAR); expect(calendar.getSelectedDay()).toBe('6'); calendar.clickDay(4); expect(calendar.getSelectedDay()).toBe('4'); }); it('should change year when month is December and click next month button', () => { const calendar = new PageCalendar(CALENDAR); expect(calendar.getSelectedMonth()).toBe('December'); expect(calendar.getSelectedYear()).toBe('2019'); calendar.clickNextMonthButton(); expect(calendar.getSelectedMonth()).toBe('January'); expect(calendar.getSelectedYear()).toBe('2020'); }); });
javascript
16
0.634178
87
39.5
38
starcoderdata
using System.Threading.Tasks; using Moq; using TripleDerby.Core.DTOs; using TripleDerby.Core.Entities; using TripleDerby.Core.Specifications; using Xunit; namespace TripleDerby.Core.Tests.Services.FeedingServiceTests { public class Get : FeedingServiceTestBase { private readonly byte _id; private readonly Feeding _feeding; public Get() { _id = 4; _feeding = new Feeding { Id = _id }; Repository.Setup(x => x.Get(It.IsAny } [Fact] public async Task ItReturnsFeeding() { // Arrange // Act var feeding = await Service.Get(_id); // Assert Assert.NotNull(feeding); Assert.IsAssignableFrom } } }
c#
21
0.567681
98
23.435897
39
starcoderdata
package com.scs.killercrates.components; public interface IBullet extends ICollideable { ICanShoot getShooter(); }
java
5
0.798319
47
16
7
starcoderdata
componentDidMount(){ // need to be refactor with timing function. let animationHub = []; const animation = new Animated.Value(0); animation.addListener(({value}) => { this.setState({ progress:value }) }) Animated.timing(animation,{ toValue:1, duration:1500, easing:Easing.bounce }).start(); }
javascript
12
0.647416
46
17.333333
18
inline
@Override public void onClick(View v) { //Check for Runtime Permission if ( ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "Call for Permission", Toast.LENGTH_SHORT).show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE); } } else { callgalary(); } }
java
14
0.518219
125
45.375
16
inline
# coding: utf-8 import numpy as np from fastdtw import fastdtw from dynamic import dynamic_time_warp from scipy.spatial.distance import hamming class WARPAlgorithm(object): """ WARP algorithm implementation based on fastDTW """ def __init__(self, sequence): self.sequence = sequence self.candidates = [] self.min_dist = np.inf self.size = self.sequence.size def get_candidates(self): """ implementation of WARP algorithm with fast Dynamic Time Warping techology :return: list of candidates where each candidate is (period_size, distance, path in cost matrix) """ for i in range(1, len(self.sequence) / 2): distance, path = fastdtw( np.array(self.sequence[i:]), np.array(self.sequence[:self.size - i]), dist=hamming ) self.candidates.append((i, distance, path)) return self.candidates def get_sorted_candidates(self): """ sorted by distance candidates :return: """ return sorted(self.get_candidates(), key=lambda key: key[1]) def get_certain_period(self): """ :return: period length = the best candidate """ candidates = self.get_sorted_candidates() return int(candidates[0][0]) def get_best_candidates(self): """ boundary: in every second period is possible to make a mistake :return: list of candidates """ return [c[0] for c in self.get_sorted_candidates() if c[1] < 0.5 * (self.size / c[0])] class WARPPoorAlgorithm(WARPAlgorithm): def __init__(self, sequence): super(WARPPoorAlgorithm, self).__init__(sequence) def get_candidates(self): for i in range(1, len(self.sequence) / 2): cost = dynamic_time_warp( np.array(self.sequence[i:]), np.array(self.sequence[:self.size - i]), d=hamming ) distance = cost[-1, -1] self.candidates.append((i, distance)) return np.array(self.candidates)
python
17
0.574343
70
28.810811
74
starcoderdata
// Copyright (c) 2017 // // 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 vox const CubeSize = 1.0 type Mesher interface { Generate(chunk *Chunk, bank *BlockBank) *MeshData } // ---------------------------------------------------------------------------- type CulledMesher struct { } func (cm *CulledMesher) Generate(chunk *Chunk, bank *BlockBank) *MeshData { data := &MeshData{} // these are the offset in world coordinates of the chunk xOffset := float32(chunk.Position.X) * ChunkWidth yOffset := float32(chunk.Position.Y) * ChunkHeight zOffset := float32(chunk.Position.Z) * ChunkDepth hasFace := false for x := 0; x < ChunkWidth; x++ { for z := 0; z < ChunkDepth; z++ { for y := 0; y < ChunkHeight; y++ { // skip block if inactive block := chunk.Get(x, y, z) if !block.Active() { continue } blockType := bank.TypeOf(block) // get offsets xx := xOffset + float32(x) yy := yOffset + float32(y) zz := zOffset + float32(z) // get sourrounding neighbors left := chunk.Get(x-1, y, z) right := chunk.Get(x+1, y, z) top := chunk.Get(x, y+1, z) bottom := chunk.Get(x, y-1, z) front := chunk.Get(x, y, z+1) back := chunk.Get(x, y, z-1) // left face hasFace = left == BlockNil && (chunk.left == nil || !chunk.left.Get(ChunkWidth-1, y, z).Active()) // check if adjacient chunk has occluding block hasFace = hasFace || left != BlockNil && !left.Active() // check if there is a adjacient block in the same chunk if hasFace { cm.addLeftFace(xx, yy, zz, data, blockType) } // right face hasFace = right == BlockNil && (chunk.right == nil || !chunk.right.Get(0, y, z).Active()) hasFace = hasFace || right != BlockNil && !right.Active() if hasFace { cm.addRightFace(xx, yy, zz, data, blockType) } // top face hasFace = top == BlockNil && (chunk.top == nil || !chunk.top.Get(x, 0, z).Active()) hasFace = hasFace || top != BlockNil && !top.Active() if hasFace { cm.addTopFace(xx, yy, zz, data, blockType) } // bottom face hasFace = bottom == BlockNil && (chunk.bottom == nil || !chunk.bottom.Get(x, ChunkHeight-1, z).Active()) hasFace = hasFace || bottom != BlockNil && !bottom.Active() if hasFace { cm.addBottomFace(xx, yy, zz, data, blockType) } // front face hasFace = front == BlockNil && (chunk.front == nil || !chunk.front.Get(x, y, 0).Active()) hasFace = hasFace || front != BlockNil && !front.Active() if hasFace { cm.addFrontFace(xx, yy, zz, data, blockType) } // back face hasFace = back == BlockNil && (chunk.back == nil || !chunk.back.Get(x, y, ChunkDepth-1).Active()) hasFace = hasFace || back != BlockNil && !back.Active() if hasFace { cm.addBackFace(xx, yy, zz, data, blockType) } } } } if len(data.Positions) == 0 { return nil } return data } func (cm *CulledMesher) addUvs(data *MeshData, region *TextureRegion) { uvs := &region.Uvs data.Uvs = append(data.Uvs, uvs[0].X, uvs[0].Y, uvs[1].X, uvs[1].Y, uvs[2].X, uvs[2].Y, uvs[3].X, uvs[3].Y, ) } func (cm *CulledMesher) addLeftFace(x, y, z float32, data *MeshData, blockType *BlockType) { data.Positions = append(data.Positions, x, y, z-CubeSize, x, y, z, x, y+CubeSize, z, x, y+CubeSize, z-CubeSize, ) data.Normals = append(data.Normals, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, ) cm.addUvs(data, blockType.Side) data.IndexCount += 6 } func (cm *CulledMesher) addRightFace(x, y, z float32, data *MeshData, blockType *BlockType) { data.Positions = append(data.Positions, x+CubeSize, y, z, x+CubeSize, y, z-CubeSize, x+CubeSize, y+CubeSize, z-CubeSize, x+CubeSize, y+CubeSize, z, ) data.Normals = append(data.Normals, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, ) cm.addUvs(data, blockType.Side) data.IndexCount += 6 } func (cm *CulledMesher) addTopFace(x, y, z float32, data *MeshData, blockType *BlockType) { data.Positions = append(data.Positions, x, y+CubeSize, z, x+CubeSize, y+CubeSize, z, x+CubeSize, y+CubeSize, z-CubeSize, x, y+CubeSize, z-CubeSize, ) data.Normals = append(data.Normals, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, ) cm.addUvs(data, blockType.Top) data.IndexCount += 6 } func (cm *CulledMesher) addBottomFace(x, y, z float32, data *MeshData, blockType *BlockType) { data.Positions = append(data.Positions, x, y, z, x+CubeSize, y, z, x+CubeSize, y, z-CubeSize, x, y, z-CubeSize, ) data.Normals = append(data.Normals, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, ) cm.addUvs(data, blockType.Bottom) data.IndexCount += 6 } func (cm *CulledMesher) addFrontFace(x, y, z float32, data *MeshData, blockType *BlockType) { data.Positions = append(data.Positions, x, y, z, x+CubeSize, y, z, x+CubeSize, y+CubeSize, z, x, y+CubeSize, z, ) data.Normals = append(data.Normals, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ) cm.addUvs(data, blockType.Side) data.IndexCount += 6 } func (cm *CulledMesher) addBackFace(x, y, z float32, data *MeshData, blockType *BlockType) { data.Positions = append(data.Positions, x, y, z-CubeSize, x+CubeSize, y, z-CubeSize, x+CubeSize, y+CubeSize, z-CubeSize, x, y+CubeSize, z-CubeSize, ) data.Normals = append(data.Normals, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, ) cm.addUvs(data, blockType.Side) data.IndexCount += 6 }
go
20
0.615721
158
25.941176
221
starcoderdata
nba_stats_columns = [ "PLAYER_ID", "PLAYER_NAME", # "Player": "player_name" "TEAM_ID", "TEAM_ABBREVIATION", # "Tm": "team_abbreviation" "AGE", # "Age": "age" "GP", # "G": "gp" "W", "L", "W_PCT", "MIN", # "MP": "min" "FGM", # "FG": "fgm" "FGA", # "FGA": "fga" "FG_PCT", # "FG%": "fg_pct" "FG3M", # "3P": "fg3m" "FG3A", # "3PA": "fg3a" "FG3_PCT", # "3P%": "fg3_pct" "FTM", # "FT": "ftm" "FTA", # "FTA": "fta" "FT_PCT", # "FT%": "ft_pct" "OREB", # "ORB": "oreb" "DREB", # "DRB": "dreb" "REB", # "TRB": "reb" "AST", # "AST": "ast" "TOV", # "TOV": "tov" "STL", # "STL": "stl" "BLK", # "BLK": "blk" "BLKA", "PF", # "PF": "pf" "PFD", "PTS", # "PTS": "pts" "PLUS_MINUS", "NBA_FANTASY_PTS", "DD2", "TD3", "GP_RANK", "W_RANK", "L_RANK", "W_PCT_RANK", "MIN_RANK", "FGM_RANK", "FGA_RANK", "FG_PCT_RANK", "FG3M_RANK", "FG3A_RANK", "FG3_PCT_RANK", "FTM_RANK", "FTA_RANK", "FT_PCT_RANK", "OREB_RANK", "DREB_RANK", "REB_RANK", "AST_RANK", "TOV_RANK", "STL_RANK", "BLK_RANK", "BLKA_RANK", "PF_RANK", "PFD_RANK", "PTS_RANK", "PLUS_MINUS_RANK", "NBA_FANTASY_PTS_RANK", "DD2_RANK", "TD3_RANK", "CFID", "CFPARAMS", ] basketball_reference_columns = [ "Player", "Pos", "Age", "Tm", "G", "GS", "MP", "FG", "FGA", "FG%", "3P", "3PA", "3P%", "2P", "2PA", "2P%", "eFG%", "FT", "FTA", "FT%", "ORB", "DRB", "TRB", "AST", "STL", "BLK", "TOV", "PF", "PTS", ] rename_these_columns = { "Player": "player_name", "Tm": "team_abbreviation", "Age": "age", "G": "gp", "MP": "min", "FG": "fgm", "FGA": "fga", "FG%": "fg_pct", "3P": "fg3m", "3PA": "fg3a", "3P%": "fg3_pct", "FT": "ftm", "FTA": "fta", "FT%": "ft_pct", "ORB": "oreb", "DRB": "dreb", "TRB": "reb", "AST": "ast", "TOV": "tov", "STL": "stl", "BLK": "blk", "PF": "pf", "PTS": "pts", } drop_these_columns = [ "Player", "Tm", "Age", "G", "MP", "FG", "FGA", "FG%", "3P", "3PA", "3P%", "FT", "FTA", "FT%", "ORB", "DRB", "TRB", "AST", "TOV", "STL", "BLK", "PF", "PTS", ] drop_these_columns_refactored = [ "player_name", "team_abbreviation", "age", "gp", "min", "fgm", "fga", "fg_pct", "fg3m", "fg3a", "fg3_pct", "ftm", "fta", "ft_pct", "oreb", "dreb", "reb", "ast", "tov", "stl", "blk", "pf", "pts", ] # Converts a basketball reference season to a season recognized by stats.nba.com (2019 -> 2018-19) def convert_bbref_season_to_nba_season(season): year = int(season) last_year = year - 1 last_two = season[-2:] return "{0}-{1}".format(last_year, last_two)
python
8
0.404324
98
15.66129
186
starcoderdata
window.onload = () => { const englishChoice = document.getElementById("english-switch-option"); const turkishChoice = document.getElementById("turkish-switch-option"); englishChoice.addEventListener("click", () => { turkishChoice.style.display = "flex"; englishChoice.style.display = "none"; }); turkishChoice.addEventListener("click", () => { turkishChoice.style.display = "none"; englishChoice.style.display = "flex"; }); };
javascript
14
0.681128
73
26.176471
17
starcoderdata
def units(model_name, dat, let, uindex, pindex): """ Read parameters pindex from unit uindex pindex: 1 - Porosity 4 - Permeability 8 - Thermal conductivity 10 - Volumetric heat capacity """ # Define path and file output_path = rm.make_output_dirs(model_name, dat, let)[0] input_file = rm.make_file_dir_names(model_name)[2] # Read hashtag input lines = rm.read_hashtag_input(output_path+'/'+input_file, '# units', uindex) # Split hashtag input by white space split_lines = str.split(lines) # Find the number of parameters per line num_ps = len(split_lines)/uindex # Calculate the index of the right parameter right_index = (uindex-1)*num_ps + pindex right_entry = split_lines[right_index] return right_entry
python
10
0.631325
62
27.655172
29
inline
import React, {Component} from 'react' import logo from './logo.png' import './App.css' import GCodeEdit from './components/GCodeEdit' import ConnectPanel from './components/ConnectPanel' import ActionPanel from './components/ActionPanel' import LogPanel from './components/LogPanel' class App extends Component { constructor() { super() this.state = { connected: false } this.onConnectChange = this.onConnectChange.bind(this) this.onExecute = this.onExecute.bind(this) this.clearBatchLog = this.clearBatchLog.bind(this) this.batchLogRef = React.createRef() } onConnectChange(connected) { this.setState({ connected: connected }) } onExecute() { this.clearBatchLog() console.log("EXEC") } clearBatchLog() { this.batchLogRef.current.setState({log: "", next: 0}) } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" id="logo"/> <ConnectPanel onConnectChange={this.onConnectChange} preConnect={this.clearBatchLog}/> <div id="appContainer"> <div id="leftPanel"> <div className="header">GCODE <div id="middlePanel"> <div className="header">ACTION <ActionPanel onExecute={this.onExecute.bind(this)} connected={this.state.connected}/> <div id="rightPanel"> <div className="header">LOG <LogPanel ref={this.batchLogRef}/> ) } } export default App
javascript
14
0.513191
106
29.439394
66
starcoderdata
package com.ddx.chiamon.node.main.servlet; import com.ddx.chiamon.common.data.ClientAccess; import com.ddx.chiamon.common.data.json.DateLong; import com.ddx.chiamon.db.DB; import com.ddx.chiamon.db.FetcherClient; import com.ddx.chiamon.db.Storage; import com.ddx.chiamon.utils.StringConv; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.util.Date; /** * * @author ddx */ public class ClientService extends CommonServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String cmd = req.getParameter("cmd"); ClientAccess clientAccess = new ClientAccess(); clientAccess.setUid(req.getParameter("client_id")); clientAccess.setIp(req.getRemoteAddr()); clientAccess.setDt(new Date()); clientAccess.setCmd(cmd); Object exp = null; String tmp; try { if (cmd == null || cmd.length() == 0) { // nothing to do } else if (cmd.equals("getHarvesterNodes")) { long period = Long.parseLong(req.getParameter("period")); exp = FetcherClient.getHarvesterNodes(new Date(System.currentTimeMillis()-period)); } else if (cmd.equals("getHarvesterNodesList")) { exp = FetcherClient.getHarvesterNodesList(); } else if (cmd.equals("getHarvesterNodesAndDisksList")) { exp = FetcherClient.getHarvesterNodesAndDisksList(); } else if (cmd.equals("getLogsFarm")) { long[] ids = StringConv.String2LongArray(req.getParameter("ids")); Date dtFrom = DateLong.getFormatter().parse(req.getParameter("dtFrom")); tmp = req.getParameter("dtTo"); Date dtTo = tmp!=null?DateLong.getFormatter().parse(tmp):new Date(); exp = FetcherClient.getLogsFarm(dtFrom, dtTo, ids); } else if (cmd.equals("getReadAccess")) { long[] ids = StringConv.String2LongArray(req.getParameter("ids")); Date dtFrom = DateLong.getFormatter().parse(req.getParameter("dtFrom")); tmp = req.getParameter("dtTo"); Date dtTo = tmp!=null?DateLong.getFormatter().parse(tmp):new Date(); exp = FetcherClient.getReadAccess(dtFrom, dtTo, ids); } else if (cmd.equals("getSmartAccess")) { long[] ids = StringConv.String2LongArray(req.getParameter("ids")); Date dtFrom = DateLong.getFormatter().parse(req.getParameter("dtFrom")); tmp = req.getParameter("dtTo"); Date dtTo = tmp!=null?DateLong.getFormatter().parse(tmp):new Date(); exp = FetcherClient.getDiskSmart(dtFrom, dtTo, ids); } else if (cmd.equals("db")) { exp = DB.checkConnection(); } else { // command not found } if (exp != null) { res.setContentType("application/json"); mapper.writeValue(res.getOutputStream(), exp); clientAccess.setSuccess(true); } } catch (Exception ex) { ex.printStackTrace(); getServletContext().log("["+cmd+"] error", ex); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { try { Storage.insertClientAccess(clientAccess); } catch (Exception ex) { getServletContext().log("insertClientAccess", ex); } } } }
java
22
0.544385
165
34.163793
116
starcoderdata
module.exports = function FormatService() { return { geopackage: "Geo Package", mbtiles: "MBTiles", xyz: "XYZ", tms: "TMS", geotiff: "GeoTIFF", shapefile: "Shapefile", geojson: "GeoJSON", kml: "KML", gpx: "GPX", wms: "Web Map Service (WMS)", kmz: "KMZ/KML", mrsid: "MrSID", arcgis: "ArcGIS" }; };
javascript
9
0.548023
43
18.666667
18
starcoderdata
package io.github.hoojo.example.repository; import io.github.hooj0.springdata.template.annotations.Query; import io.github.hooj0.springdata.template.repository.TemplateRepository; import io.github.hoojo.example.entity.User; /** * example repo * @author hoojo * @createDate 2018年7月16日 上午9:22:38 * @file ExampleRepotisory.java * @package io.github.hoojo.example.repository * @project spring-data-template-example * @blog http://hoojo.cnblogs.com * @email * @version 1.0 */ public interface ExampleRepotsitory extends TemplateRepository<User, Long> { User findByName(String name); User findBySexAndAge(boolean sex, int age); @Query("select * from User where name = ?0 and nick_name = ?1") User findBySQL(String name, String nickName); }
java
8
0.758874
76
29.259259
27
starcoderdata
namespace Sizmon.Domain { using System.Diagnostics; using Newtonsoft.Json.Linq; public class SizProcess : IToJson { private readonly Process processInfo; public SizProcess(Process processInfo) { this.processInfo = processInfo; } public JObject ToJson() { if (processInfo != null) { var json = new JObject(); json["ProcessName"] = processInfo.ProcessName; json["WorkingSet64"] = processInfo.WorkingSet64; return json; } else return null; } } }
c#
15
0.510511
64
20.483871
31
starcoderdata
using NPOI.SS.Formula.Eval; using System.Text; namespace NPOI.SS.Formula.Functions { /// @author &lt; amolweb at ya hoo dot com &gt; public class Concatenate : TextFunction { public override ValueEval EvaluateFunc(ValueEval[] args, int srcCellRow, int srcCellCol) { StringBuilder stringBuilder = new StringBuilder(); int i = 0; for (int num = args.Length; i < num; i++) { stringBuilder.Append(TextFunction.EvaluateStringArg(args[i], srcCellRow, srcCellCol)); } return new StringEval(stringBuilder.ToString()); } } }
c#
19
0.708633
90
26.8
20
starcoderdata
package com.redhat.consulting.fusequickstarts.springboot.restconsumer.restxml; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RestXmlApplication { public static void main(String[] args) { SpringApplication.run(RestXmlApplication.class, args); } }
java
7
0.831283
192
39.642857
14
starcoderdata
// Turns on debug information of the ArduinoHA core. // Please note that you need to initialize serial interface manually // by calling Serial.begin([baudRate]) before initializing ArduinoHA. // #define ARDUINOHA_DEBUG // You can reduce Flash size of the compiled library by commenting unused components below #define ARDUINOHA_BINARY_SENSOR #define ARDUINOHA_COVER #define ARDUINOHA_FAN #define ARDUINOHA_HVAC #define ARDUINOHA_SENSOR #define ARDUINOHA_SWITCH #define ARDUINOHA_TAG_SCANNER #define ARDUINOHA_TRIGGERS #define ARDUINOHA_LIGHT #ifdef __GNUC__ #define AHA_DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define AHA_DEPRECATED(func) __declspec(deprecated) func #else #warning "Arduino Home Assistant: You may miss deprecation warnings." #define AHA_DEPRECATED(func) func #endif
c
6
0.790499
90
33.208333
24
starcoderdata
async def name_to_uuid(self, player: str): try: self.uuidcache[player] except KeyError: route = Route( 'GET', f'/users/profiles/minecraft/{player}' ) try: profile = await self.bot.http.mojang.request(route) if profile: self.uuidcache.update({player: profile['id']}) except Exception: pass # whatever is using this should check for None return self.uuidcache.get(player, None)
python
17
0.672986
56
27.2
15
inline
protected void initialize(String baseurl, String user, String password, String connect, String read) { // store Base URL this.baseurl = baseurl; this.user = user; this.password = password; this.connect = connect; this.read = read; // create HTTP Client this.client = ClientBuilder.newClient(); // Fix timeout client.property(ClientProperties.CONNECT_TIMEOUT, Integer.parseInt(connect)); client.property(ClientProperties.READ_TIMEOUT, Integer.parseInt(read)); // register auth feature if user is not null if(user != null) { HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(user, password); client.register(feature); } // Mapper mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new JodaModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); }
java
9
0.729785
102
34.259259
27
inline
func NewS3Connection(configuration ConfigStruct) (*minio.Client, context.Context, error) { s3Configuration := GetS3Configuration(configuration) endpoint := fmt.Sprintf("%s:%d", s3Configuration.EndpointURL, s3Configuration.EndpointPort) log.Info().Str("S3 endpoint", endpoint).Msg("Preparing connection") ctx := context.Background() // Initialize minio client object minioClient, err := minio.New(endpoint, &minio.Options{ Creds: credentials.NewStaticV4( s3Configuration.AccessKeyID, s3Configuration.SecretAccessKey, ""), Secure: s3Configuration.UseSSL, }) if err != nil { log.Error().Err(err).Msg("Unable to initialize connection to S3") return nil, nil, err } log.Info().Msg("Connection established") return minioClient, ctx, nil }
go
15
0.743455
90
29.6
25
inline
const app = require('express')(); const server = require('http').createServer(app); const io = require('socket.io')(server); const Message = require('./app/models/Message'); const usersArray = []; server.listen(3001, () => { console.log('Running on port 3001'); }); io.on('connection', socket => { socket.on('user-connect', async (userData) => { userData.socketId = socket.id; usersArray.push(userData); io.sockets.emit('users-connected', usersArray); console.log('Users online: ' + usersArray.length); try { const messages = await Message.find(); io.sockets.emit('old-messages', messages); } catch (err) { io.sockets.emit('error', err); } }); socket.on('send-message', async (messageData) => { try { const newMessage = await Message.create(messageData); console.log('> ' + messageData.username + ':' + messageData.message); io.sockets.emit('new-message', newMessage); } catch (err) { console.log(err); io.sockets.emit('error', err); } }); socket.on('disconnect', () => { usersArray.map((user, index) => { if(usersArray[index].socketId === socket.id) return usersArray.splice(index, 1); }); console.log('Users online: ' + usersArray.length); io.sockets.emit('users-connected', usersArray); }); });
javascript
18
0.623252
75
26.2
50
starcoderdata
package hr.fer.zemris.ooup.lab3.zad_2.observers.stack; import hr.fer.zemris.ooup.lab3.zad_2.actions.edit.IEditAction; import java.util.*; /** * @author */ public class UndoManager { private static UndoManager instance; private Stack undoStack; private Stack redoStack; private Set undoObservers; private Set redoObservers; private UndoManager() { this.undoStack = new Stack<>(); this.redoStack = new Stack<>(); this.undoObservers = new HashSet<>(); this.redoObservers = new HashSet<>(); } public static UndoManager getInstance() { if(instance == null) { instance = new UndoManager(); } return instance; } public void clear() { this.undoStack.clear(); this.redoStack.clear(); notifyRedoObservers(); notifyUndoObservers(); } public void push(IEditAction action) { redoStack.clear(); notifyRedoObservers(); undoStack.push(action); notifyUndoObservers(); } public void undo() { if (undoStack.isEmpty()) { notifyUndoObservers(); return; } IEditAction action = undoStack.pop(); notifyUndoObservers(); action.executeUndo(); redoStack.push(action); notifyRedoObservers(); } public void redo() { if (redoStack.isEmpty()) { notifyRedoObservers(); return; } IEditAction action = redoStack.pop(); notifyRedoObservers(); action.executeDo(); undoStack.push(action); notifyUndoObservers(); } public boolean addUndoObserver(StackObserver observer) { return undoObservers.add(observer); } public boolean removeUndoObserver(StackObserver observer) { return undoObservers.remove(observer); } private void notifyUndoObservers() { boolean isEmpty = undoStack.isEmpty(); undoObservers.forEach((observer) -> observer.updateStack(isEmpty)); } public boolean addRedoObserver(StackObserver observer) { return redoObservers.add(observer); } public boolean removeRedoObserver(StackObserver observer) { return redoObservers.remove(observer); } private void notifyRedoObservers() { boolean isEmpty = redoStack.isEmpty(); redoObservers.forEach((observer) -> observer.updateStack(isEmpty)); } }
java
11
0.622328
75
23.057143
105
starcoderdata
def stop(self, signum=None, frame=None): """ Stop the zygote master. Steps: * Ask all zygotes to kill and wait on their children * Wait for zygotes to exit * Kill anything left over if necessary """ if self.stopped: return # kill all of the workers self.logger.info('stopping all zygotes and workers') pids = set() for zygote in self.zygote_collection: pids.add(zygote.pid) self.logger.debug('requesting shutdown on %d', zygote.pid) zygote.request_shut_down() self.logger.debug('setting self.stopped') self.stopped = True self.logger.debug('master is stopping. will not try to update anymore.') signal.signal(signal.SIGHUP, signal.SIG_IGN) self.logger.debug('stopping io_loop.') if getattr(self, 'io_loop', None) is not None: self.io_loop.stop() self.logger.info('waiting for workers to exit before stoping master.') wait_for_pids(pids, self.WAIT_FOR_KILL_TIME, self.logger, kill_pgroup=True) self.logger.info('all zygotes exited; good night') self.really_stop(0)
python
9
0.606489
83
36.59375
32
inline
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mail; use App\Http\Requests\EmailReq; use App\Mail\Email; class EmailCon extends Controller { public function kirim(EmailReq $request){ $kontak = [ 'nama' => $request->input('nama'), 'pesan' => $request->input('pesan'), 'email' => $request->input('email') ]; $emailAdmin = setting('site.email'); if (!Mail::to($emailAdmin)->send(new Email($kontak))) { $status = session()->flash('status','Pesan Terkirim, Terima Kasih'); }else{ $status = session()->flash('status','Pesan Tidak Terkirim, Mohon Coba Lagi'); } return redirect('/'); } }
php
15
0.56393
89
22.967742
31
starcoderdata
def extract_keywords(sites, k=10): """ Extract top k most frequent keywords """ stop = stopwords.words('english') counter = Counter() for site in sites: for p in site: text = p.get_text('meta') text = URLUtility.clean_text(text) words = word_tokenize(text) words = [word for word in words if word not in stop and len(word)>2] counter += Counter(words) # Get the topk words counter = [(counter[w], w) for w in counter if counter[w]>1] # convert to array heapq.heapify(counter) topk = heapq.nlargest(k, counter) print "Top extracted keywords: ", topk return [w[1] for w in topk]
python
15
0.590258
83
33.95
20
inline
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/home', 'HomeController@index')->name('home'); Route::get('/', 'HomeController@index')->name('home'); Auth::routes(); Route::middleware('auth')->group(function () { // Route::get('/users','UserController@index')->middleware('role:admin'); Route::middleware('role:admin')->group(function () { Route::get('/users', 'UserController@index'); Route::get('/roleUser/{id}', 'UserController@edit_role'); Route::post('/updateUserRole/{id}', 'UserController@update_role'); Route::get('/groupUser/{id}', 'UserController@edit_group'); Route::post('/updateUserGroup/{id}', 'UserController@update_group'); Route::get('/deleteUser/{id}', 'UserController@destroy'); Route::get('roles', 'RoleController@index'); Route::get('createRole', 'RoleController@create'); Route::post('storeRole', 'RoleController@store'); Route::post('updateRole/{id}', 'RoleController@update'); Route::get('deleteRole/{id}', 'RoleController@destroy'); Route::get('editRole/{id}', 'RoleController@edit'); Route::get('permissions', 'PermissionController@index'); Route::get('createPermission', 'PermissionController@create'); Route::post('storePermission', 'PermissionController@store'); Route::post('updatePermission/{id}', 'PermissionController@update'); Route::get('deletePermission/{id}', 'PermissionController@destroy'); Route::get('editPermission/{id}', 'PermissionController@edit'); Route::get('groups', 'GroupController@index'); Route::get('createGroup', 'GroupController@create'); Route::post('storeGroup', 'GroupController@store'); Route::post('updateGroup/{id}', 'GroupController@update'); Route::get('deleteGroup/{id}', 'GroupController@destroy'); Route::get('editGroup/{id}', 'GroupController@edit'); Route::get('tags', 'TagController@index'); Route::get('createTag', 'TagController@create'); Route::post('storeTag', 'TagController@store'); Route::post('updateTag/{id}', 'TagController@update'); Route::get('deleteTag/{id}', 'TagController@destroy'); Route::get('editTag/{id}', 'TagController@edit'); }); Route::get('reports', 'ReportController@index'); Route::get('createReport', 'ReportController@create'); Route::post('storeReport', 'ReportController@store'); Route::post('updateReport/{id}', 'ReportController@update'); Route::get('deleteReport/{id}', 'ReportController@destroy'); Route::get('editReport/{id}', 'ReportController@edit'); Route::get('showReport/{id}', 'ReportController@show'); Route::get('search', 'ReportController@search'); });
php
18
0.622152
76
40.038961
77
starcoderdata
package bucketing import ( "testing" ) func testTargetingNumber(operator TargetingOperator, targetingValue float64, value float64, t *testing.T, shouldMatch bool, shouldRaiseError bool) { match, err := targetingMatchOperatorNumber(operator, targetingValue, value) if ((err != nil && !shouldRaiseError) || (shouldRaiseError && err == nil)) || (match != shouldMatch) { t.Errorf("Targeting number %v not working - tv : %f, v: %f, match : %v, err: %v", operator, targetingValue, value, match, err) } } func testTargetingBoolean(operator TargetingOperator, targetingValue bool, value bool, t *testing.T, shouldMatch bool, shouldRaiseError bool) { match, err := targetingMatchOperatorBool(operator, targetingValue, value) if ((err != nil && !shouldRaiseError) || (shouldRaiseError && err == nil)) || (match != shouldMatch) { t.Errorf("Targeting number %v not working - tv : %v, v: %v, match : %v, err: %v", operator, targetingValue, value, match, err) } } func testTargetingString(operator TargetingOperator, targetingValue string, value string, t *testing.T, shouldMatch bool, shouldRaiseError bool) { match, err := targetingMatchOperatorString(operator, targetingValue, value) if ((err != nil && !shouldRaiseError) || (shouldRaiseError && err == nil)) || (match != shouldMatch) { t.Errorf("Targeting string %v not working - tv : %v, v: %v, match : %v, err: %v", operator, targetingValue, value, match, err) } } func testTargetingCast(operator TargetingOperator, targeting interface{}, value interface{}, t *testing.T, shouldMatch bool, shouldRaiseError bool) { match, err := targetingMatchOperator(operator, targeting, value) if ((err != nil && !shouldRaiseError) || (shouldRaiseError && err == nil)) || (match != shouldMatch) { t.Errorf("Targeting cast value %v not working - tv : %v, v: %v, match : %v, err: %v", operator, targeting, value, match, err) } } func testTargetingListString(operator TargetingOperator, targetingValues []string, value string, t *testing.T, shouldMatch bool, shouldRaiseError bool) { stringValues := []string{} for _, str := range targetingValues { stringValues = append(stringValues, str) } match, err := targetingMatchOperator(operator, stringValues, value) if ((err != nil && !shouldRaiseError) || (shouldRaiseError && err == nil)) || (match != shouldMatch) { t.Errorf("Targeting list string %v not working - tv : %v, v: %v, match : %v, err: %v", operator, targetingValues, value, match, err) } } // TestNumberTargeting checks all possible number targeting func TestNumberTargeting(t *testing.T) { testTargetingNumber(LOWER_THAN, 11, 10, t, true, false) testTargetingNumber(LOWER_THAN, 10, 10, t, false, false) testTargetingNumber(LOWER_THAN, 9, 10, t, false, false) testTargetingNumber(LOWER_THAN_OR_EQUALS, 11, 10, t, true, false) testTargetingNumber(LOWER_THAN_OR_EQUALS, 10, 10, t, true, false) testTargetingNumber(LOWER_THAN_OR_EQUALS, 9, 10, t, false, false) testTargetingNumber(GREATER_THAN, 11, 10, t, false, false) testTargetingNumber(GREATER_THAN, 10, 10, t, false, false) testTargetingNumber(GREATER_THAN, 9, 10, t, true, false) testTargetingNumber(GREATER_THAN_OR_EQUALS, 11, 10, t, false, false) testTargetingNumber(GREATER_THAN_OR_EQUALS, 10, 10, t, true, false) testTargetingNumber(GREATER_THAN_OR_EQUALS, 9, 10, t, true, false) testTargetingNumber(NOT_EQUALS, 11, 10, t, true, false) testTargetingNumber(NOT_EQUALS, 10, 10, t, false, false) testTargetingNumber(NOT_EQUALS, 9, 10, t, true, false) testTargetingNumber(EQUALS, 11, 10, t, false, false) testTargetingNumber(EQUALS, 10, 10, t, true, false) testTargetingNumber(EQUALS, 9, 10, t, false, false) testTargetingNumber(CONTAINS, 11, 10, t, false, true) testTargetingNumber(ENDS_WITH, 10, 10, t, false, true) testTargetingNumber(STARTS_WITH, 9, 10, t, false, true) } // TestBooleanTargeting checks all possible boolean targeting func TestBooleanTargeting(t *testing.T) { testTargetingBoolean(NOT_EQUALS, true, false, t, true, false) testTargetingBoolean(NOT_EQUALS, true, true, t, false, false) testTargetingBoolean(NOT_EQUALS, false, true, t, true, false) testTargetingBoolean(EQUALS, true, false, t, false, false) testTargetingBoolean(EQUALS, true, true, t, true, false) testTargetingBoolean(EQUALS, false, true, t, false, false) testTargetingBoolean(CONTAINS, true, false, t, false, true) testTargetingBoolean(ENDS_WITH, true, false, t, false, true) testTargetingBoolean(STARTS_WITH, true, false, t, false, true) testTargetingBoolean(GREATER_THAN, true, false, t, false, true) testTargetingBoolean(GREATER_THAN_OR_EQUALS, true, false, t, false, true) testTargetingBoolean(LOWER_THAN, true, false, t, false, true) testTargetingBoolean(LOWER_THAN_OR_EQUALS, true, false, t, false, true) } // TestStringTargeting checks all possible string targeting func TestStringTargeting(t *testing.T) { testTargetingString(LOWER_THAN, "abc", "abd", t, false, false) testTargetingString(LOWER_THAN, "abc", "abc", t, false, false) testTargetingString(LOWER_THAN, "abd", "abc", t, true, false) testTargetingString(LOWER_THAN_OR_EQUALS, "abc", "abd", t, false, false) testTargetingString(LOWER_THAN_OR_EQUALS, "abc", "abc", t, true, false) testTargetingString(LOWER_THAN_OR_EQUALS, "abd", "abc", t, true, false) testTargetingString(GREATER_THAN, "abc", "abd", t, true, false) testTargetingString(GREATER_THAN, "abc", "abc", t, false, false) testTargetingString(GREATER_THAN, "abd", "abc", t, false, false) testTargetingString(GREATER_THAN_OR_EQUALS, "abc", "abd", t, true, false) testTargetingString(GREATER_THAN_OR_EQUALS, "abc", "abd", t, true, false) testTargetingString(GREATER_THAN_OR_EQUALS, "abd", "abc", t, false, false) testTargetingString(NOT_EQUALS, "abc", "abd", t, true, false) testTargetingString(NOT_EQUALS, "abc", "abc", t, false, false) testTargetingString(NOT_EQUALS, "", "", t, false, false) testTargetingString(NOT_EQUALS, "", " ", t, true, false) testTargetingString(EQUALS, "abc", "abd", t, false, false) testTargetingString(EQUALS, "abc", "abc", t, true, false) testTargetingString(EQUALS, "ABC", "abc", t, true, false) testTargetingString(EQUALS, "", "", t, true, false) testTargetingString(EQUALS, "", " ", t, false, false) testTargetingString(CONTAINS, "b", "abc", t, true, false) testTargetingString(CONTAINS, "B", "abc", t, true, false) testTargetingString(CONTAINS, "d", "abc", t, false, false) testTargetingString(NOT_CONTAINS, "d", "abc", t, true, false) testTargetingString(NOT_CONTAINS, "D", "abc", t, true, false) testTargetingString(NOT_CONTAINS, "b", "abc", t, false, false) testTargetingString(ENDS_WITH, "c", "abc", t, true, false) testTargetingString(ENDS_WITH, "C", "abc", t, true, false) testTargetingString(ENDS_WITH, "d", "abc", t, false, false) testTargetingString(ENDS_WITH, "a", "abc", t, false, false) testTargetingString(ENDS_WITH, "", "abc", t, true, false) testTargetingString(STARTS_WITH, "a", "abc", t, true, false) testTargetingString(STARTS_WITH, "A", "abc", t, true, false) testTargetingString(STARTS_WITH, "d", "abc", t, false, false) testTargetingString(STARTS_WITH, "c", "abc", t, false, false) testTargetingString(STARTS_WITH, "", "abc", t, true, false) testTargetingString(NULL, "", "abc", t, false, true) } // TestListStringTargeting checks all possible string list targeting func TestListStringTargeting(t *testing.T) { testTargetingListString(EQUALS, []string{"abc"}, "abd", t, false, false) testTargetingListString(EQUALS, []string{"abc"}, "abc", t, true, false) testTargetingListString(NOT_EQUALS, []string{"abc"}, "abd", t, true, false) testTargetingListString(NOT_EQUALS, []string{"abc"}, "abc", t, false, false) testTargetingListString(EQUALS, []string{"abc", "bcd"}, "abd", t, false, false) testTargetingListString(EQUALS, []string{"abc", "bcd"}, "abc", t, true, false) testTargetingListString(NOT_EQUALS, []string{"abc", "bcd"}, "abd", t, true, false) testTargetingListString(NOT_EQUALS, []string{"abc", "bcd"}, "abc", t, false, false) } // TestTargetingCast checks all possible targeting type func TestTargetingCast(t *testing.T) { testTargetingCast(EQUALS, "abc", "abc", t, true, false) testTargetingCast(EQUALS, 1, "abc", t, false, true) testTargetingCast(EQUALS, 200, 200, t, true, false) testTargetingCast(EQUALS, 200, 400, t, false, false) testTargetingCast(EQUALS, 200.0, 200.0, t, true, false) testTargetingCast(EQUALS, 200.0, 400.0, t, false, false) testTargetingCast(EQUALS, true, true, t, true, false) testTargetingCast(EQUALS, true, false, t, false, false) } func TestTargetingMatch(t *testing.T) { vg := VariationGroup{ Targeting: TargetingWrapper{ TargetingGroups: []*TargetingGroup{ { Targetings: []*Targeting{ { Operator: EQUALS, Key: "test", Value: 1, }, }, }, }, }, } context := map[string]interface{}{ "test": true, } _, err := TargetingMatch(&vg, testVID, context) if err == nil { t.Error("Expected error as targeting and context value type do not match") } }
go
26
0.710576
153
42.6875
208
starcoderdata
import numpy as np import pandas as pd from datetime import datetime import json from datetime import timedelta # R:年度无风险利率 # T:一年的周期个数,以月为周期T=12,以周为周期T=52 # 年化夏普比率(R为一年期的无风险利率;T为一年的周期个数,以月为周期T=12,以周为周期T=52) from Time.datatime import get_firstday_year def get_sharpe_ratio(yield_list, R, T): ''' :param yield_list: :param R: :param T: :return: ''' yield_list = yield_list.dropna() if len(yield_list) > 1: return ((np.average(yield_list)+1)**T-1-R)/(np.std(yield_list) * np.sqrt(T)) else: return np.nan # 标准差 def get_year_std(yield_list): yield_list = yield_list.dropna() if len(yield_list) > 1: return yield_list.std() else: return np.nan # 年化下行标准差(R_T为对应周期的无风险利率) def get_DownStd(yield_list, R, T): yield_list = yield_list.dropna() R_T = (R + 1) ** (1 / T) - 1 newlist = [] for i in yield_list: if i<R_T: newlist.append((i-R_T)**2) else: continue return np.sqrt(np.average(newlist) * T) # 最大回撤,s是以日期为索引的Series def get_max_retracement(s): s_retracement = 1 - s / s.expanding(min_periods=1).max() edate = s_retracement.idxmax() max_retracement = s_retracement[edate] bdate = s[:edate].idxmax() rdate = s[s > s[bdate]][edate:].index.min() rdays = (rdate - edate).days return [max_retracement, bdate, edate, rdate, rdays] # 最大回撤,s_source是以日期为索引的Series def get_max_retracement(s_source, current_T, section='total'): if section == 'total': s = s_source[:current_T] elif section == 'year': if get_firstday_year(current_T) < s_source.index[0]: return [np.nan, np.nan, np.nan, np.nan, np.nan] else: s = s_source[get_firstday_year(current_T):current_T] elif section == 'm3': if (current_T - pd.DateOffset(months=3)) < s_source.index[0]: return [np.nan, np.nan, np.nan, np.nan, np.nan] else: s = s_source[current_T - pd.DateOffset(months=3):current_T] elif section == 'm6': if (current_T - pd.DateOffset(months=6)) < s_source.index[0]: return [np.nan, np.nan, np.nan, np.nan, np.nan] else: s = s_source[current_T - pd.DateOffset(months=6):current_T] elif section == 'y1': if (current_T - pd.DateOffset(years=1)) < s_source.index[0]: return [np.nan, np.nan, np.nan, np.nan, np.nan] else: s = s_source[current_T - pd.DateOffset(years=1):current_T] elif section == 'y3': if (current_T - pd.DateOffset(years=3)) < s_source.index[0]: return [np.nan, np.nan, np.nan, np.nan, np.nan] else: s = s_source[current_T - pd.DateOffset(years=3):current_T] elif section == 'y5': if (current_T - pd.DateOffset(years=5)) < s_source.index[0]: return [np.nan, np.nan, np.nan, np.nan, np.nan] else: s = s_source[current_T - pd.DateOffset(years=5):current_T] else: return [np.nan, np.nan, np.nan, np.nan, np.nan] s_retracement = 1 - s / s.expanding(min_periods=1).max() edate = s_retracement.idxmax() max_retracement = s_retracement[edate] bdate = s[:edate].idxmax() rdate = s[s > s[bdate]][edate:].index.min() rdays = (rdate - edate).days return [max_retracement, bdate, edate, rdate, rdays] # return 1 # 年化索提诺比率(R为一年期的无风险利率;T为一年的周期个数,以月为周期T=12,以周为周期T=52;R_T为对应周期的无风险利率) def get_sortino_ratio(yield_list,R,T): yield_list = yield_list.dropna() if len(yield_list) > 1: return ((np.average(yield_list)+1)**T-1-R) / (get_DownStd(yield_list, R, T) * np.sqrt(T)) else: return np.nan # beta def get_beta(s1,s2): if s1.cov(s2) != 0 and np.var(s2, ddof=1) != 0: beta = s1.cov(s2) / np.var(s2, ddof=1) return beta else: return np.nan # pearson def get_pearson(s1,s2): if (np.std(s1) > 0 and np.std(s2) > 0): return s1.corr(s2) else: return np.nan # 特雷诺指数 def get_treynor_ratio(s1, s2, R, T): if (pd.isnull(get_beta(s1, s2)) or get_beta(s1, s2) == 0): return np.nan else: treynor = ((np.average(s1.dropna())+1)**T-1-R) / get_beta(s1, s2) return treynor # 平均损益比 mean(大于0的模拟组合周收益率)/mean(小于等于0的模拟组合周收益率) def get_loss_to_profit(yield_list): if yield_list.empty: return np.nan else: avg_loss = np.average([i for i in yield_list if i <= 0]) avg_profit = np.average([i for i in yield_list if i > 0]) return abs(avg_profit / avg_loss) # 波动率(年化) 波动率(年化)=模拟组合周收益率标准差*√52 def year_wave_ratio(yield_list,T): yield_list = yield_list.dropna() if len(yield_list) > 1: np.std(yield_list) * np.sqrt(T) else: return np.nan # 投资胜率 def get_win_rate(yield_list): if yield_list.empty: return np.nan else: return len([i for i in yield_list if i > 0]) / len(yield_list) # 年化收益率 def year_profit_ratio(yield_list): if yield_list.empty: return np.nan else: return np.power(1 + np.average(yield_list),52) - 1 # 最大回撤 净值 def MaxDrawdown(yield_list): i = np.argmax((np.maximum.accumulate(yield_list) - yield_list) / np.maximum.accumulate(yield_list)) # 结束位置 if i == 0: return 0 j = np.argmax(yield_list[:i]) # 开始位置 return (yield_list[j] - yield_list[i]) / (yield_list[j]) # 用等差的原则填充缺少的净值数据 def NV_fillna(NV_list): for i in range(len(NV_list)): if pd.isnull(NV_list[i]): j = 1 while pd.isnull(NV_list[i+j]): j += 1 diff_NV = (NV_list[i+j] - NV_list[i-1])/(j+1) for k in range(0, j): NV_list[i+k] = NV_list[i-1] + (k+1) * diff_NV else: continue # 用等差的原则填充缺少的净值数据 def NV_fillna2(NV_list): tmp_i1 = 0 for mm in range(len(NV_list)): if pd.isna(NV_list[mm]): continue tmp_i1 = mm break NV_list[0:tmp_i1] = NV_list[tmp_i1] tmp_i2 = 0 for mmm in range(len(NV_list)): if pd.isna(NV_list[len(NV_list)-mmm-1]): continue tmp_i2 = len(NV_list)-mmm-1 break NV_list[tmp_i2:] = NV_list[tmp_i2] for i in range(len(NV_list)): if pd.isnull(NV_list[i]): j = 1 while pd.isnull(NV_list[i+j]): j += 1 diff_NV = (NV_list[i+j] - NV_list[i-1])/(j+1) for k in range(0, j): NV_list[i+k] = NV_list[i-1] + (k+1) * diff_NV else: continue # else: # return NV_list
python
19
0.563258
110
25.688259
247
starcoderdata
# pylint: disable=redefined-outer-name import pytest import slash from io import StringIO from slash.frontend.slash_run import slash_run def test_errors_during_initialization_hoook(suite, init_hook): @init_hook.register def callback(): # pylint: disable=unused-variable raise slash.exceptions.SlashException('some error') exit_code, output = _console_run(suite) assert 'some error' in output assert exit_code != 0 def test_slashrc_errors(suite): @suite.slashrc.include def __code__(): # pylint: disable=unused-variable 1 / 0 # pylint: disable=pointless-statement exit_code, output = _console_run(suite) assert exit_code != 0 output = output.lower() assert 'unexpected error' in output assert 'division' in output assert 'zero' in output @pytest.fixture(params=[ slash.hooks.session_start, # pylint: disable=no-member slash.hooks.configure, # pylint: disable=no-member ]) def init_hook(request): return request.param def _console_run(suite): suite.disable_debug_info() path = suite.commit() stream = StringIO() exit_code = slash_run([path], report_stream=stream, working_directory=path) return exit_code, stream.getvalue()
python
10
0.694915
79
25.934783
46
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Model\Employee; use App\Model\Department; use App\Model\Position; use App\Model\Permission; use App\Model\Role; use Auth; class EmployeeController extends Controller { public function index() { $employees = $this->getEmployees(Auth::user()); $dataTables = []; $dataTables['colums'] = ['id', 'department', 'position', 'role', 'firstname', 'lastname', 'action']; $dataTables['datas'] = []; foreach($employees as $employee) { $department = (empty($employee->department))? 'none' : $employee->department->name; $position = (empty($employee->position))? 'none' : $employee->position->name; $roleName = ($employee->permission && $employee->permission->role)? $employee->permission->role->name : 'none'; $dataTables['datas'][] = [ $this->renderClickEdit($employee, $employee->code), $department, $position, $roleName, $employee->firstname, $employee->lastname, $this->renderClickDelete($employee, 'delete') ]; } $roles = Role::where('active', true) ->whereNotIn('name', Role::developer()) ->get(); return view('pages.employee.index', [ 'dataTables' => $dataTables, 'departments' => Department::all(), 'positions' => Position::all(), 'roles' => $roles, ]); } public function store(Request $request) { if($request->input('active') != 'on') $request['active'] = false; $this->validate($request, [ 'department_id' => 'required|integer', 'position_id' => 'required|integer', 'role_id' => 'required|integer', 'code' => 'required|unique:employee', 'firstname' => 'required|string', 'lastname' => 'required|string', // 'can_login' => 'required|string', // 'active' => 'required|string', ]); $employee = Employee::create($request->all()); $employee->permission()->create([ 'employee_id' => $employee->id, 'role_id' => $request->role_id ]); if(!$employee) return back(); return redirect()->action('EmployeeController@index'); } public function edit($id) { // if(!Auth::user()->permission->role->isAdmin()) // return view('errors.404'); $employee = Employee::find($id); $roles = Role::where('active', true) ->whereNotIn('name', Role::Developer()) ->get(); if(!$employee) return back(); return view('pages.employee.edit', [ 'employee' => $employee, 'departments' => Department::all(), 'positions' => Position::all(), 'roles' => $roles, 'canEdit' => Auth::user()->permission->role->isAdmin() ? true : false ]); } public function update(Request $request, $id) { $this->validate($request, [ 'department_id' => 'required|integer', 'position_id' => 'required|integer', 'role_id' => 'required|integer', 'code' => 'required', 'firstname' => 'required|string', 'lastname' => 'required|string', // 'can_login' => 'required|string', // 'active' => 'required|string', ]); $employee = Employee::find($id); if($employee->code != $request->input('code') && Employee::where('code', $request->input('code'))->count() > 0) return back(); if(!$employee) return back(); if($request->input('active') != 'on') $request['active'] = false; $employee->update($request->all()); $employee->permission->update([ 'role_id' => $request->role_id ]); return redirect()->action('EmployeeController@index'); } public function destroy($id) { $employee = Employee::find($id); if($employee) { if(!$employee->projects->count() || !$employee->employeeProjects->count()) $employee->delete(); } return back(); } /** * Render tag html */ private function renderClickDelete($employee, $text) { if(Auth::user()->permission->role->isAdmin()) { return '<span class="label label-warning" data-toggle="tooltip" title="It\'s has related" style="cursor:not-allowed;" disabled>Delete } if($employee->projects->count() || $employee->employeeProjects->count()) { return '<span class="label label-warning" data-toggle="tooltip" title="It\'s has related" style="cursor:not-allowed;" disabled>Delete } else { return '<span class="label label-warning" style="cursor:pointer;" onclick="$(this).find(\'form\').submit();"> ' . $text . ' <form action="' . action('EmployeeController@destroy', $employee->id) . '" method="POST" hidden>' . method_field('delete') . csrf_field() . ' } } private function renderClickEdit($employee, $text) { return '<a href="' . action('EmployeeController@edit', $employee->id) . '" > ' . $text . ' } private function getEmployees($user) { $employees = []; if($user->permission->role->isAdmin()) { $employees = Employee::all(); } elseif($user->permission->role->isManager()) { $excepts = Permission::whereIn('role_id', Role::manager('id'))->lists('employee_id'); $employees = Employee::where('department_id', $user->department_id) ->whereNotIn('id', $excepts) ->get(); } elseif($user->permission->role->isProjectManager()) { $excepts = Permission::whereIn('role_id', Role::projectManager('id'))->lists('employee_id'); $employees = Employee::where('department_id', $user->department_id) ->whereNotIn('id', $excepts) ->get(); } return $employees; } }
php
19
0.519645
150
30.752475
202
starcoderdata
import sys sys.path = ['./superfast/build'] + sys.path import dlib import numpy as np import superfast random_projections = np.random.randn(100,75*75).astype('float32'); random_projections = np.asmatrix(random_projections) def hash_image(filename): img = dlib.load_grayscale_image(filename) img = dlib.convert_image(img, dtype='float32') img = dlib.resize_image(img, 75,75) img = img.reshape(img.size,1) img = np.asmatrix(img) img -= 110 h = random_projections*img; h = h>0; return hash(np.packbits(h).tostring()) for filename in sys.argv[1:]: h = hash_image(filename) print("{} \t{}".format(h, filename)) # for h,f in superfast.hash_images(sys.argv[1:]): # print(h, "\t", f) # for h,f in superfast.hash_images_parallel(sys.argv[1:]): # print(h, "\t", f) # Time this program with a statement like: # time find images/small_face_dataset/ -name "*.png" | xargs python3 020_hash_images.py | wc
python
10
0.659686
94
24.131579
38
starcoderdata
void ossimUtmpt::convertFromGround(const ossimGpt &aPt) { const ossimDatum *aDatum = aPt.datum(); if(aDatum) { //call Geotrans init code Set_UTM_Parameters(aDatum->ellipsoid()->a(), aDatum->ellipsoid()->flattening(), 0); Convert_Geodetic_To_UTM(aPt.latr(), aPt.lonr(), &theZone, &theHemisphere, &theEasting, &theNorthing); theDatum = aDatum; } else { //ERROR: Should never happen } }
c++
12
0.473504
89
26.904762
21
inline
def test_worker_set_status_invalid_parameter(setup_config): """ Testing set status request with all invalid parameter values. """ # retrieve values from conftest session fixture worker_obj, uri_client, private_key, err_cd = setup_config[:4] # input and output names request = './worker_tests/input/worker_set_status_invalid_parameter.json' request_mode = 'file' output_json_file_name = 'worker_set_status' tamper = {"params": {}} request_method = "" request_id = 0 # submit worker set status request_tup = (request, request_mode, tamper, output_json_file_name, uri_client, request_method, worker_obj, request_id) response_tup = post_request(request_tup) response = response_tup[1] # validate work order response and get error code err_cd = validate_response_code(response) assert err_cd == TestStep.SUCCESS.value logger.info('\t\t!!! Test completed !!!\n\n')
python
8
0.659138
77
35.111111
27
inline
import Vue from "vue"; import App from "./App.vue"; import Buefy from "buefy"; import axios from "axios"; import VueAxios from "vue-axios"; import PerfectScrollbar from "vue2-perfect-scrollbar"; import "vue2-perfect-scrollbar/dist/vue2-perfect-scrollbar.css"; import store from "./store"; Object.filter = (obj, predicate) => Object.keys(obj) .filter(key => predicate(obj[key])) .reduce((res, key) => ((res[key] = obj[key]), res), {}); Vue.use(PerfectScrollbar); console.log(process.env.VUE_APP_API_URL); var axiosInstance = axios.create({ baseURL: process.env.VUE_APP_API_URL }); Vue.use(VueAxios, axiosInstance); store.axios = axiosInstance; Vue.use(Buefy); Vue.prototype.$gitcommit = process.env.VUE_APP_GIT_HASH; Vue.prototype.$installQueue = []; Object.filter = (obj, predicate) => Object.keys(obj) .filter(key => predicate(obj[key])) .reduce((res, key) => ((res[key] = obj[key]), res), {}); Vue.config.productionTip = false; new Vue({ store, render: h => h(App) }).$mount("#app");
javascript
12
0.674744
75
31.515152
33
starcoderdata
def zeros_test(self, compress_rate, array_mask, H, W): compress_rate = compress_rate / 100 print("array mask:\n", array_mask) zeros_size = np.sum(array_mask == 0.0) # print(zero2) total_size = H * W # print("total size: ", total_size) fraction_zeroed = zeros_size / total_size print("compress rate: ", compress_rate, " fraction of zeroed out: ", fraction_zeroed) error = 0.2 if fraction_zeroed > compress_rate + error or ( fraction_zeroed < compress_rate - error): raise Exception(f"The compression is wrong, for compression " f"rate {compress_rate}, the number of fraction " f"of zeroed out coefficients " f"is: {fraction_zeroed}")
python
11
0.540573
76
48.352941
17
inline
@Override public void periodic() { // This method will be called once per scheduler run // Fill the buffer with a rainbow // here we will create a state system to have the external command system opperate new states switch(m_led_mode_state){ case 1: // rainbow rainbow(); break; case 2: // frenzy Random rand = new Random(); if(led_loop_count++ % 10 == 0){ frenzy(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255)); } break; case 3: // red red(); break; case 4: // green green(); break; case 5: // blue blue(); break; case 6: //purple purple(); break; case 7: // redPulse redPulse(); break; case 8: // redstreak redStreak(); break; case 9: // greenstreak greenStreak(); break; case 10: // bluestreak blueStreak(); break; case 11: // red if(led_loop_count++ % 20 == 0){ red(); }else if(led_loop_count % 10 == 0){ clearAll(); } break; case 12: // green if(led_loop_count++ % 20 == 0){ green(); }else if(led_loop_count % 10 == 0){ clearAll(); } break; case 13: // blue if(led_loop_count++ % 20 == 0){ blue(); }else if(led_loop_count % 10 == 0){ clearAll(); } break; case 14: //purple if(led_loop_count++ % 20 == 0){ purple(); }else if(led_loop_count % 10 == 0){ clearAll(); } break; case 0: // do nothing break; default:// do nothing break; } }
java
13
0.433638
97
22.513158
76
inline
package com.nekohit.neo.ozkens.service; import com.nekohit.neo.ozkens.model.SignedMessage; import io.neow3j.crypto.ECKeyPair; import io.neow3j.crypto.Sign; import io.neow3j.protocol.Neow3j; import io.neow3j.protocol.core.Request; import io.neow3j.protocol.core.Response; import io.neow3j.types.ContractParameter; import io.neow3j.types.Hash160; import io.neow3j.types.Hash256; import io.neow3j.types.NeoVMStateType; import io.neow3j.utils.Numeric; import io.neow3j.wallet.Account; import io.reactivex.disposables.Disposable; import lombok.extern.slf4j.Slf4j; import org.springframework.data.util.Pair; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @Slf4j public class NekoinService implements AutoCloseable { private final Neow3j neow3j; private final Account account; private final Hash160 nekoinScripHash; private final String assetMapPrefixHexString; private final Disposable subscribeToNewBlock; private final AtomicLong highestBlockIndex = new AtomicLong(); public NekoinService(Neow3j neow3j, Account account, Hash160 nekoinScripHash, String assetMapPrefixHexString) { this.neow3j = neow3j; this.account = account; this.nekoinScripHash = nekoinScripHash; this.assetMapPrefixHexString = assetMapPrefixHexString; try { this.subscribeToNewBlock = this.neow3j.subscribeToNewBlocksObservable(false) .subscribe(r -> { var b = r.getBlock(); this.highestBlockIndex.set(b.getIndex()); log.debug("Get new block: #{}, 0x{}", b.getIndex(), b.getHash()); }); } catch (IOException e) { throw new RuntimeException(e); } } /** * Catch all check exception and rethrow it as an unchecked exception ({@link RuntimeException}). */ private <S, T extends Response T sendRequest(Request<S, T> request) { try { var result = request.send(); if (result.hasError()) { throw new RuntimeException(result.getError().getMessage()); } return result; } catch (IOException e) { throw new RuntimeException(e); } } // TODO: Dump assets map at given block index // TODO: Get someone's balance at given block index // TODO: Get the balances of a list of address at given block index /** * Fetch content from a given tx hash. The tx should contain events called "WriteMessage", * fired by Nekoin contract. The method will fetch those events and read the data. * * Return a map: (Hex string of index, byte array of content). */ public Map<String, byte[]> readMessage(Hash256 txHash) { var resultList = this.sendRequest(this.neow3j.getApplicationLog(txHash)) .getApplicationLog() .getExecutions() .parallelStream() // filter HALT executions .filter(e -> e.getState() == NeoVMStateType.HALT) .flatMap(e -> e.getNotifications().parallelStream()) // filter Nekoin contract notifies .filter(n -> n.getContract().equals(this.nekoinScripHash)) .filter(n -> n.getEventName().equals("WriteMessage")) .map(n -> { var index = n.getState().getList().get(0).getByteArray(); var resp = this.sendRequest(this.neow3j.invokeFunction( this.nekoinScripHash, "readMessage", List.of(ContractParameter.byteArray(index)) )).getInvocationResult(); if (resp.hasStateFault()) { throw new RuntimeException(resp.getException()); } var content = resp.getStack().get(0).getByteArray(); return Pair.of(Numeric.toHexString(index), content); }) .toList(); var resultMap = new HashMap<String, byte[]>(); resultList.forEach(p -> resultMap.put(p.getFirst(), p.getSecond())); return resultMap; } /** * Verify the {@link SignedMessage} object and return the signer's address. * * Return null means the signed message is invalid. */ public String extractAddressFromSignature(SignedMessage signedMessage) { // check signature var decoder = Base64.getDecoder(); var signature = Sign.SignatureData.fromByteArray( signedMessage.header(), decoder.decode(signedMessage.signature())); byte[] message = signedMessage.message().getBytes(StandardCharsets.UTF_8); var publicKey = new ECKeyPair.ECPublicKey(decoder.decode(signedMessage.publicKey())); if (!Sign.verifySignature(message, signature, publicKey)) { throw new IllegalArgumentException("Signature didn't match the hash or public key"); } // pub key -> signature -> hash -> content, return the address return Account.fromPublicKey(publicKey).getAddress(); } /** * Sign the input message using server's wallet. */ public SignedMessage signMessage(String message) { byte[] content = message.getBytes(StandardCharsets.UTF_8); var keyPair = this.account.getECKeyPair(); var signature = Sign.signMessage(content, keyPair, true); var encoder = Base64.getEncoder(); return new SignedMessage(message, signature.getV(), encoder.encodeToString(signature.getConcatenated()), encoder.encodeToString(keyPair.getPublicKey().getEncoded(true))); } public String getServerWalletAddress() { return this.account.getAddress(); } /** * Check if the given block is already popped. * Force means it request data from Node when invoked. */ public boolean blockIsPresentForce(BigInteger blockIndex) { return blockIndex.compareTo(this.getHighestBlockIndexForce()) <= 0; } /** * Check if the given block is already popped. * It will use the internal counter, instead of requesting node. */ public boolean blockIsPresent(BigInteger blockIndex) { return blockIndex.compareTo(this.getHighestBlockIndex()) <= 0; } /** * Get the highest block index. * Force means it request data from node when invoked. */ public BigInteger getHighestBlockIndexForce() { return this.sendRequest(this.neow3j.getBlockCount()) .getBlockCount().add(BigInteger.ONE.negate()); } /** * Get the highest block index. * It will use the internal counter, instead of requesting node. */ public BigInteger getHighestBlockIndex() { return BigInteger.valueOf(this.highestBlockIndex.get()); } @Override public void close() { this.subscribeToNewBlock.dispose(); } }
java
21
0.633144
115
37.865591
186
starcoderdata
/* Copyright (c) 2017, /* All rights reserved. /* /* Redistribution and use in source and binary forms, with or without /* modification, are permitted provided that the following conditions are met: /* /* * Redistributions of source code must retain the above copyright notice, this /* list of conditions and the following disclaimer. /* /* * 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. /* /* * Neither the name of Sikan Zhu 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 SIKAN ZHU 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 SIKAN ZHU 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 innova; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import innova.common.Constant; import innova.common.Utility; import innova.redis.ToRedis; import innova.redis.ToRedisOperation; import innova.redis.ToRedisProperty; import innova.core.IPlugin; import innova.protocol.InnovaProtocol.IdPtype; import innova.protocol.InnovaProtocol.Region; import redis.clients.jedis.Pipeline; public class RegionCleaner implements IPlugin { private final static Logger _logger = Logger.getLogger(""); private ToRedis _redis; private Pipeline _pipline; private final List _regions = new ArrayList // implement of IPlugin @Override public void Init( final String[] args ) { _logger.trace( new Exception().getStackTrace()[0] ); _redis = new ToRedis(); //TODO set up cleaning regions for( int x = -10 ; x < 10 ; ++x ) for( int z = -10 ; z < 10 ; ++z ) { _regions.add( Utility.ToRegion( x , 0 , z , 0 ) ); } } @Override public float Start( final String[] args ) { _logger.trace( new Exception().getStackTrace()[0] ); if( false == _redis.Connect( Constant.ADRESS_LOCALHOST )) { _logger.error( "Can not connect to redis." ); return -1; } _pipline = _redis.Get().pipelined(); return Constant.REGION_CLEANER_INTERVAL; } @Override public boolean Update( final float elapse ) { _logger.trace( new Exception().getStackTrace()[0] + "( elapse = " + elapse + ")" ); final long max_removing_time = _redis.GetTime() - Constant.INACTIVE_PROPERTY_REMAIN; //TODO use world server to synchronize time for( Region ri : _regions ) { // max_removing_time must be > 0 because Redis server time is Unix timestamp, // so it is not necessary to check max_removing_time's sign. // we are sure that no active property will be in [-max_removing_time , 0], // because all the active properties will be in [ServerStartUnixTimeStamp , CurrentUnixTimeStamp]. final List aps = ToRedisProperty.UGetInactive( _pipline , ri , 0 , max_removing_time ); // pop operations on these inactive properties for( IdPtype ap : aps ) { ToRedisOperation.UPopOperations( _pipline , ap ); } // remove these properties ToRedisProperty.PRemoveInactive( _pipline , ri , aps ); } ToRedisProperty.PCommit( _pipline ); return true; } @Override public void Pause() { _logger.trace( new Exception().getStackTrace()[0] ); } @Override public void Resume() { _logger.trace( new Exception().getStackTrace()[0] ); } @Override public void Stop( final String[] args ) { _logger.trace( new Exception().getStackTrace()[0] ); try { _pipline.close(); } catch( IOException e ) { _logger.error( e ); } _redis.Disconnect(); } @Override public void Deinit( final String[] args ) { _logger.trace( new Exception().getStackTrace()[0] ); } }
java
15
0.708249
130
28.82
150
starcoderdata
#pragma once #include "chokoplayer.hpp" #define CE_MOD_AC_NS ModuleAC #define CE_BEGIN_MOD_AC_NAMESPACE\ CE_BEGIN_NAMESPACE\ namespace CE_MOD_AC_NS { #define CE_END_MOD_AC_NAMESPACE }\ CE_END_NAMESPACE CE_BEGIN_MOD_AC_NAMESPACE AnimClip LoadAnimClip(DataStream strm); AnimGraph LoadAnimGraph(const JsonObject& data); Armature LoadArmature(const JsonObject& data); Shader LoadShader(const JsonObject& data); CE_END_MOD_AC_NAMESPACE
c++
6
0.783058
48
22.047619
21
starcoderdata
<?php namespace App\Http\Controllers; use App\Http\Requests\CreateUserRequest; use App\Http\Requests\UpdateUserRequest; use App\Mail\Complete; use Illuminate\Http\Request; use App\User; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Spatie\Permission\Models\Role; class UsersController extends Controller { public function index(){ $users = User::orderBy('id', 'DESC')->paginate(10); return view('users.index',['users' => $users]); } public function create(){ $roles = Role::all(); return view('users.create', ['roles' => $roles]); } //Crear un nuevo usuario public function store(CreateUserRequest $request){ $code = Str::random(40); $user = User::create([ 'name' => $request->name, 'last_name' => $request->last_name, 'document_type' => $request->document_type, 'document_number' => $request->document_number, 'email' => $request->email, 'remember_token' => $code, ]); if($user){ $role = Role::find($request->role); $user->assignRole($role); //envia correo electronico para que ingrese la contraseña y se complete el registro Mail::to($request->email) ->send(new Complete($request->name, $request->last_name, $code)); } if($user){ session()->flash('message', 'El usuario '.$request->name.' fue creado correctamente!'); } return redirect()->route('users.index'); } //retorna la vita para que le usurio complete el registro public function complete($code){ $user = User::where('remember_token', $code) ->whereNull('password')->first(); return view('users.complete', ['user' => $user]); } //actualiza la contaseña que envio el usuario public function updatePass(User $user, Request $request){ $update = $user->update(['password' => if($update){ session()->flash('message', 'Sus datos se han actualizado correctamente!'); } return redirect()->route('login'); } //retorna vista de edicion de usurio public function edit(User $user){ return view('users.edit', ['user' => $user]); } public function update(UpdateUserRequest $request, User $user){ $u = $user->update([ 'name' => $request->name, 'last_name' => $request->last_name, 'document_type' => $request->document_type, 'document_number' => $request->document_number, 'email' => $request->email, 'active' => $request->active, ]); if($u){ session()->flash('message', 'Los datos del usuario '.$request->name.' fueron actualizados correctamente!'); } return redirect()->route('users.index'); } public function roles(User $user){ $roles = $user->roles()->paginate(5); $role_arr = []; foreach ($roles as $role) $role_arr[] = $role->id; $not_roles = Role::whereNotIn('id', $role_arr)->get(); return view('users.roles.index', ['roles' => $roles, 'not_roles' => $not_roles, 'user' => $user]); } public function addRole(User $user, Request $request){ $messages = [ 'new_role.required' => 'Debe seleccionar un rol!' ]; $validator = Validator::make($request->all(), [ 'new_role' => 'required', ], $messages); if($validator->fails()){ return redirect()->route('users.addRole', ['user' => $user->id]) ->withErrors($validator) ->withInput(); } $r = $user->assignRole($request->new_role); if($r){ $role = Role::find($request->new_role); session()->flash('message', 'El rol '.$role->name.' fue asignado correctamente!'); } return redirect()->route('users.addRole', ['user' => $user->id]); } public function removeRole(User $user, Role $role){ $r = $user->removeRole($role->id); if($r){ session()->flash('message', 'El rol '.strtolower($role->name).' fue removido correctamente!'); } return redirect()->route('users.addRole', ['user' => $user->id]); } }
php
18
0.559408
119
27.840764
157
starcoderdata
/* * Copyright (C) 2019 CFS Engineering * * Created: 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TIGLViewerNewFileDialog.h" #include "ui_TIGLViewerNewFileDialog.h" #include "TIGLViewerSettings.h" #include #include #include "CTiglLogging.h" #include "TIGLViewerErrorDialog.h" TIGLViewerNewFileDialog::TIGLViewerNewFileDialog(QWidget* parent) : QDialog(parent) , ui(new Ui::TIGLViewerNewFileDialog) { ui->setupUi(this); populate(); newCPACSFileName = ""; connect(ui->templatesListView, SIGNAL(activated(const QModelIndex)), this, SLOT(templateIsSelected(const QModelIndex))); } TIGLViewerNewFileDialog::~TIGLViewerNewFileDialog() { delete ui; } void TIGLViewerNewFileDialog::populate() { // get the settings for this application TIGLViewerSettings& settings = TIGLViewerSettings::Instance(); // retrieve the files in the templates dir QRegExp filesFilter("^.*\\.(xml|cpacs|cpacs3)$", Qt::CaseInsensitive, QRegExp::RegExp); QStringList files = settings.templateDir().entryList(QDir::Files); files = files.filter(filesFilter); // set the model and the view templateListModel.setStringList(files); ui->templatesListView->setModel(&templateListModel); } void TIGLViewerNewFileDialog::templateIsSelected(const QModelIndex& index) { TIGLViewerSettings& settings = TIGLViewerSettings::Instance(); // Create the new filename QString selectedTemplate = templateListModel.data(index, 0).toString(); QString originalFile = settings.templateDir().absolutePath() + "/" + selectedTemplate; QString newFilePath = originalFile + ".temp"; int prefix = 1; while (QFile::exists(newFilePath)) { newFilePath = settings.templateDir().absolutePath() + "/" + QString::number(prefix) + "_" + selectedTemplate + ".temp"; prefix = prefix + 1; } // Copy the file if (QFile::copy(originalFile, newFilePath)) { newCPACSFileName = newFilePath; LOG(INFO) << "TIGLViewerNewFileDialog::templateIsSelected: new file " + newFilePath.toStdString() + " created based on the template." << std::endl; accept(); } else { QString errorMsg = "An error occurs during the creation of the file \"" + newFilePath + "\". Make shure the application has the permission to write into \"" + settings.templateDir().absolutePath() + "\""; LOG(WARNING) << "TIGLViewerNewFileDialog::templateIsSelected: " + errorMsg.toStdString() << std::endl; // Display the TIGLViewerErrorDialog dialog(this); dialog.setMessage(QString(" /><br />%2").arg("Template Error").arg(errorMsg)); dialog.setWindowTitle("Error"); dialog.exec(); reject(); } } QString TIGLViewerNewFileDialog::getNewFileName() { return newCPACSFileName; }
c++
16
0.672309
117
33.653846
104
starcoderdata
<?php namespace App\Http\Controllers; use App\Models\SunderlandPlayers; use Illuminate\Http\Request; class SunderlandPlayersController extends Controller { public function index(){ $players = \DB::table('sunderland_players')->get(); return view('football.sunderland.players.index', ['players' => $players]); } public function show($id) { $player = \DB::table('sunderland_players')->where('id', $id)->first(); return view('football.sunderland.players.show', ['player' => $player ]); } public function create() { return view('football.sunderland.players.create'); } public function edit($id) { $player = SunderlandPlayers::find($id); return view('football.sunderland.players.edit', ['player' => $player]); } public function store(Request $request) { $newImageName = time() . '_' . $request->first_name . '.' . $request->img->extension(); $request->img->move(public_path('img/players'), $newImageName); $player = new SunderlandPlayers(); $player->first_name = $request->input('first_name'); $player->last_name = $request->input('last_name'); $player->nickname = $request->input('nickname'); $player->bio = $request->input('bio'); $player->position = $request->input('position'); $player->img = $newImageName; $player->save(); return redirect('/football/sunderland/players')->with('mssg', "Player added to the squad"); } public function update(Request $request, $id) { $player = SunderlandPlayers::find($id); if($request->img){ $replaceImageName = time() . '_' . $request->first_name . '.' . $request->img->extension(); $request->img->move(public_path('img/players'), $replaceImageName); } else { $replaceImageName = $player->img; } $player->first_name = $request->input('first_name'); $player->last_name = $request->input('last_name'); $player->position = $request->input('position'); $player->bio = $request->input('bio'); $player->position = $request->input('position'); $player->img = $replaceImageName; $player->save(); return redirect('/football/sunderland/players')->with('mssg', "Player was updated"); } public function destroy($player){ $player = SunderlandPlayers::findOrFail($player); $player->delete(); } }
php
15
0.578968
103
29.452381
84
starcoderdata
/* Copyright (c) 2017 * * Jonson is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #include #include #include "ealloc.h" void *emalloc(size_t num, size_t size) { void *mem = malloc(num * size); if (!mem) { fprintf(stderr, "Failed to allocate %zu bytes\n", num * size); exit(EXIT_FAILURE); } return mem; } void *ecalloc(size_t num, size_t size) { void *mem = calloc(num, size); if (!mem) { fprintf(stderr, "Failed to allocate %zu bytes\n", num * size); exit(EXIT_FAILURE); } return mem; } void *erealloc(void *ptr, size_t num, size_t size) { void *mem = realloc(ptr, num * size); if (!mem && size) { fprintf(stderr, "Failed to reallocate %zu bytes\n", num * size); exit(EXIT_FAILURE); } return mem; }
c
9
0.644628
66
20.175
40
starcoderdata
void ED_object_add_generic_props(wmOperatorType *ot, int do_editmode) { PropertyRNA *prop; /* note: this property gets hidden for add-camera operator */ prop= RNA_def_boolean(ot->srna, "view_align", 0, "Align to View", "Align the new object to the view"); RNA_def_property_update_runtime(prop, view_align_update); if(do_editmode) { prop= RNA_def_boolean(ot->srna, "enter_editmode", 0, "Enter Editmode", "Enter editmode when adding this object"); RNA_def_property_flag(prop, PROP_HIDDEN); } RNA_def_float_vector_xyz(ot->srna, "location", 3, NULL, -FLT_MAX, FLT_MAX, "Location", "Location for the newly added object", -FLT_MAX, FLT_MAX); RNA_def_float_rotation(ot->srna, "rotation", 3, NULL, -FLT_MAX, FLT_MAX, "Rotation", "Rotation for the newly added object", (float)-M_PI * 2.0f, (float)M_PI * 2.0f); prop = RNA_def_boolean_layer_member(ot->srna, "layers", 20, NULL, "Layer", ""); RNA_def_property_flag(prop, PROP_HIDDEN); }
c
10
0.691332
166
48.842105
19
inline
package main import "fmt" var ( a [1024]byte prog = "++++++++++[>++++++++++ p,pc int ) func loop(inc int){ for i := inc; i != 0; pc +=inc { switch prog[pc+inc] { case '[': i++ case ']': i-- } } } func main() { for { switch prog[pc] { case '>': p++ case '<': p-- case '+': a[p]++ case '-': a[p]-- case '.': fmt.Printf("%c",a[p]) case '[': if a[p] == 0 { loop(1) } case ']': if a[p] != 0 { loop(-1) } default: fmt.Println("Illegal instruction") } pc++ if pc == len(prog) { fmt.Println() return } } } /* 本程序实现了一个简单的编译器.目标语言为brainfuck语言 该语言为图灵完备的,也就是计算能力与图灵机等价. 该语言本身语法规范,异常简单. + 当前值加1 - 当前值减1 > 以下一个单元作为当前值 < 以上一个单元作为当前值 [ 若当前值为0,则jmp到对应的]之后 ] 若当前值不为0,则jmp到对应的[之后 . 输出当前值,以字符形式 可以看到代码中,以a为存储空间,以prog为程序空间. p为存储空间指针,pc为prog程序空间指针 loop函数实现了跳转功能 这里的loop函数实现很精妙 auth: liuyang1 mtime: 2013-03-24 15:29:39 */ /* 因此上面的代码就可以如下翻译 "++++++++++[>++++++++++ brainfuck: +++++++++++ c sytle: a[0]=10 brainfuck: [>++++++++++<-] c sytle: while(a[0]>0] a[1]+=10 a[0]-- brainfuck: >++++.+. c sytle: a[1]+=4 printf("%c",a[1]) a[1]++ printf("%c",a[1]) */
go
13
0.498734
43
12.166667
90
starcoderdata
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace NatesJauntyTools { /// Used for organizing many boolean conditions into a single output. public class Conditions { const char trueCharacter = 'Y'; const char falseCharacter = 'N'; string[] names; bool[] values; public Conditions() { Clear(); } int GrowArray() { string[] newNames = new string[names.Length + 1]; Array.Copy(names, newNames, names.Length); names = newNames; bool[] newValues = new bool[values.Length + 1]; Array.Copy(values, newValues, values.Length); values = newValues; return names.Length - 1; } public void Track(bool condition, string name = "") { int newItemIndex = GrowArray(); names[newItemIndex] = name; values[newItemIndex] = condition; } public void Clear() { names = new string[0]; values = new bool[0]; } public bool AND() { for (int i = 0; i < values.Length; i++) { if (values[i] == false) { return false; } } return true; } public bool OR() { for (int i = 0; i < values.Length; i++) { if (values[i] == true) { return true; } } return false; } public void DebugLog(bool hideNames = false) { string logString = ""; for (int i = 0; i < values.Length; i++) { logString += MessageForIndex(i, hideNames); } Debug.Log(logString); } string MessageForIndex(int i, bool hideNames) { if (names[i] == "" || hideNames) { if (i < values.Length) { return (values[i]) ? $"[{trueCharacter}] " : $"[{falseCharacter}] "; } else { return (values[i]) ? $"[{trueCharacter}]" : $"[{falseCharacter}]"; } } else { if (i < values.Length) { return (values[i]) ? $"[{names[i]} : {trueCharacter}] " : $"[{names[i]} : {falseCharacter}] "; } else { return (values[i]) ? $"[{names[i]} : {trueCharacter}]" : $"[{names[i]} : {falseCharacter}]"; } } } public string GetFailures() { List failures = new List for (int i = 0; i < values.Length; i++) { if (!values[i]) { failures.Add(names[i]); } } return String.Join(", ", failures); } public string GetSuccesses() { List successes = new List for (int i = 0; i < values.Length; i++) { if (values[i]) { successes.Add(names[i]); } } return String.Join(", ", successes); } } }
c#
18
0.580645
99
19.162602
123
starcoderdata
#pragma once #include "ShaderProgram.h" #include #include "../entities/Camera.h" #include "../entities/Light.h" #include "../utils/Maths.h" class TerrainShader :public ShaderProgram { public: TerrainShader(); void loadTransformationMatrix(glm::mat4 matrix); void loadProjectionMatrix(glm::mat4 matrix); void loadViewMatrix(Camera* camera); void loadLights(std::vector *lights); void loadShineVariables(GLfloat damper, GLfloat reflectivity); void loadSkyColour(float r, float g, float b); void connectTextureUnits(); protected: void bindAttributes(); void getAllUniformLocations(); private: int location_transformationMatrix; int location_projectionMatrix; int location_viewMatrix; std::vector location_lightPosition; std::vector location_lightColour; std::vector location_attenuation; int location_shineDamper; int location_reflectivity; int location_skyColour; int location_backgroundTexture; int location_rTexture; int location_gTexture; int location_bTexture; int location_blendMap; };
c
8
0.780952
63
26.631579
38
starcoderdata
var reflux = require('Reflux'); var ProjectAction = reflux.createActions([ 'addNewProject', 'retrieveUserProjects', 'retrieveProjects', 'viewProject', 'addComment', 'retrieveProjectComments', 'deleteProject', 'editProject', 'updateProject', 'fundProject' ]); export default ProjectAction;
javascript
3
0.729167
42
17.722222
18
starcoderdata
/* * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth.instrument.web.client.exception; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.Collections; import java.util.Map; import brave.Span; import brave.Tracer; import brave.Tracing; import brave.sampler.Sampler; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.cloud.sleuth.util.ArrayListSpanReporter; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RestTemplate; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import static org.assertj.core.api.BDDAssertions.then; @RunWith(JUnitParamsRunner.class) @SpringBootTest(classes = { WebClientExceptionTests.TestConfiguration.class }, properties = {"ribbon.ConnectTimeout=30000", "spring.application.name=exceptionservice" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class WebClientExceptionTests { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @ClassRule public static final SpringClassRule SCR = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); @Rule public final OutputCapture capture = new OutputCapture(); @Autowired TestFeignInterfaceWithException testFeignInterfaceWithException; @Autowired @LoadBalanced RestTemplate template; @Autowired Tracing tracer; @Autowired ArrayListSpanReporter reporter; @Before public void open() { this.reporter.clear(); } // issue #198 @Test @Parameters public void shouldCloseSpanUponException(ResponseEntityProvider provider) throws IOException { Span span = this.tracer.tracer().nextSpan().name("new trace").start(); try (Tracer.SpanInScope ws = this.tracer.tracer().withSpanInScope(span)) { log.info("Started new span " + span); provider.get(this); Assert.fail("should throw an exception"); } catch (RuntimeException e) { // SleuthAssertions.then(e).hasRootCauseInstanceOf(IOException.class); } finally { span.finish(); } then(this.tracer.tracer().currentSpan()).isNull(); then(this.reporter.getSpans()).isNotEmpty(); then(this.reporter.getSpans().get(0).tags().get("error")) .contains("invalid.host.to.break.tests"); } Object[] parametersForShouldCloseSpanUponException() { return new Object[] { (ResponseEntityProvider) (tests) -> tests.testFeignInterfaceWithException .shouldFailToConnect(), (ResponseEntityProvider) (tests) -> tests.template .getForEntity("http://exceptionservice/", Map.class) }; } @FeignClient("exceptionservice") public interface TestFeignInterfaceWithException { @RequestMapping(method = RequestMethod.GET, value = "/") ResponseEntity shouldFailToConnect(); } @Configuration @EnableAutoConfiguration @EnableFeignClients @RibbonClient(value = "exceptionservice", configuration = ExceptionServiceRibbonClientConfiguration.class) public static class TestConfiguration { @LoadBalanced @Bean public RestTemplate restTemplate() { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); clientHttpRequestFactory.setReadTimeout(1); clientHttpRequestFactory.setConnectTimeout(1); return new RestTemplate(clientHttpRequestFactory); } @Bean Sampler alwaysSampler() { return Sampler.ALWAYS_SAMPLE; } @Bean ArrayListSpanReporter accumulator() { return new ArrayListSpanReporter(); } } @Configuration public static class ExceptionServiceRibbonClientConfiguration { @Bean public ILoadBalancer exceptionServiceRibbonLoadBalancer() { BaseLoadBalancer balancer = new BaseLoadBalancer(); balancer.setServersList(Collections .singletonList(new Server("invalid.host.to.break.tests", 1234))); return balancer; } } @FunctionalInterface interface ResponseEntityProvider { ResponseEntity get( WebClientExceptionTests webClientTests); } }
java
15
0.794726
142
34.247059
170
starcoderdata
using System; using System.Collections.Generic; using System.Linq; namespace SFA.DAS.EmployerIncentives.Web.Models { public class ApplicationModel { public Guid ApplicationId { get; } public string AccountId { get; } public string AccountLegalEntityId { get; } public Decimal TotalPaymentAmount { get; } public List Apprentices { get; } public bool BankDetailsRequired { get; } public bool NewAgreementRequired { get; } public string OrganisationName { get; set; } public ApplicationModel(Guid applicationId, string accountId, string accountLegalEntityId, IEnumerable apprentices, bool bankDetailsRequired, bool newAgreementRequired) { ApplicationId = applicationId; AccountId = accountId; AccountLegalEntityId = accountLegalEntityId; Apprentices = apprentices.ToList(); TotalPaymentAmount = Apprentices.Sum(x => x.ExpectedAmount); BankDetailsRequired = bankDetailsRequired; NewAgreementRequired = newAgreementRequired; } } }
c#
15
0.708239
208
39.090909
33
starcoderdata
using System; using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore; namespace edX.DataApp.Lab.CoreConsole { public class ContosoContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string connectionString = @"Data Source=(localdb)\MSSQLLOCALDB;Initial Catalog=ContosoDB;"; optionsBuilder.UseSqlServer(connectionString); } public DbSet Products { get; set; } } }
c#
11
0.717117
103
28.210526
19
starcoderdata
import logging import re from streamlink.plugin import Plugin from streamlink.plugin.api import http log = logging.getLogger(__name__) class Mediaklikk(Plugin): _url_re = re.compile(r'https?://(?:www\.)?mediaklikk\.hu/') _id_re = re.compile(r'''(?P new_self_url = 'https://player.mediaklikk.hu/playernew/player.php?video={0}' @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) def _get_streams(self): log.debug('Version 2018-07-01') log.info('This is a custom plugin. ' 'For support visit https://github.com/back-to/plugins') res = http.get(self.url) m = self._id_re.search(res.text) if not m: log.info('Found no videoid.') self.url = 'resolve://{0}'.format(self.url) return self.session.streams(self.url) video_id = m.group('id') if video_id: log.debug('Found id: {0}'.format(video_id)) self.url = self.new_self_url.format(video_id) return self.session.streams(self.url) __plugin__ = Mediaklikk
python
13
0.581554
94
27.560976
41
starcoderdata
/* * Copyright (c) 2022 Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ #pragma once #include typedef std::chrono::time_point TimePoint; class Timer { static const std::chrono::high_resolution_clock s_Clock; TimePoint m_StartTime; public: static TimePoint Now() { return s_Clock.now(); } Timer(); /// Get time spent since construction of this object in seconds float GetTimeS() const { return (float)(s_Clock.now() - m_StartTime).count() * 1e-9; } };
c
14
0.718706
115
25.333333
27
starcoderdata
package minimax.fourinarow.core.arrays.core; import java.util.Arrays; import utils.implementation.core.AbstractGameState; /** * * 2D array based Four In A Row specific game-state. * * @author * */ public class FourInARowGameState extends AbstractGameState { public static int ROWS = 6; public static int COLUMNS = 7; public static int MAX_NUMBER_OF_PLYS = 42; /** * 2D array "Game Board" filled with pieces. Has dimensions ROWS X COLUMNS. */ private Piece[][] board; private Piece currentPlayer; /** * The next open row in every column. The bottom row is 6 and the top row is 0. */ private int[] nextOpenRowInColumns; public FourInARowGameState(int plyNumber, Piece[][] board, Piece currentPlayer) { super(plyNumber); this.board = board; this.currentPlayer = currentPlayer; this.nextOpenRowInColumns = new int[COLUMNS]; this.calculateNextOpenRowInColumns(); } /** * * @param plyNumber * @param board * @param currentPlayer * @param nextOpenRowInColumns */ public FourInARowGameState(int plyNumber, Piece[][] board, Piece currentPlayer, int[] nextOpenRowInColumns) { super(plyNumber); this.board = copyBoard(board); this.currentPlayer = currentPlayer; this.nextOpenRowInColumns = Arrays.copyOf(nextOpenRowInColumns, COLUMNS); } /** * * Creates a new copy of the given board. Utilized in the private constructor. * * @param board * @return */ private Piece[][] copyBoard(Piece[][] board) { Piece[][] copy = new Piece[ROWS][]; for (int row = 0; row < ROWS; ++row) { copy[row] = Arrays.copyOf(board[row], COLUMNS); } return copy; } /** * If this is externally mutable then a reference to this game-state's board is * returned directly otherwise a copy is made and returned. * * @return - either reference or copy of current game board. */ public Piece[][] getBoard() { return copyBoard(board); } public Piece getCurrentPlayer() { return currentPlayer; } /** * If this is externally mutable then a reference is returned directly otherwise * a copy is made and returned. * * @return - either reference or copy of the current array of next move in every * column. */ public int[] getNextOpenRowInColumns() { return Arrays.copyOf(nextOpenRowInColumns, COLUMNS); } /** * * @param column - the column to look for the next open move in. * @return - the next open row in the column. */ public int getNextOpenRowInColumn(int column) { return nextOpenRowInColumns[column]; } /** * Places a piece on the board and decrements the next open space in that * column. Increments plyNumber then swaps current players. */ @Override public void makeMove(FourInARowMove move) { board[nextOpenRowInColumns[move.getColumn()]--][move.getColumn()] = currentPlayer; plyNumber++; currentPlayer = Piece.swapPlayerPiece(currentPlayer); } /** * Deletes a piece off of the board and increments the next open space in that * column. Decrements plyNumber then swaps current players. */ @Override public void undoMove(FourInARowMove move) { board[++nextOpenRowInColumns[move.getColumn()]][move.getColumn()] = Piece.__EMPTY___; plyNumber--; currentPlayer = Piece.swapPlayerPiece(currentPlayer); } /** * Calculates the lowest empty row in every column. */ private void calculateNextOpenRowInColumns() { for (int column = 0; column < COLUMNS; ++column) { for (int row = ROWS - 1; row >= 0; --row) { if (board[row][column] == Piece.__EMPTY___) { nextOpenRowInColumns[column] = row; break; } } } } @Override public int hashCode() { return Arrays.hashCode(board); } @Override public String toString() { StringBuilder stateString = new StringBuilder(); stateString.append("Current Player : " + currentPlayer.name() + "\n"); stateString.append("Ply: " + plyNumber + "\n"); for (Piece[] row : board) { for (Piece piece : row) { stateString.append(piece.name() + " "); } stateString.append("\n"); } return stateString.toString(); } }
java
15
0.686611
110
24.810127
158
starcoderdata
<?php namespace Sonic\UnitTest; use Sonic\UnitTest\Result\Error; use Sonic\UnitTest\Result\Failure; use Sonic\UnitTest\Result\Success; /** * Tracker * * Used to track failures, successes, errors, and coverage for the the entire * test run * * @category Sonic * @package UnitTest * @author */ class Tracker { /** * @var Tracker */ protected static $_instance; /** * @var array */ protected $_failures = array(); /** * @var array */ protected $_successes = array(); /** * @var array */ protected $_errors = array(); /** * @var array */ protected $_coverages = array(); /** * @var int */ protected $_test_count = 0; /** * constructor * * @return void */ private function __construct() {} /** * gets Tracker instance * * @return Tracker */ public static function getInstance() { if (!self::$_instance instanceof Tracker) { self::$_instance = new Tracker(); } return self::$_instance; } /** * adds a failure for the run * * @param Failure * @return void */ public static function addFailure(Failure $failure) { $results = self::getInstance(); $results->_failures[] = $failure; } /** * adds an error for the run * * @param Error * @return void */ public static function addError(Error $error) { $results = self::getInstance(); $results->_errors[] = $error; } /** * adds a success for the run * * @param Success */ public static function addSuccess(Success $success) { $results = self::getInstance(); $results->_successes[] = $success; } /** * increments the test count when a new test gets run * * @return void */ public function incrementTestCount() { ++$this->_test_count; } /** * gets the total number of assertions * * @return int */ public function getAssertionCount() { return count($this->_successes) + count($this->_failures) + count($this->_errors); } /** * gets an array of all failures * * @return array */ public function getFailures() { return $this->_failures; } /** * gets an array of all errors * * @return array */ public function getErrors() { return $this->_errors; } /** * outputs stats to the command line * * @return void */ public function outputStats() { $this->output("\n\nRESULTS\n", 'white', 'black', true); $this->output('Tests: ' . $this->_test_count . "\n"); $this->output('Assertions: ' . $this->getAssertionCount() . "\n"); $this->output('Failures: ' . count($this->_failures) . "\n"); $this->output('Errors: ' . count($this->_errors) . "\n"); } /** * outputs failures to command line * * @return void */ public function outputFailures() { $failures = ''; foreach ($this->getFailures() as $key => $failure) { $i = $key + 1; $failures .= $i . '. ' . $failure->getMessage() . "\n"; $failures .= ' ' . $failure->getMethod() . "\n"; $failures .= ' ' . $failure->getFile() . "\n"; $failures .= ' Line ' . $failure->getLine() . "\n"; } return $this->output($failures); } /** * outputs errors to command line * * @return void */ public function outputErrors() { $errors = ''; foreach ($this->getErrors() as $key => $error) { $i = $key + 1; $errors .= $i . '. ' . $error->getMessage() . "\n"; $errors .= ' ' . $error->getMethod() . "\n"; $errors .= ' ' . $error->getFile() . "\n"; $errors .= ' Line ' . $error->getLine() . "\n"; } return $this->output($errors); } /** * outputs a message to command line * * @todo make background color work * @param string $message * @param string $color * @param string $background * @param bool $bold * @return void */ public function output($message, $color = null, $background = null, $bold = false) { $bold = $bold ? 1 : 0; $start = "\033[{$bold};"; switch ($color) { case 'black': $start .= '30m'; break; case 'red': $start .= '31m'; break; case 'green': $start .= '32m'; break; case 'yellow': $start .= '33m'; break; case 'blue': $start .= '34m'; break; case 'pink': $start .= '35m'; break; case 'light blue': $start .= '36m'; break; default: $start .= '37m'; break; } echo $start . $message; echo "\033[0;37m"; } /** * adds a coverage report to the tracker * * @param Coverage $coverage * @return void */ public function addCoverage(Coverage $coverage) { $this->_coverages[] = $coverage; } /** * gets all coverage reports for the run * * @return array */ public function getCoverages() { return $this->_coverages; } /** * gets total lines of code that can be tested/run * * @return int */ public function getTotalLines() { $lines = 0; foreach ($this->getCoverages() as $coverage) { $lines += $coverage->getLineCount(); } return $lines; } /** * gets total lines of code that have been run * * @return int */ public function getCoveredLines() { $lines = 0; foreach ($this->getCoverages() as $coverage) { $lines += $coverage->getCoveredLineCount(); } return $lines; } /** * gets total coverage for all files processed * * @return float */ public function getTotalCoverage() { return round(($this->getCoveredLines() / $this->getTotalLines()) * 100, 2); } }
php
16
0.473354
90
20.986532
297
starcoderdata
/** * Video.js Topbar Buttons * Created by * License information: https://github.com/slavrinja/videojs-topbar-buttons/blob/master/LICENSE * Plugin details: https://github.com/slavrinja/videojs-topbar-buttons */ (function(videojs) { 'use strict'; videojs.plugin('topBarButtons', function(opts) { opts = opts || {}; var player = this; var _ss; //TODO remove jQuery $("body").prepend( '<div class="vjs-share-block hidden">\n' + ' Video: + '<div class="a2a_kit text-center">\n' + '<a class="btn btn-social btn-facebook a2a_button_facebook "> + '<a class="btn btn-social btn-reddit a2a_button_reddit"> + '<a class="btn btn-social btn-telegram a2a_button_telegram"> + '<a class="btn btn-social btn-twitter a2a_button_twitter"> + '<a class="btn btn-social btn-viber a2a_button_viber"> + '<a class="btn btn-social btn-whatsapp a2a_button_whatsapp"> + ' + ' + 'var a2a_config = a2a_config || {};\n' + 'a2a_config.locale = "ru";\n' + ' + '<script async src="https://static.addtoany.com/menu/page.js"> + ' $("body").prepend( '<div class="vjs-feedback-block hidden">\n' + '<ul class="dropdown-menu dropdown-feedback">\n' + ' data-feedtype="start_slow" class="btn btn-warning btn-block" href="javascript:void(0);">Long pause before video start + ' data-feedtype="start_fail" class="btn btn-warning btn-block" href="javascript:void(0);">Video does not play at all + ' data-feedtype="play_slow" class="btn btn-warning btn-block" href="javascript:void(0);">Video plays slowly or with buffering + ' data-feedtype="subtitles_fail" class="btn btn-warning btn-block" href="javascript:void(0);">Problems with subtitles + ' data-feedtype="ads_fail" class="btn btn-warning btn-block" href="javascript:void(0);">Noisy or scam Ads // add class for LIO-mode switching document.getElementById(player.id()).classList.add('.vjs-light-player'); var _lio = true; // light is on /** * Returns HTML template for button with icon set from param * @param icon - name of FA-icon */ function buttonTemplate(icon) { return '<div class="vjs-topbar-button__icon"><i class="fa ' + icon + '" aria-hidden="true"> } /** * Toggling light behind player * Used for Toggle light button * @param e */ function launchToggleLights(e) { e.preventDefault(); if (_lio) { _lio = false; document.getElementsByTagName("body")[0].classList.add('vjs-light--off'); document.getElementsByClassName('fa-lightbulb-o')[0].classList.add('vjs-topbar-button__icon--off'); } else { _lio = true; document.getElementsByTagName("body")[0].classList.remove('vjs-light--off'); document.getElementsByClassName('fa-lightbulb-o')[0].classList.remove('vjs-topbar-button__icon--off'); } } /** * Redirects page to the URL * Used for Watch on site button * @param e */ function launchWatchOnSite(e) { e.preventDefault(); if (opts.watchOnSite.url !== undefined && opts.watchOnSite.url != '') { window.location.href = opts.watchOnSite.url; } } /** * Show share dialog * Share button handler * @param e */ function launchShare(e) { e.preventDefault(); var ModalDialog = videojs.getComponent('ModalDialog'); var modal = new ModalDialog(player, { // We don't want this modal to go away when it closes. temporary: false }); player.addChild(modal); modal.addClass('vjs-share-modal'); // console.log(); // var shareBlock = document.createElement('div'); // shareBlock.className = 'vjs-share-block-modal'; // shareBlock.innerHTML = document.getElementsByClassName('vjs-share-block')[0].innerHTML; // modal.content($('.vjs-share-block').html()); //TODO remove jQuery setTimeout(function(){ // Copy modal window body $('#player').find('.vjs-modal-dialog-content').html($('.vjs-share-block').html()); }, 500); modal.open(); } /** * Show feedback dialog * feedback button handler * @param e */ function launchFeedback(e) { e.preventDefault(); var ModalDialog = videojs.getComponent('ModalDialog'); var modal = new ModalDialog(player, { // We don't want this modal to go away when it closes. temporary: false }); player.addChild(modal); modal.addClass('vjs-feedback-modal'); //todo remove jQuery setTimeout(function(){ // Copy modal window body $('#player').find('.vjs-modal-dialog-content').html($('.vjs-feedback-block').html()); }, 500); modal.open(); // Send feedback at the base of feedtype clicked $('body').on('click', '.dropdown-feedback a', function() { var feedtype = $(this).data('feedtype'); console.log('send ' + feedtype); modal.close(); }); } /** * Generate the DOM elements for the topbar buttons * @type {function} */ function constructTopButtonsContent() { var _frag = document.createDocumentFragment(); var _aside = document.createElement('aside'); var _button; if (opts.feedback) { console.log('build feedback'); _button = document.createElement('a'); _button.className = 'vjs-topbar-button'; _button.setAttribute('data-title', opts.feedback.title); _button.innerHTML = buttonTemplate(opts.feedback.icon); _button.addEventListener('click', launchFeedback, false); _aside.appendChild(_button); } if (opts.watchOnSite) { console.log('build watchOnSite'); _button = document.createElement('a'); _button.className = 'vjs-topbar-button'; _button.setAttribute('data-title', opts.watchOnSite.title); _button.innerHTML = buttonTemplate(opts.watchOnSite.icon); _button.addEventListener('click', launchWatchOnSite, false); _aside.appendChild(_button); } if (opts.share) { console.log('build share'); _button = document.createElement('a'); _button.className = 'vjs-topbar-button'; _button.setAttribute('data-title', opts.share.title); _button.innerHTML = buttonTemplate(opts.share.icon); _button.addEventListener('click', launchShare, false); _aside.appendChild(_button); } if (opts.toggleLights) { console.log('build toggleLights'); _button = document.createElement('a'); _button.className = 'vjs-topbar-button'; _button.setAttribute('data-title', opts.toggleLights.title); _button.innerHTML = buttonTemplate(opts.toggleLights.icon); _button.addEventListener('click', launchToggleLights, false); _aside.appendChild(_button); } _aside.className = 'vjs-topbar'; _ss = _aside; _frag.appendChild(_aside); player.el().appendChild(_frag); } // attach VideoJS event handlers player.on('mouseover', function() { // on hover, fade in the social share tools _ss.classList.add('is-visible'); }); player.on('mouseout', function() { // when not hovering, fade share tools back out _ss.classList.remove('is-visible'); }); /** * Start plugin */ player.ready(function() { if (opts.toggleLights || opts.share || opts.watchOnSite || opts.feedback) { constructTopButtonsContent(); } }); }); }(window.videojs));
javascript
30
0.522775
165
39.314159
226
starcoderdata
DefaultScript.global.exists = remember(null, '@exists', function $logic$(scopes, step, stepName, key, onException) { if (typeof key !== 'string') { throw new SyntaxError('Cannot determine if name exists'); } for (var i = 0; i < scopes.length; i++) { var itemType = DefaultScript.global.type(scopes[i]); if (itemType === 'undefined') { return false; } if (scopes[i] === null) { return false; } if (itemType === 'object' && (key in scopes[i])) { var val = scopes[i][key]; if (DefaultScript.global.type(val) === 'function') { val = val.bind(scopes[i]); } return val !== undefined; } if (itemType in DefaultScript.protoOverrides) { var property = DefaultScript.protoOverrides[itemType][key]; if (typeof property === 'string') { val = scopes[i][property]; if (DefaultScript.global.type(val) === 'function') { val = val.bind(scopes[i]); } return val !== undefined;; } else if (typeof property === 'function') { return true; } else { continue; } } var proto; switch (itemType) { case 'logic': return false; case 'number': proto = Number; break; case 'boolean': proto = Boolean; break; case 'string': proto = String; break; case 'function': proto = Function; break; case 'object': case 'array': proto = Object.getPrototypeOf(scopes[i]); break; default: throw new Error('Invalid scope type: ' + itemType); } if (proto && (key in proto)) { var val = scopes[i][key]; if (DefaultScript.global.type(val) === 'function') { val = val.bind(scopes[i]); } return val !== undefined; } } if (key[0] === '@') { var globalKey = key.substr(1); if (globalKey in DefaultScript.global) { return globalKey in DefaultScript.global; } } return false; });
javascript
20
0.533886
116
22.574713
87
starcoderdata
function form_validate_addError($field, label) { app_missingFields = app_missingFields.concat(label); } function dob_validator($field) { var val = $.trim($field.val()); if (val.length == 0) { return "Birth date cannot be empty"; } var dob = new Date(val); var today = new Date(); if (dob > today) { return "Birth date cannot be in the future"; } } function form_validate_dob(selector, label) { if (_.isObject(selector)) { return dob_validator(selector); } else { form_validate__each(selector, dob_validator, label); } } function form_validate_checked(selector, label) { var checkedValidator = function($field) { if(!$field.is(':checked')) { return "must be checked"; } } form_validate__each(selector, checkedValidator, label); } function form_validate_date(selector, label) { var dateValidator = function($field) { if (util_isDate($.trim($field.val())) == false ) { return 'must be valid date'; } } form_validate__each(selector, dateValidator, label); } function form_validate_clearErrors() { app_missingFields = []; app_formError = false; util_clearErrors(); } function form_validate(callback, options={}) { var validator = options.validator; if (!validator) return; var form = options.form || app_form; form_validate_clearErrors(); if (validator) { validator(form); } if (app_formError === true || app_missingFields.length > 0) { var missingFieldsTitle = ""; var missingFieldsText = ""; if (app_missingFields.length > 0) { missingFieldsTitle = " + "The following fields are required to proceed:" + " missingFieldsText = "<ul class='text-danger'>"; for (var i=0;i<app_missingFields.length;i++) { missingFieldsText += " + app_missingFields[i] + " } missingFieldsText += " } var showDialog = $('#pi-missing-fields').length == 0; if (showDialog || options.dialog) { var modalH4Text = "The following fields are required to proceed:"; var modalBodyText = missingFieldsText; if (app_formError) { modalH4Text = "Please fix the highlighted errors on the page to proceed." modalBodyText = ""; } var args = _.extend({ modalH4: modalH4Text, modalBodyText: modalBodyText }, options.dialog, { okButton: 'Ok', cancelButton: null }); RenderUtil.render('dialog/confirm', args, function(s) { $('#modal-confirm').remove(); $('#modals-placement').append(s); $('#modal-confirm').modal('show'); }); } else { $('#pi-missing-fields').html(missingFieldsTitle + missingFieldsText); $('#pi-no-errors').hide(); $('#pi-with-errors').show(); } } else { callback(); } } function form_validate__each(selector, errorFn, label) { var $field, errMsg; $(selector).each(function(_, field){ $field = $(field); if (errMsg = errorFn($field)) { form_validate_addError($field, label, errMsg); util_showError($field, errMsg == true ? undefined : errMsg); } else { util_clearItemError($field); } }) } function form_validate_empty(selector, label) { form_validate__each(selector, util_isFieldEmpty, label) } function form_validate_regex(selector, regex, label) { var regexValidator = function($field) { return util_checkRegexp($.trim($field.val()), regex) == false; } form_validate__each(selector, regexValidator, label) } function form_validateField($this) { var isValid = true; util_clearItemError($this); var id = $this.attr('id'); var updateProperty = $this.attr('data-property'); if (typeof updateProperty == 'undefined') { return; } var errorFns = form_field_getValidators($this); var testValidators = function() { errorFn = errorFns.shift(); if (errorFn) { if (errMsg = errorFn($this)) { util_showError($this, errMsg); return false; } else { testValidators(); } } } testValidators(); var updatePropertyValue = $this.val(); var updatePropertyArray = updateProperty.split('.'); var className = updatePropertyArray[0]; var property = updatePropertyArray[1]; if (className == "bh-entity-form-ClientContact") { if (property == 'firstName' && util_isFieldEmpty('#cc-first-name')) { util_showError($('#cc-first-name')); return false; } else if (property == 'lastName' && util_isFieldEmpty('#cc-last-name')) { util_showError($('#cc-last-name')); return false; } else if (property == 'dob' && util_isDate($.trim($('#cc-dob').val())) == false) { util_showError($('#cc-dob'), 'must be valid date'); return false; } else if (property == 'signer' && util_isFieldEmpty('#cc-signer')) { util_showError($('#cc-signer')); return false; } else if (property == 'signerRelationship' && util_isFieldEmpty('#cc-signer-rel')) { util_showError($('#cc-signer-rel')); return false; } else if (property == 'voicemailOk' && util_isFieldEmpty('#cc-voicemail-ok')) { util_showError($('#cc-voicemail-ok')); return false; } else if (property == 'msgOk' && util_isFieldEmpty('#cc-msg-ok')) { util_showError($('#cc-msg-ok')); return false; } else if (property == 'cellMsgOk' && util_isFieldEmpty('#cc-cell-msg-ok')) { util_showError($('#cc-cell-msg-ok')); return false; } else if (property == 'textOk' && util_isFieldEmpty('#cc-text-msg-ok')) { util_showError($('#cc-cell-text-ok')); return false; } else if (property == 'textWaiverSigned' && util_isFieldEmpty('#cc-text-waiver-signed')) { util_showError($('#cc-cell-text-waiver-signed')); return false; } else if (property == 'callWorkOk' && util_isFieldEmpty('#cc-call-work-ok')) { util_showError($('#cc-call-work-ok')); return false; } else if (property == 'msgWorkOk' && util_isFieldEmpty('#cc-msg-work-ok')) { util_showError($('#cc-msg-work-ok')); return false; } else if (property == 'noInfo' && util_isFieldEmpty('#cc-no-info')) { util_showError($('#cc-no-info')); return false; } else if (property == 'completedBy' && util_isFieldEmpty('#cc-completed-by')) { util_showError($('#cc-completed-by')); return false; } else if (property == 'completedByDate' && util_isDate($.trim($('#cc-completed-by-date').val())) == false) { util_showError($('#cc-completed-by-date'), 'must be valid date'); return false; } } else if (className == "bh-entity-form-ClientRights") { if (property == 'name' && util_isFieldEmpty('#cr-name')) { util_showError($('#cr-name')); return false; } else if (property == 'dob' && util_isDate($.trim($('#cr-dob').val())) == false) { util_showError($('#cr-dob'), 'must be valid date'); return false; } else if (property == 'signedDate' && util_isDate($.trim($('#cr-signed-date').val())) == false) { util_showError($('#cr-signed-date'), 'must be valid date'); return false; } } else if (className == "bh-entity-form-Consent") { if (property == 'respName' && util_isFieldEmpty('#consent-resp-name')) { util_showError($('#consent-resp-name')); return false; } else if (property == 'respDate' && util_isDate($.trim($('#consent-resp-date').val())) == false) { util_showError($('#consent-resp-date'), 'must be valid date'); return false; } } else if (className == "bh-entity-form-TextingWaiver") { if (property == 'name' && util_isFieldEmpty('#texting-name')) { util_showError($('#texting-name')); return false; } else if (property == 'guardian' && util_isFieldEmpty('#texting-guardian')) { util_showError($('#texting-guardian')); return false; } else if (property == 'guardianDate' && util_isDate($.trim($('#texting-guardian-date').val())) == false) { util_showError($('#texting-guardian-date'), 'must be valid date'); return false; } else if (property == 'provider' && util_isFieldEmpty('#texting-provider')) { util_showError($('#texting-provider')); return false; } else if (property == 'providerDate' && util_isDate($.trim($('#texting-provider-date').val())) == false) { util_showError($('#texting-provider-date'), 'must be valid date'); return false; } } else if (className == "pot-entity-form-POTPatientForm") { if (property == 'govtId' && util_checkRegexp($.trim($("#patient-form-ssn").val()), util_ssnRegexObj) == false) { util_showError($('#patient-form-ssn'), 'invalid ssn'); return false; } } else if (className == "entity-form-Invoice") { if (property == 'issueDate' && util_isDate($.trim($('#invoice-issue-date').val())) == false) { util_showError($('#invoice-issue-date'), 'must be valid date'); return false; } } return true; }
javascript
28
0.59636
116
32.054348
276
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Dmarc.Common.Interface.PublicSuffix; using Dmarc.Common.Interface.PublicSuffix.Domain; using Dmarc.DnsRecord.Evaluator.Dmarc.Domain; using Dmarc.DnsRecord.Evaluator.Dmarc.Rules.Record; using Dmarc.DnsRecord.Evaluator.Rules; using FakeItEasy; using NUnit.Framework; namespace Dmarc.DnsRecord.Evaluator.Test.Dmarc.Rules.Record { [TestFixture] public class SubDomainPolicyShouldNotBeOnNonOrganisationalDomainTests { private SubDomainPolicyShouldNotBeOnNonOrganisationalDomain _rule; [SetUp] public void SetUp() { _rule = new SubDomainPolicyShouldNotBeOnNonOrganisationalDomain(); } [Test] public void NoErrorWhenOnOrganisationalDomain() { string domain = "abc.com"; DmarcRecord dmarcRecord = new DmarcRecord("", new List { new SubDomainPolicy("", PolicyType.Unknown) }, domain, domain, false, false); Error error; bool isErrored = _rule.IsErrored(dmarcRecord, out error); Assert.That(isErrored, Is.EqualTo(false)); Assert.That(error, Is.Null); } [Test] public void NoErrorWhenNosubDomainPolicyAndNonOrganisationalDomain() { string domain = "abc.com"; DmarcRecord dmarcRecord = new DmarcRecord("", new List domain, domain, false, false); Error error; bool isErrored = _rule.IsErrored(dmarcRecord, out error); Assert.That(isErrored, Is.EqualTo(false)); Assert.That(error, Is.Null); } [Test] public void NoErrorWhenOnNonOrganisationalDomainIsImpicit() { string domain = "abc.com"; DmarcRecord dmarcRecord = new DmarcRecord("", new List { new SubDomainPolicy("", PolicyType.Unknown, true) }, domain, "def.com", false, false); Error error; bool isErrored = _rule.IsErrored(dmarcRecord, out error); Assert.That(isErrored, Is.EqualTo(false)); Assert.That(error, Is.Null); } [Test] public void ErrorWhenOnNonOrganisationalDomain() { string domain = "abc.com"; DmarcRecord dmarcRecord = new DmarcRecord("", new List { new SubDomainPolicy("", PolicyType.Unknown) }, domain, "def.com", false, false); Error error; bool isErrored = _rule.IsErrored(dmarcRecord, out error); Assert.That(isErrored, Is.EqualTo(true)); Assert.That(error, Is.Not.Null); Assert.That(error.Message, Is.EqualTo($"The specified sub-domain policy (sp) is ineffective because {domain} is not an organisational domain.")); } } }
c#
20
0.636364
157
32.733333
90
starcoderdata
bool CFontTextureCache::GetTextureAndCoordsForChar( FontHandle_t font, FontDrawType_t type, wchar_t wch, int *textureID, float *texCoords ) { // Ask for just one character float *textureCoords = NULL; bool bSuccess = GetTextureForChars( font, type, &wch, textureID, &textureCoords, 1 ); if ( textureCoords ) { texCoords[0] = textureCoords[0]; texCoords[1] = textureCoords[1]; texCoords[2] = textureCoords[2]; texCoords[3] = textureCoords[3]; } return bSuccess; }
c++
9
0.725941
139
30.933333
15
inline
import urllib.request import json import codecs import jmespath import random import ruamel.yaml from string import Template def get_prizes() -> list: total_prizes = int(input("How many prizes: ")) prizes = [] while total_prizes > 0: input_prize = input('Add prize: ') prizes.append(input_prize) total_prizes -= 1 return prizes def get_parameters() -> dict: parameters = {} with open('parameters.yml', 'r') as stream: try: parameters = ruamel.yaml.load(stream) except ruamel.yaml.YAMLError as exc: print(exc) return parameters def get_attendees() -> list: parameters = get_parameters() event_id = input('What\'s the event id?\n') endpoint_template = Template('http://api.meetup.com/$urlname/events/$eventid/rsvps?key=$apikey') endpoint = endpoint_template.substitute( urlname=parameters['url_name'], eventid=event_id, apikey=parameters['api_key'] ) request = urllib.request.Request(endpoint) with urllib.request.urlopen(request) as response: reader = codecs.getreader("utf-8") data = json.load(reader(response)) attendees = [] for attendee_name in jmespath.search('[?response != `no`].[member.name]', data): attendees.append(attendee_name[0]) return attendees def prize_raffle(): attendees = get_attendees() prizes = get_prizes() for i in range(0, len(prizes)): accept = 'no' while accept != 'yes': prize = prizes[i] winner = attendees.pop(random.randint(0, len(attendees) - 1)) print('The winner of ' + prize + ' prize is: ' + winner) accept = input('accept winner? (yes or no)') prize_raffle()
python
16
0.615044
100
25.985075
67
starcoderdata
import React from "react" const Project = ({ title, src, meta, url, srcUrl, app }) => { return ( <div className="project-card"> <img src={src} alt="Project" /> <div className="project-card-info"> <h5 className="project-card-title">{title} <div className="project-card-meta"> {meta.map((m, i) => ( <> <span key={i}>{m} <br /> ))} <div className="project-card-footer"> {url && ( <div className="site"> <a href={url} target="_blank" rel="noopener noreferrer"> {app === true ? "App" : "Site"} )} {srcUrl && ( <div className="source"> <a href={srcUrl} target="_blank" rel="noopener noreferrer"> Source )} ) } export default Project
javascript
18
0.427459
73
25.333333
39
starcoderdata
import os import pandas as pd pathtohere = os.path.abspath(__file__) HERE = os.path.dirname(pathtohere) PREFIX = HERE + '/../DataByEndAirport/' POSTFIX = '.csv' CODES = ['EDDF', 'EGKK', 'EGLL', 'EHAM', 'LEMD', 'LFPG', 'LGAV', 'LIRF'] AIRPORTS = { 'EDDF': 'Frankfurt am Main International Airport', 'EGKK': 'London Gatwick Airport', 'EGLL': 'London Heathrow Airport', 'EGSS': 'London Stansted Airport', 'EGGW': 'London Luton Airport', 'EHAM': 'Amsterdam Airport Schiphol', 'EIDW': 'Dublin Airport', 'LEMD': 'Madrid Barajas International Airport', 'LFPG': 'Charles de Gaulle International Airport', 'LGAV': 'Athens International Airport', 'LIRF': 'Rome Fiumicino International Airport' } TIMEZONES = { 'EDDF': pd.Timedelta(2, 'h'), 'EGKK': pd.Timedelta(1, 'h'), 'EGLL': pd.Timedelta(1, 'h'), 'EGSS': pd.Timedelta(1, 'h'), 'EGGW': pd.Timedelta(1, 'h'), 'EHAM': pd.Timedelta(2, 'h'), # 'EIDW': pd.Timedelta(1, 'h'), 'LEMD': pd.Timedelta(2, 'h'), 'LFPG': pd.Timedelta(2, 'h'), 'LGAV': pd.Timedelta(3, 'h'), 'LIRF': pd.Timedelta(2, 'h') } TZONES = { 'EDDF': 'Europe/Berlin', 'EGKK': 'Europe/London', 'EGLL': 'Europe/London', 'EGSS': 'Europe/London', 'EGGW': 'Europe/London', 'EHAM': 'Europe/Amsterdam', # 'EIDW': 'Europe/Dublin', 'LEMD': 'Europe/Madrid', 'LFPG': 'Europe/Paris', 'LGAV': 'Europe/Athens', 'LIRF': 'Europe/Rome' } # http://www.somersault1824.com/tips-for-designing-scientific-figures-for-color-blind-readers/ COLORS = { 'EDDF': [73, 0, 146], 'EGKK': [0, 73, 73], 'EGLL': [109, 182, 255], 'EGSS': [219, 209, 0], 'EGGW': [182, 219, 255], 'EHAM': [255, 182, 119], 'LEMD': [146, 0, 0], 'LFPG': [146, 73, 0], 'LGAV': [0, 109, 219], 'LIRF': [36, 255, 36], } ALLICAO = AIRPORTS.keys() BEGDT = '2016-06-15 00:00:00' ENDDT = '2016-09-14 23:59:59' CLMNS = ['START', 'END', 'ID', 'M1_FL240', 'M3_FL240'] TIMERESAMPLE = 5
python
8
0.576
94
26.027027
74
starcoderdata
<?php namespace App\Http\Controllers\Client\Main; use App\Http\Controllers\Controller; use App\Http\Requests\Client\OfferRequest; use App\Models\v1\Offer; use Illuminate\Http\Request; class OfferClientController extends Controller { public function store(OfferRequest $request){ $offer = new Offer(); $offer->standart_id = $request['standart_id']; $offer->text= $request['text']; $offer->phone_number = $request['phone_number']; $offer->save(); if ($offer==true){ return redirect()->route('standart1',$request->standart_id); } } }
php
13
0.64791
72
26.043478
23
starcoderdata
function (path) { var data = path ? getPath(this._data, path) : this._data; if (data) { data = clean(data); } // include computed fields if (!path) { var key; for (key in this.$options.computed) { data[key] = clean(this[key]); } if (this._props) { for (key in this._props) { data[key] = clean(this[key]); } } } console.log(data); }
javascript
15
0.465479
62
22.684211
19
inline
#include "viewer.h" #include "staticfunctions.h" #include "messagedisplayer.h" bool MessageDisplayer::renderScene() { return (!m_mesgShowing || m_firstTime); } bool MessageDisplayer::showingMessage() { return m_mesgShowing; } MessageDisplayer::MessageDisplayer(Viewer *viewer) { m_Viewer = viewer; m_message = ""; m_mesgShowing = false; m_firstTime = false; m_mesgShift = 0; m_mesgImage = 0; } MessageDisplayer::~MessageDisplayer() { m_message = ""; m_mesgShowing = false; m_firstTime = false; m_mesgShift = 0; if (m_mesgImage) delete [] m_mesgImage; } void MessageDisplayer::holdMessage(QString mesg, bool warn) { m_message = mesg; m_warning = warn; m_mesgShowing = true; m_firstTime = true; m_mesgShift = 0; emit updateGL(); } void MessageDisplayer::turnOffMessage() { m_mesgShowing = false; m_firstTime = false; m_message = ""; } void MessageDisplayer::renderMessage(QSize isize) { QFont font("Helvetica", 14, QFont::Normal); QFontMetrics fm(font); int mde = fm.descent(); QStringList strlist = m_message.split(". ", QString::SkipEmptyParts); int nlines = strlist.count(); int ht0, ht1, lft; if (m_warning) { float cost = fabs(cos(m_mesgShift*0.1)); float expt; if (m_mesgShift < 50) // expt = 1.0 -> 0.25 expt = 1.0f - 0.015f*m_mesgShift; else if (m_mesgShift < 101) // expt = 0.25 -> 0.0 expt = 0.5f - 0.005f*m_mesgShift; else expt = 0.0; ht0 = isize.height()/2-nlines*fm.height()/2; ht0 -= 200*(cost*expt); ht1 = ht0 + nlines*fm.height(); lft = 5; } else { ht0 = 15; ht1 = ht0 + nlines*fm.height(); float cost = fabs(cos(m_mesgShift*0.4)); float expt; if (m_mesgShift < 20) // expt = 1.0 -> 0.0 expt = 1.0f - 0.05f*m_mesgShift; else expt = 0.0; lft = 5 + 20*(cost*expt); } int maxlen = 0; for (int si=0; si<nlines; si++) { maxlen = qMax(maxlen, fm.width(strlist[si])); } maxlen += lft+20; // show transparent message // darken the image then render the message m_Viewer->startScreenCoordinatesSystem(); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // blend on top glColor4f(0.0f, 0.0f, 0.0f, 0.7f); glBegin(GL_QUADS); glVertex2f(lft-5, ht0-10); glVertex2f(maxlen, ht0-10); glVertex2f(maxlen, ht1+10); glVertex2f(lft-5, ht1+10); glEnd(); if (m_warning) glColor4f(0.9f, 0.7f, 0.7f, 0.9f); else glColor4f(0.7f, 0.87f, 0.9f, 0.9f); glBegin(GL_LINE_STRIP); glVertex2f(lft, ht0-7); glVertex2f(maxlen-5, ht0-7); glVertex2f(maxlen-5, ht1+7); glVertex2f(lft, ht1+7); glVertex2f(lft, ht0-7); glEnd(); int hi = (ht1-ht0)/nlines; float dim = qMin(1.0, m_mesgShift*0.05); for (int si=0; si<nlines; si++) { int ht = ht0 + (si+1)*hi; StaticFunctions::renderText(lft+5, ht, strlist[si], font, Qt::black, Qt::white); } m_Viewer->stopScreenCoordinatesSystem(); if (m_mesgShift <= 100) QTimer::singleShot(5, this, SLOT(refreshGL())); m_mesgShift++; } void MessageDisplayer::refreshGL() { emit updateGL(); } void MessageDisplayer::drawMessage(QSize isize) { if (!m_mesgShowing) return; if (m_firstTime) { // save screen image so that we can render message on top if (m_mesgImage) delete [] m_mesgImage; m_mesgImage = new GLubyte[4*isize.width()* isize.height()]; glFinish(); glReadBuffer(GL_BACK); glReadPixels(0, 0, isize.width(), isize.height(), GL_RGBA, GL_UNSIGNED_BYTE, m_mesgImage); QTimer::singleShot(1000, this, SLOT(turnOffMessage())); m_firstTime = false; } else { // splat the saved image glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, isize.width(), 0, isize.height(), -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRasterPos2i(0,0); glDrawPixels(isize.width(), isize.height(), GL_RGBA, GL_UNSIGNED_BYTE, m_mesgImage); glFlush(); } renderMessage(isize); }
c++
13
0.602723
80
21.385027
187
starcoderdata
var _ = require('underscore'); var WidgetModel = require('./widgets/widget-model'); var CategoryWidgetModel = require('./widgets/category/category-widget-model'); var HistogramWidgetModel = require('./widgets/histogram/histogram-widget-model'); var TimeSeriesWidgetModel = require('./widgets/time-series/time-series-widget-model'); var WIDGETSTYLEPARAMS = { auto_style_allowed: 'autoStyleEnabled' }; // We create an object with options off the attributes var makeWidgetStyleOptions = function (attrs) { return _.reduce(WIDGETSTYLEPARAMS, function (memo, value, key) { if (attrs[key] !== undefined) { memo[value] = attrs[key]; return memo; } }, {}); }; var _checkProperties = function (obj, propertiesArray) { _.each(propertiesArray, function (prop) { if (obj[prop] === undefined) { throw new Error(prop + ' is required'); } }); }; var extendAttrs = function (attrs, state, hasInitialState) { return _.extend(attrs, state, { hasInitialState: hasInitialState }); // Will overwrite preset attributes with the ones passed on the state }; var checkAnalysisModel = function (attrs) { if (!(attrs.source instanceof Object) || !attrs.source.cid) { throw new Error('Source must be defined and be an instance of AnalysisModel.'); } }; /** * Public API to interact with dashboard widgets. */ var WidgetsService = function (widgetsCollection, dataviews) { this._widgetsCollection = widgetsCollection; this._dataviews = dataviews; }; WidgetsService.prototype.getCollection = function () { return this._widgetsCollection; }; WidgetsService.prototype.get = function (id) { return this._widgetsCollection.get(id); }; WidgetsService.prototype.getList = function () { return this._widgetsCollection.models; }; /** * @param {Object} attrs * @param {String} attrs.title Title rendered on the widget view * @param {String} attrs.column Name of column to use to aggregate * @param {String} attrs.aggregation Name of aggregation operation to apply to get categories * can be any of ['sum', 'count']. Default is 'count' * @param {String} attrs.aggregation_column column to be used for the aggregation operation * it only applies for sum operations. * @param {Object} attrs.source Object with the id of the source analysis node that the widget points to * @param {Object} layer Instance of a layer model (cartodb.js) * @return {CategoryWidgetModel} */ WidgetsService.prototype.createCategoryModel = function (attrs, layer, state) { _checkProperties(attrs, ['title']); var extendedAttrs = extendAttrs(attrs, state, this._widgetsCollection.hasInitialState()); checkAnalysisModel(extendedAttrs); var dataviewModel = this._dataviews.createCategoryModel(extendedAttrs); var ATTRS_NAMES = ['id', 'title', 'order', 'collapsed', 'prefix', 'suffix', 'show_stats', 'show_source', 'style', 'hasInitialState']; var widgetAttrs = _.pick(extendedAttrs, ATTRS_NAMES); var options = makeWidgetStyleOptions(extendedAttrs); widgetAttrs.attrsNames = ATTRS_NAMES; var widgetModel = new CategoryWidgetModel(widgetAttrs, { dataviewModel: dataviewModel, layerModel: layer }, options); widgetModel.setInitialState(state); this._widgetsCollection.add(widgetModel); return widgetModel; }; /** * @param {Object} attrs * @param {String} attrs.title Title rendered on the widget view * @param {String} attrs.column Name of column * @param {Number} attrs.bins Count of bins * @param {Object} layer Instance of a layer model (cartodb.js) * @return {WidgetModel} */ WidgetsService.prototype.createHistogramModel = function (attrs, layer, state, opts) { _checkProperties(attrs, ['title']); var extendedAttrs = extendAttrs(attrs, state, this._widgetsCollection.hasInitialState()); checkAnalysisModel(extendedAttrs); var dataviewModel = this._dataviews.createHistogramModel(extendedAttrs); // Default bins attribute was removed from dataViewModel because of time-series aggregation. // Just in case it's needed for histogram models we added it here. if (!dataviewModel.has('bins')) { dataviewModel.set('bins', 10, { silent: true }); } var attrsNames = ['id', 'title', 'order', 'collapsed', 'bins', 'show_stats', 'show_source', 'normalized', 'style', 'hasInitialState', 'table_name']; var widgetAttrs = _.pick(extendedAttrs, attrsNames); var options = makeWidgetStyleOptions(extendedAttrs); widgetAttrs.type = 'histogram'; widgetAttrs.attrsNames = attrsNames; var widgetModel = new HistogramWidgetModel(widgetAttrs, { dataviewModel: dataviewModel, layerModel: layer }, options); widgetModel.setInitialState(state); this._widgetsCollection.add(widgetModel); return widgetModel; }; /** * @param {Object} attrs * @param {String} attrs.title Title rendered on the widget view * @param {String} attrs.column Name of column * @param {String} attrs.operation Name of operation to use, can be any of ['min', 'max', 'avg', 'sum'] * @param {Object} layer Instance of a layer model (cartodb.js) * @return {CategoryWidgetModel} */ WidgetsService.prototype.createFormulaModel = function (attrs, layer, state) { _checkProperties(attrs, ['title']); var extendedAttrs = extendAttrs(attrs, state, this._widgetsCollection.hasInitialState()); checkAnalysisModel(extendedAttrs); var dataviewModel = this._dataviews.createFormulaModel(extendedAttrs); var ATTRS_NAMES = ['id', 'title', 'order', 'collapsed', 'prefix', 'suffix', 'show_stats', 'show_source', 'description', 'hasInitialState']; var widgetAttrs = _.pick(extendedAttrs, ATTRS_NAMES); widgetAttrs.type = 'formula'; widgetAttrs.attrsNames = ATTRS_NAMES; var widgetModel = new WidgetModel(widgetAttrs, { dataviewModel: dataviewModel, layerModel: layer }); widgetModel.setInitialState(state); this._widgetsCollection.add(widgetModel); return widgetModel; }; /** * @param {Object} attrs * @param {String} attrs.column Name of column that contains * @param {Object} layer Instance of a layer model (cartodb.js) * @param {Number} bins * @return {WidgetModel} */ WidgetsService.prototype.createTimeSeriesModel = function (attrs, layer, state, opts) { // TODO will other kind really work for a time-series? attrs.column_type = attrs.column_type || 'date'; checkAnalysisModel(attrs); var dataviewModel = this._dataviews.createHistogramModel(attrs); var ATTRS_NAMES = ['id', 'style', 'title', 'normalized', 'animated', 'timezone']; var widgetAttrs = _.pick(attrs, ATTRS_NAMES); widgetAttrs.type = 'time-series'; widgetAttrs.attrsNames = ATTRS_NAMES; var widgetModel = new TimeSeriesWidgetModel(widgetAttrs, { dataviewModel: dataviewModel, layerModel: layer }, opts); widgetModel.setInitialState(state); this._widgetsCollection.add(widgetModel); return widgetModel; }; WidgetsService.prototype.setWidgetsState = function (state) { this._widgetsCollection.setStates(state); }; module.exports = WidgetsService;
javascript
14
0.727131
150
35.476684
193
starcoderdata
<?php namespace TenantCloud\BetterReflection\Relocated; use TenantCloud\BetterReflection\Relocated\AnotherNamespace\Foo; /** @var int[] $integers */ $integers = \TenantCloud\BetterReflection\Relocated\foos(); foreach ($integers as $integer) { die; }
php
7
0.761719
64
24.6
10
starcoderdata
<? $MESS["GD_BITRIX24"] = "для 12 сотрудников $MESS["GD_BITRIX24_TITLE"] = "Облачный сервис"; $MESS["GD_BITRIX24_BUTTON"] = "Подключить"; $MESS["GD_BITRIX24_LIST"] = "- CRM Управление задачами Корпоративный мессенджер Мобильное приложение"; $MESS["GD_BITRIX24_MORE"] = "и многое другое"; $MESS["GD_BITRIX24_LINK"] = "http://www.bitrix24.ru/?utm_source=BUS_Admin&utm_medium=referral&utm_campaign=BUS_Admin"; ?>
php
5
0.704846
118
55.75
8
starcoderdata