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
import { loadDoc, saveDoc } from '@/control/firebase' export default { namespaced: true, state : { upkey: '', dados: {} }, mutations: { SET_DADOS(state, { key, dados }) { // Vue.set(state.dados, key, dados ) state.dados[key] = dados state.upkey = key } }, actions: { loadData({ commit, dispatch }, { documento }) { // 'cliente/alitec/dados/cadastro' ou até '/cliente/alitec/dados/cadastro/' let path = documento.split('/').filter(e => e) // '[cliente,alitec,dados,cadastro]' let key = path.join('-') // cliente-alitec-dados-cadastro let col = path.slice(0, -1).join('/') // 'cliente/alitec/dados' let doc = path.pop() // 'cadastro' return loadDoc(col, doc) .then(doc => { let dados = doc.data() commit('SET_DADOS', { key, dados }) return dados }) .catch(error => { dispatch( 'snackbar/show', { text: error.message, color: 'error' }, { root: true } ) }) }, saveData({ commit, dispatch }, { documento, dados }) { // 'cliente/alitec/dados/cadastro' ou até '/cliente/alitec/dados/cadastro/' let path = documento.split('/').filter(e => e) // '[cliente,alitec,dados,cadastro]' let key = path.join('-') // cliente-alitec-dados-cadastro let col = path.slice(0, -1).join('/') // 'cliente/alitec/dados' let doc = path.pop() // 'cadastro' return saveDoc(col, doc, dados) .then(data => { commit('SET_DADOS', { key, data }) return data }) .catch(error => { dispatch( 'snackbar/show', { text: error.message, color: 'error' }, { root: true } ) }) } }, getters: { read: state => doc => { // 'cliente/alitec/dados/cadastro' ou até '/cliente/alitec/dados/cadastro/' let path = doc.split('/').filter(e => e) // '[cliente,alitec,dados,cadastro]' // let col = path.slice(0, -1).join('/') // 'cliente/alitec/dados' // let doc = path.pop() // 'cadastro' let key = path.join('-') // cliente-alitec-dados-cadastro return state.dados[key] || {} } }, modules: {} }
javascript
19
0.514238
81
27.771084
83
starcoderdata
# -*- coding: utf-8 -*- """ flaskext.flask-warehouse --------------- A clean abstraction over cloud file storage platforms like S3, Alicloud, or Heroku. :copyright: (c) by :license: MIT license , see LICENSE for more details. """ __author__ = """ __email__ = ' __version__ = '0.1.6' from .flask_warehouse import Warehouse assert(Warehouse)
python
5
0.605991
79
18.727273
22
starcoderdata
<?php /** * @copyright Copyright (C) 2016 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT * @author */ namespace app\components\ability; use Yii; use app\models\Battle; class Effect { public static function factory(Battle $battle) { $gameVersion = $battle->splatoonVersion->tag ?? null; if (!$gameVersion) { return null; } $ns = __NAMESPACE__ . '\effect'; $list = [ '2.9.0' => "{$ns}\\v020900", '2.8.0' => "{$ns}\\v020800", '2.7.0' => "{$ns}\\v020700", '2.6.0' => "{$ns}\\v020600", '2.5.0' => "{$ns}\\v020500", ]; foreach ($list as $classVersion => $className) { if (version_compare($classVersion, $gameVersion, '<=')) { return Yii::createObject([ 'class' => $className, 'battle' => $battle, 'version' => $gameVersion, ]); } } return null; } }
php
16
0.457987
74
25.414634
41
starcoderdata
package tutoraid.logic.commands; import static java.util.Objects.requireNonNull; import static tutoraid.ui.DetailLevel.LOW; import tutoraid.commons.core.Messages; import tutoraid.model.Model; import tutoraid.ui.DetailLevel; /** * Lists all students in TutorAid to the user. */ public class ListCommand extends Command { public static final String COMMAND_WORD = "list"; private final DetailLevel detailLevel; /** * Default constructor that lists students without showing fields. */ public ListCommand() { this.detailLevel = LOW; } /** * Constructor for a list command that lists students. Fields are shown if {@code viewAll} is true. * * @param detailLevel Level of detail for fields to be displayed */ public ListCommand(DetailLevel detailLevel) { this.detailLevel = detailLevel; } @Override public CommandResult execute(Model model) { requireNonNull(model); model.updateFilteredStudentList(Model.PREDICATE_SHOW_ALL_STUDENTS); model.updateFilteredLessonList(Model.PREDICATE_SHOW_ALL_LESSONS); model.viewList(detailLevel); return new CommandResult(Messages.MESSAGE_LIST_SUCCESS); } }
java
9
0.706699
103
27.465116
43
starcoderdata
import click from flask.cli import with_appcontext @click.command('test') @with_appcontext def test(): ''' Run all the tests ''' import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) def test_init_app(app): app.cli.add_command(test)
python
10
0.704268
51
22.428571
14
starcoderdata
using System.Linq; using NetBots.WebModels; namespace NetBots.EngineModels { class GameStateBotletMove { public SpatialGameState State { get; set; } public BotletMove Move { get; set; } public GameStateBotletMove(GameState state, BotletMove move) { State = new SpatialGameState(state); Move = move; } public Space From() { return State.GetSpace(Move.From); } public Space To() { return State.GetSpace(Move.To); } public bool IsContiguous(){ return State.AdjacentSpaces(To()).Contains(From()); } public bool IsValid() { return State.IsInBounds(From()) && State.IsInBounds(To()) && IsContiguous(); } } }
c#
15
0.546229
88
21.216216
37
starcoderdata
/** * Copyright (c) 2015 Ovitas Inc, All rights reserved. */ package me.hzhou.spider.pipeline; import me.hzhou.spider.model.ZhuaMeiImageExtract; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import us.codecraft.webmagic.Task; import us.codecraft.webmagic.pipeline.PageModelPipeline; import java.io.File; import java.io.IOException; import java.net.URL; /** * Description: * * @author hzhou */ public class ZhuaMeiImagePipeline implements PageModelPipeline { private static final Logger log = Logger.getLogger(ZhuaMeiImagePipeline.class); public void process(ZhuaMeiImageExtract imageExtract, Task task) { //log.info(imageExtract); //Image.me.persist(imageExtract); for (String image : imageExtract.getImageUrls()) { image = getUrl(image); log.info(image); try { FileUtils.copyURLToFile(new URL(image), new File("download" + File.separator + System.nanoTime() + ".jpg")); } catch (IOException e) { e.printStackTrace(); } } } private String getUrl(String image) { String newUrl = image.replace(".thumb.jpg", ""); if (!newUrl.startsWith("http")) { newUrl = "http://www.zhuamei5.com/" + newUrl; } return newUrl; } }
java
18
0.644853
124
27.354167
48
starcoderdata
/* * Copyright 2014 Inc. */ package gw.plugin.ij.intentions; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiMatcherImpl; import gw.internal.gosu.parser.Expression; import gw.internal.gosu.parser.expressions.NumericLiteral; import gw.lang.parser.IStatement; import gw.lang.parser.statements.IAssignmentStatement; import gw.lang.parser.statements.IStatementList; import gw.lang.parser.statements.IWhileStatement; import gw.plugin.ij.lang.psi.api.statements.IGosuVariable; import gw.plugin.ij.lang.psi.impl.statements.GosuForEachStatementImpl; import gw.plugin.ij.lang.psi.impl.statements.GosuWhileStatementImpl; import gw.plugin.ij.lang.psi.util.GosuPsiParseUtil; import gw.plugin.ij.util.GosuBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.psi.util.PsiMatchers.hasClass; public class WhileToForFix extends LocalQuickFixAndIntentionActionOnPsiElement { String ident; Expression rhs; private IGosuVariable declarationEqualToZero; private IAssignmentStatement increment; public WhileToForFix(PsiElement whileStmt, String ident, Expression rhs, IGosuVariable declarationEqualToZero, IAssignmentStatement increment) { super(whileStmt); this.ident = ident; this.rhs = rhs; this.declarationEqualToZero = declarationEqualToZero; this.increment = increment; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) { return; } IWhileStatement parsedElement = ((GosuWhileStatementImpl) startElement).getParsedElement(); if (parsedElement == null) { return; } IStatement statement = parsedElement.getStatement(); IStatement[] statements = ((IStatementList) statement).getStatements(); StringBuilder forStmt = new StringBuilder(); forStmt.append("for ("); forStmt.append(ident); forStmt.append(" in 0.."); if(rhs instanceof NumericLiteral) { Object res = rhs.evaluate(); if(res instanceof Integer) { forStmt.append(((Integer)res)-1); } } else { forStmt.append("|" + rhs); } forStmt.append(") {\n"); String indent = getIndet(parsedElement, statements); for (IStatement statement1 : statements) { if (statement1 != increment) { forStmt.append(indent); forStmt.append(statement1.getLocation().getTextFromTokens()); forStmt.append("\n"); } } forStmt.append("}"); PsiElement stub = GosuPsiParseUtil.parseProgramm(forStmt.toString(), startElement, file.getManager(), null); PsiElement newForStmt = new PsiMatcherImpl(stub) .descendant(hasClass(GosuForEachStatementImpl.class)) .getElement(); if (newForStmt != null) { declarationEqualToZero.delete(); startElement.replace(newForStmt); } } private String getIndet(IWhileStatement parsedElement, IStatement[] statements) { int whileColum = parsedElement.getLocation().getColumn(); int column = statements[1].getLocation().getColumn() - whileColum; if(column < 0) { return " "; } StringBuilder out = new StringBuilder(); for(int i = 0; i <= column; i++) { out.append(" "); } return out.toString(); } private void removeVarDecl(PsiElement whileStmt, String ident) { PsiElement prev = whileStmt.getPrevSibling(); while (prev instanceof PsiWhiteSpace) { prev = prev.getPrevSibling(); } if (prev instanceof IGosuVariable && ((IGosuVariable) prev).getName().equals(ident)) { prev.delete(); } } @Override public boolean isAvailable(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { return startElement instanceof GosuWhileStatementImpl; } @NotNull @Override public String getText() { return GosuBundle.message("inspection.while.to.for"); } @NotNull @Override public String getFamilyName() { return GosuBundle.message("inspection.group.name.statement.issues"); } }
java
15
0.708723
201
34.877863
131
starcoderdata
# # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import common import os def port_to_ip_mapping(index): """ A user defined mapping port_id (kni) to ipv4. """ return {"vEth0_{}".format(index): "192.167.10.{}".format(index + 1)} def set_interface_ports(kni_to_deploy): """ Initialize kni ports in kernel. Input: - A dict() with keys as port name and values being the IP address. """ # Iterate over all the kni ports. for kni_port, ip_addr_str in kni_to_deploy.items(): add_dev_command = "ip addr add dev {} {}".format(kni_port, ip_addr_str) ifup_command = "ifconfig {} up".format(kni_port) # Add device and ifup. common.run_local_cmd(add_dev_command) common.run_local_cmd(ifup_command) def setup_virtual_tcp_interface(n_kni_ports=None): """ Initilize all the kni ports required by containers. Input: - The number of kni ports. Each virtual port is a DPDK kernel network interface port for the purposes of providing a TCP stack. A TCP stack is necessary for retransmission functionality. """ # Verify no ports are instantiated. kni_ports_ifconfig = common.get_kni_ports() if len(kni_ports_ifconfig) != 0: print('Non zero KNI ports. Exiting') exit() # Identify the port ids / IP to deploy. port_name_to_ip_map = dict() for i in range(n_kni_ports): port_name_to_ip_map = {**port_name_to_ip_map, **port_to_ip_mapping(i)} # Verify that the ports are unique. if len(port_name_to_ip_map.values()) != len(set(port_name_to_ip_map.values())): print('IP addresses not unique') exit() # Start the ports. set_interface_ports(port_name_to_ip_map)
python
11
0.633607
83
29.886076
79
starcoderdata
<?php namespace App; class Quote { public static $list = [ "Make an empty space in any corner of your mind, and creativity will instantly fill it.", "I am convinced that material things can contribute a lot to making one's life pleasant, but, basically, if you do not have very good friends and relatives who matter to you, life will be really empty and sad and material things cease to be important.", "Thoughts without content are empty, intuitions without concepts are blind.", "I walk slowly into myself, through a forest of empty suits of armor.", "Education's purpose is to replace an empty mind with an open one.", ]; public static function randomize() { $i = self::generateKey(); while(!isset(self::$list[$i])) { $i = self::generateKey(); } echo self::$list[$i]; } public static function generateKey() { return rand(0, count(self::$list)); } } ?>
php
14
0.698936
255
24.432432
37
starcoderdata
ex_tcb * ExExplainTdb::build(ex_globals * glob) { // Allocate and initialize a new explain TCB. ExExplainTcb *explainTcb = new(glob->getSpace()) ExExplainTcb(*this, glob); // initParamsTuple: Allocate the paramsTuple_, the paramsAtp, the // modName_ buffer and the stmtPattern_ buffer. The paramsTuple_ will // hold the result of evaluating the paramsExpr. The modName_ and // stmtPattern_ buffers are used to hold a NULL terminated copy of the // parameters. Also, initialize the paramsTuppDesc_ to point to the // paramsTuple_ and the paramsTupp_ to point to the paramsTuppDesc_. // This is done to create the necessary tuple structure so that the // paramsExpr can be evaluateed. explainTcb->initParamsTuple(getTupleLength(), criDescParams_, getLengthModName(), getLengthStmtPattern()); // add the explain tcb to the scheduler's task list. explainTcb->registerSubtasks(); return (explainTcb); }
c++
9
0.720083
77
37.48
25
inline
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name:SVMachine Description : 支持向量机 Email : Date:2017/12/18 """ import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn.datasets import load_iris from sklearn.svm import SVC sns.set(style='whitegrid') colors = sns.color_palette("Set2", 2) # 数据 iris = load_iris() X, y = iris.data[:100, :2], iris.target[:100] names = iris.target_names[:2] # 模型建立 model = SVC(kernel='linear') # 拟合 model.fit(X, y) print('n support: {}\n{}'.format(model.n_support_, model.support_vectors_)) coef = model.coef_ inter = model.intercept_ x1 = np.linspace(np.min(X[:, 0]), np.max(X[:, 0]), 1000) print(coef, inter) y1 = (-inter - coef[0, 0] * x1) / coef[0, 1] plt.ylim(np.min(X[:, 1]), np.max(X[:, 1])) # 原始数据 for color, species, name in zip(colors, [0, 1], names): plt.scatter(X[y == species, 0], X[y == species, 1], color=color, label=name) plt.legend(loc='best') plt.plot(x1, y1, 'b') plt.show()
python
9
0.622624
80
24.113636
44
starcoderdata
// // Created by CainHsu on 2019/10/19. // #ifndef TEST_205_HPP #define TEST_205_HPP #include #include #include #include "vector" bool isIsomorphic(std::string s, std::string t) { if(s.size() != t.size()) return false; std::unordered_map<char, char> temp; for(int i = 0; i < s.size(); ++i){ auto iter = temp.find(s[i]); // 存在key但映射与原映射不相同则false if(iter != temp.end()) if(temp[s[i]] != t[i]) return false; else continue; // 若不同key的value相同则false for(int j = 0; j < temp.size(); ++j) if(temp[s[j]] == t[i]) return false; temp[s[i]] = t[i]; } return true; } #endif //TEST_205_HPP
c++
14
0.547196
49
19.305556
36
starcoderdata
package com.hubspot.singularity; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import java.util.Objects; @Schema( description = "The number of tasks in each state for a particular request. Cleaning tasks are also included in active (i.e. total task count = active + pending)" ) public class SingularityTaskCounts { private final String requestId; private final int active; private final int pending; private final int cleaning; @JsonCreator public SingularityTaskCounts( @JsonProperty("requestId") String requestId, @JsonProperty("active") int active, @JsonProperty("pending") int pending, @JsonProperty("cleaning") int cleaning ) { this.requestId = requestId; this.active = active; this.pending = pending; this.cleaning = cleaning; } @Schema(description = "Request id") public String getRequestId() { return requestId; } @Schema(description = "The number of actively running tasks") public int getActive() { return active; } @Schema(description = "The number of tasks that have not yet launched") public int getPending() { return pending; } @Schema( description = "The number of tasks in a cleaning state. Note these are also counted under 'active'" ) public int getCleaning() { return cleaning; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SingularityTaskCounts that = (SingularityTaskCounts) o; return ( active == that.active && pending == that.pending && cleaning == that.cleaning && Objects.equals(requestId, that.requestId) ); } @Override public int hashCode() { return Objects.hash(requestId, active, pending, cleaning); } @Override public String toString() { return ( "SingularityTaskCounts{" + "requestId='" + requestId + '\'' + ", active=" + active + ", pending=" + pending + ", cleaning=" + cleaning + '}' ); } }
java
16
0.657859
163
23.538462
91
starcoderdata
#ifndef SYSTEM_MONITOR_CPU_MONITOR_RASPI_CPU_MONITOR_H #define SYSTEM_MONITOR_CPU_MONITOR_RASPI_CPU_MONITOR_H /* * Copyright 2020 Autoware Foundation. All rights reserved. * * 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. */ /** * @file raspi_cpu_monitor.h * @brief Raspberry Pi CPU monitor class */ #include #define raspiUnderVoltageDetected (1 << 0) // 0x00001 #define raspiArmFrequencyCapped (1 << 1) // 0x00002 #define raspiCurrentlyThrottled (1 << 2) // 0x00004 #define raspiSoftTemperatureLimitActive (1 << 3) // 0x00008 #define raspiUnderVoltageHasOccurred (1 << 16) // 0x10000 #define raspiArmFrequencyCappedHasOccurred (1 << 17) // 0x20000 #define raspiThrottlingHasOccurred (1 << 18) // 0x40000 #define raspiSoftTemperatureLimitHasOccurred (1 << 19) // 0x80000 #define raspiThermalThrottlingMask (raspiCurrentlyThrottled | raspiSoftTemperatureLimitActive) #define throttledToString(X) \ (((X)&raspiUnderVoltageDetected) \ ? "Under-voltage detected" \ : ((X)&raspiArmFrequencyCapped) \ ? "Arm frequency capped" \ : ((X)&raspiCurrentlyThrottled) \ ? "Currently throttled" \ : ((X)&raspiSoftTemperatureLimitActive) \ ? "Soft temperature limit active" \ : ((X)&raspiUnderVoltageHasOccurred) \ ? "Under-voltage has occurred" \ : ((X)&raspiArmFrequencyCappedHasOccurred) \ ? "Arm frequency capped has occurred" \ : ((X)&raspiThrottlingHasOccurred) \ ? "Throttling has occurred" \ : ((X)&raspiSoftTemperatureLimitHasOccurred) \ ? "Soft temperature limit has occurred" \ : "UNKNOWN") class CPUMonitor : public CPUMonitorBase { public: /** * @brief constructor * @param [in] nh node handle to access global parameters * @param [in] pnh node handle to access private parameters */ CPUMonitor(const ros::NodeHandle & nh, const ros::NodeHandle & pnh); /** * @brief get names for core temperature files */ void getTempNames(void) override; protected: /** * @brief check CPU thermal throttling * @param [out] stat diagnostic message passed directly to diagnostic publish calls * @note NOLINT syntax is needed since diagnostic_updater asks for a non-const reference * to pass diagnostic message updated in this function to diagnostic publish calls. */ void checkThrottling( diagnostic_updater::DiagnosticStatusWrapper & stat) override; // NOLINT(runtime/references) }; #endif // SYSTEM_MONITOR_CPU_MONITOR_RASPI_CPU_MONITOR_H
c
10
0.590091
100
45.204819
83
starcoderdata
package uk.gov.digital.ho.hocs.audit.application; public enum LogEvent { AUDIT_EVENT_CREATED, AUDIT_RECORD_NOT_FOUND, AUDIT_STARTUP_FAILURE, INVALID_AUDIT_PALOAD_STORED, AUDIT_EVENT_CREATION_FAILED, UNCAUGHT_EXCEPTION, REST_HELPER_GET, INFO_CLIENT_GET_TEAMS_SUCCESS, INFO_CLIENT_GET_ALL_TEAMS_SUCCESS, INFO_CLIENT_GET_TEAM_SUCCESS, INFO_CLIENT_GET_UNITS_SUCCESS, INFO_CLIENT_GET_CASE_TYPES_SUCCESS, INFO_CLIENT_GET_USERS_SUCCESS, INFO_CLIENT_GET_USER_SUCCESS, INFO_CLIENT_GET_EXPORT_FIELDS_SUCCESS, INFO_CLIENT_GET_EXPORT_VIEWS_SUCCESS, INFO_CLIENT_GET_EXPORT_VIEW_SUCCESS, INFO_CLIENT_GET_EXPORT_VIEW_FAILURE, INFO_CLIENT_GET_SOMUTYPE_SUCCESS, CSV_EXPORT_START, CSV_EXPORT_COMPETE, CSV_EXPORT_FAILURE, REFRESH_MATERIALISED_VIEW, CSV_CUSTOM_CONVERTER_FAILURE, INFO_CLIENT_GET_TOPIC_SUCCESS, CASEWORK_CLIENT_GET_CORRESPONDENTS_SUCCESS, CASEWORK_CLIENT_GET_CORRESPONDENTS_FAILURE, CASEWORK_CLIENT_GET_TOPICS_SUCCESS, CASEWORK_CLIENT_GET_TOPICS_FAILURE, CASEWORK_CLIENT_GET_CASE_REFERENCE_SUCCESS, CASEWORK_CLIENT_GET_CASE_REFERENCE_FAILURE; public static final String EVENT = "event_id"; public static final String EXCEPTION = "exception"; }
java
8
0.727843
55
31.692308
39
starcoderdata
<?php if (!PHPFOX_IS_AJAX) { $mRedirectId = Phpfox::getService('subscribe.purchase')->getRedirectId(); if (is_numeric($mRedirectId) && $mRedirectId > 0) { Phpfox::getLib('url')->send('subscribe.register', array('id' => $mRedirectId), Phpfox::getPhrase('subscribe.please_complete_your_purchase')); } } ?>
php
13
0.68323
144
28.363636
11
starcoderdata
/*L * Copyright Northwestern University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.io/psc/LICENSE.txt for details. */ package edu.northwestern.bioinformatics.studycalendar.domain.tools.hibernate; import edu.northwestern.bioinformatics.studycalendar.StudyCalendarError; import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException; import gov.nih.nci.cabig.ctms.lang.ComparisonTools; import org.hibernate.HibernateException; import org.hibernate.usertype.ParameterizedType; import org.hibernate.usertype.UserType; import org.slf4j.Logger; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; /** * A Hibernate UserType for subclasses of {@link edu.northwestern.bioinformatics.studycalendar.domain.AbstractControlledVocabularyObject}. * Required parameter: * * * enumeration class of which this type instance will readAndSave instances * * Optional parameters: * * * public static method to call to obtain an instance of the class from a database key. * Default is * * public method to call on an instance of the class to get the database key under * which it should be stored. Default is * * * @author */ public class ControlledVocabularyObjectType implements UserType, ParameterizedType { protected static final String ENUM_CLASS_PARAM_KEY = "enumClass"; protected static final String FACTORY_METHOD_PARAM_KEY = "factoryMethod"; protected static final String KEY_METHOD_PARAM_KEY = "keyMethod"; private static final String DEFAULT_FACTORY_METHOD_NAME = "getById"; private static final String DEFAULT_KEY_METHOD_NAME = "getId"; private static final Class[] NO_PARAMS = new Class[0]; // private Log log = HibernateTypeUtils.getLog(getClass()); private Logger log = HibernateTypeUtils.getLog(getClass()); private Properties parameterValues; protected final Properties getParameterValues() { return parameterValues; } ////// IMPLEMENTATION of ParameterizedType public void setParameterValues(Properties parameters) { this.parameterValues = new Properties(createDefaults()); if (parameters != null) { this.parameterValues.putAll(parameters); } // call various methods so that they have an opportunity to fail during initialization getEnumClass(); getFactoryMethod(); getKeyMethod(); } private Properties createDefaults() { Properties defaults = new Properties(); defaults.put(FACTORY_METHOD_PARAM_KEY, DEFAULT_FACTORY_METHOD_NAME); defaults.put(KEY_METHOD_PARAM_KEY, DEFAULT_KEY_METHOD_NAME); return defaults; } ////// IMPLEMENTATION OF UserType public final int[] sqlTypes() { return new int[] { Types.INTEGER }; } public Class returnedClass() { return getEnumClass(); } private Class getEnumClass() { if (getEnumClassName() == null) { throw new StudyCalendarError("required enumClass parameter not specified"); } try { return Class.forName(getEnumClassName()); } catch (ClassNotFoundException e) { throw new StudyCalendarError("enumClass " + getEnumClassName() + " does not exist", e); } } private String getEnumClassName() { return getParameterValues().getProperty(ENUM_CLASS_PARAM_KEY); } private Method getFactoryMethod() { return getParameterNamedMethod(FACTORY_METHOD_PARAM_KEY, new Class[] { Integer.TYPE }); } private Method getKeyMethod() { return getParameterNamedMethod(KEY_METHOD_PARAM_KEY, NO_PARAMS); } private Method getParameterNamedMethod(String paramKey, Class[] parameterTypes) { String methodName = getParameterValues().getProperty(paramKey); try { return getEnumClass().getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { throw new StudyCalendarError("enumClass " + getEnumClassName() + " has no method named " + methodName, e); } } protected Object getKeyObject(ResultSet rs, String colname) throws SQLException { return rs.getInt(colname); } public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { Object key = getKeyObject(rs, names[0]); Object value = null; if (key != null) { Method factoryMethod = getFactoryMethod(); try { value = factoryMethod.invoke(null, key); } catch (IllegalArgumentException iae) { throw new StudyCalendarSystemException("Invocation of " + factoryMethod + " with key=" + key + " (" + key.getClass().getName() + ") failed", iae); } catch (IllegalAccessException e) { throw new StudyCalendarSystemException("Cannot access factoryMethod " + factoryMethod, e); } catch (InvocationTargetException e) { throw new StudyCalendarSystemException("Invocation of " + factoryMethod + " failed", e); } } HibernateTypeUtils.logReturn(log, names[0], value); return value; } public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { Method keyMethod = getKeyMethod(); Object key = null; try { if (value != null) { key = keyMethod.invoke(value, new Object[0]); } } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("Could not call keyMethod " + keyMethod + " on value " + value, iae); } catch (IllegalAccessException e) { throw new StudyCalendarSystemException("Cannot access keyMethod " + keyMethod, e); } catch (InvocationTargetException e) { throw new StudyCalendarSystemException("Invocation of " + keyMethod + " failed", e); } HibernateTypeUtils.logBind(log, index, key); st.setObject(index, key, Types.INTEGER); } public Object deepCopy(Object value) throws HibernateException { return value; } public boolean isMutable() { return false; } public boolean equals(Object x, Object y) throws HibernateException { return ComparisonTools.nullSafeEquals(x, y); } public int hashCode(Object x) throws HibernateException { return x == null ? 0 : x.hashCode(); } public Serializable disassemble(Object value) throws HibernateException { return (Serializable) value; } public Object assemble(Serializable cached, Object owner) throws HibernateException { return cached; } public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } }
java
20
0.672472
138
35.745
200
starcoderdata
package com.omnicrola.voxel.debug; import com.jme3.bullet.BulletAppState; import com.jme3.input.controls.ActionListener; import com.omnicrola.voxel.engine.VoxelGameEngine; /** * Created by Eric on 2/5/2016. */ public class DebugPhysicsListener implements ActionListener { private VoxelGameEngine voxelGameEngine; public DebugPhysicsListener(VoxelGameEngine voxelGameEngine) { this.voxelGameEngine = voxelGameEngine; } @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { BulletAppState bulletAppState = this.voxelGameEngine.getStateManager().getState(BulletAppState.class); bulletAppState.setDebugEnabled(!bulletAppState.isDebugEnabled()); } } }
java
13
0.739869
114
30.875
24
starcoderdata
void CPlayerSummaryMgr::HandleLevelEnd(CPlayerObj* pPlayer) { if (!pPlayer) return; UpdateTotalMissionTime(); // Calculate the player's ranking... if (!IsMultiplayerGame()) { CalcPlayerGlobalRank(); WriteRankData(); } Save(g_pLTServer); SendDataToClient(pPlayer->GetClient()); }
c++
8
0.67619
59
15.611111
18
inline
import os import unittest from robot.utils.asserts import assert_equals, assert_true from robot.utils.etreewrapper import ETSource, ET from robot.utils import IRONPYTHON, PY3 PATH = os.path.join(os.path.dirname(__file__), 'test_etreesource.py') if PY3: unicode = str class TestETSource(unittest.TestCase): def test_path_to_file(self): source = ETSource(PATH) with source as src: assert_equals(src, PATH) self._verify_string_representation(source, PATH) assert_true(source._opened is None) def test_opened_file_object(self): source = ETSource(open(PATH)) with source as src: assert_true(src.read().startswith('import os')) assert_true(src.closed is False) self._verify_string_representation(source, PATH) assert_true(source._opened is None) def test_byte_string(self): self._test_string('\n def test_unicode_string(self): self._test_string(u'\n def _test_string(self, xml): source = ETSource(xml) with source as src: content = src.read() if not IRONPYTHON: content = content.decode('UTF-8') assert_equals(content, xml) self._verify_string_representation(source, '<in-memory file>') assert_true(source._opened.closed) with ETSource(xml) as src: assert_equals(ET.parse(src).getroot().tag, 'tag') def test_non_ascii_string_repr(self): self._verify_string_representation(ETSource(u'\xe4'), u'\xe4') def _verify_string_representation(self, source, expected): assert_equals(unicode(source), expected) assert_equals('-%s-' % source, '-%s-' % expected) if __name__ == '__main__': unittest.main()
python
15
0.631777
70
30.576271
59
starcoderdata
<?php namespace Bone\Controller; use Bone\I18n\I18nAwareInterface; use Bone\Server\Traits\HasSiteConfigTrait; use Bone\I18n\Traits\HasTranslatorTrait; use Bone\View\Traits\HasViewTrait; use Bone\View\ViewAwareInterface; use Bone\Server\SiteConfigAwareInterface; use Psr\Http\Message\ResponseInterface; class Controller implements I18nAwareInterface, ViewAwareInterface, SiteConfigAwareInterface { use HasSiteConfigTrait; use HasTranslatorTrait; use HasViewTrait; /** * @param ResponseInterface $response * @param string $layout */ public function responseWithLayout(ResponseInterface $response, string $layout): ResponseInterface { return $response->withHeader('layout', $layout); } }
php
10
0.766216
102
26.407407
27
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MCR.models { public class Student { public string id { get; set; } public string ip { get; set; } public string name { get; set; } public string studentId { get; set; } public DateTime expires { get; set; } public Student() { } public Student(string id, string ip, string name, string studentId) { this.id = id; this.ip = ip; this.name = name; this.studentId = studentId; } public override bool Equals(object obj) { var student = obj as Student; return student != null && ip == student.ip && name == student.name && studentId == student.studentId; } public override int GetHashCode() { var hashCode = 148588527; hashCode = hashCode * -1521134295 + EqualityComparer hashCode = hashCode * -1521134295 + EqualityComparer hashCode = hashCode * -1521134295 + EqualityComparer return hashCode; } public override string ToString() { return String.Format("Id: {0}, Ip: {1}, StudentId: {2}, Name: {3}", id, ip, studentId, name); } public bool expired() { return expires < DateTime.Now; } public bool isValid() { return id != null && ip != null && name != null && studentId != null; } } }
c#
15
0.530968
104
28.114754
61
starcoderdata
import os import math as m from pyfiglet import Figlet from alive_progress import alive_bar import random def defAndClear(): global debugFlag global randomFlag global forceDict global radDict global forceKey global radKey global xDict global yDict global xKey global yKey global forceSum global forceSumAngle global xSum global ySum global xDictValues global yDictValues randomFlag = False debugFlag = False forceDict = {} radDict = {} forceKey = "force{}" radKey = "angle{}" xDict = {} yDict = {} xKey = "x{}" yKey = "y{}" forceSum = 0.0 forceSumAngle = 0.0 xSum = 0.0 ySum = 0.0 xDictValues = {} yDictValues = {} def renderAscii(msg): terminal = os.get_terminal_size() welcome_fig = Figlet( font="kban", justify="left", width=getattr(terminal, "columns") ) print() print(welcome_fig.renderText(msg)) print("By: PEOL0", end="\n\n") print("Remember the math!", end="\n\n") def inputForces(): forces = input("Antal krafter: ").split() if "d" in forces: global debugFlag debugFlag = True if "r" in forces: global randomFlag randomFlag = True if randomFlag == True: with alive_bar(int(forces[0])) as bar: for each in range(int(forces[0])): inputPrompt(each) bar() else: for each in range(int(forces[0])): inputPrompt(each) if debugFlag == True: print(forceDict) print(radDict) def inputPrompt(each): newforce = random.uniform(-100, 100) if randomFlag != True: promt = "Storlek{}: " newforce = float(eval(input(promt.format(each + 1)))) forceDict.update({forceKey.format(each + 1): newforce}) if debugFlag == True: print( "Uppdaterat " + forceKey.format(each + 1) + " med värdet: " + str(newforce) ) newangle = m.radians(random.uniform(0, 360)) if randomFlag != True: prompt = "Vinkel{}: " newangle = m.radians(float(eval(input(prompt.format(each + 1))))) if newangle < 0: newangle = m.radians(360 + m.degrees(newangle)) if newforce < 0: radDict.update({radKey.format(each + 1): newangle + m.radians(180)}) else: radDict.update({radKey.format(each + 1): newangle}) if debugFlag == True: print("Uppdaterat " + radKey.format(each + 1) + " med värdet: " + str(newangle)) def split(): with alive_bar(len(forceDict) * 2) as bar: for each in range(len(forceDict)): forceDictValues = list(forceDict.values()) angleDictValues = list(radDict.values()) xComponentSplit(each, forceDictValues[each], angleDictValues[each]) bar() yComponentSplit(each, forceDictValues[each], angleDictValues[each]) bar() def xComponentSplit(index, force, rad): xComponent = round(abs(force * m.cos(rad)), 12) if m.degrees(rad) > 90 and m.degrees(rad) < 270: xComponent = round(-abs(xComponent), 12) xDict.update({xKey.format(index + 1): xComponent}) if debugFlag == True: print("Uppdaterat " + xKey.format(index) + " med värdet: " + str(xComponent)) def yComponentSplit(index, force, rad): yComponent = round(abs(force * m.sin(rad)), 12) if m.degrees(rad) > 180 and m.degrees(rad) < 360: yComponent = round(-abs(yComponent), 12) yDict.update({yKey.format(index + 1): yComponent}) if debugFlag == True: print("Uppdaterat " + yKey.format(index) + " med värdet: " + str(yComponent)) def method(): method = input("Välj operation: ") if method == "" or method == "+": sumOfForces() def sumOfForces(): global forceSum global xSum global ySum global forceSumAngle xDictValues = list(xDict.values()) yDictValues = list(yDict.values()) xSum = m.fsum(xDictValues) ySum = m.fsum(yDictValues) forceSum = round(m.sqrt((xSum**2) + (ySum**2)), 12) if xSum != 0.0 and ySum != 0.0: forceSumAngle = m.atan(abs(ySum) / abs(xSum)) if xSum < 0 and ySum > 0: forceSumAngle = m.radians(180) - forceSumAngle elif xSum < 0 and ySum < 0: forceSumAngle = m.radians(180) + forceSumAngle elif xSum > 0 and ySum < 0: forceSumAngle = m.radians(360) - forceSumAngle elif xSum == 0.0 and ySum != 0.0: if ySum > 0.0: forceSumAngle = m.radians(90) elif ySum < 0.0: forceSumAngle = m.radians(270) elif ySum == 0.0 and xSum != 0.0: if xSum > 0.0: forceSumAngle = m.radians(0.0) elif xSum < 0.0: forceSumAngle = m.radians(180.0) def presentResults(): print("Summa x: " + str(xSum)) print("Summa y: " + str(ySum)) print("Kraft: " + str(forceSum)) print("Vinkel: " + str(m.degrees(forceSumAngle))) print() renderAscii("Forces") while True: defAndClear() inputForces() split() method() presentResults() if input() == "b": break
python
18
0.584869
88
23.783654
208
starcoderdata
std::vector<MasterTrace> ComputeSessionImpl::GetTraceProtos() { std::vector<MasterTrace> traces; // First compute all possible traces for each component. std::map<string, std::vector<std::vector<ComponentTrace>>> component_traces; std::vector<string> pipeline; for (auto &component_spec : spec_.component()) { pipeline.push_back(component_spec.name()); component_traces.insert( {component_spec.name(), GetComponent(component_spec.name())->GetTraceProtos()}); } // Only output for the actual number of states in each beam. auto final_beam = GetComponent(pipeline.back())->GetBeam(); for (int batch_idx = 0; batch_idx < final_beam.size(); ++batch_idx) { for (int beam_idx = 0; beam_idx < final_beam[batch_idx].size(); ++beam_idx) { std::vector<int> beam_path; beam_path.push_back(beam_idx); // Trace components backwards, finding the source of each state in the // prior component. VLOG(2) << "Start trace: " << beam_idx; for (int i = pipeline.size() - 1; i > 0; --i) { const auto *component = GetComponent(pipeline[i]); int source_beam_idx = component->GetSourceBeamIndex(beam_path.back(), batch_idx); beam_path.push_back(source_beam_idx); VLOG(2) << "Tracing path: " << pipeline[i] << " = " << source_beam_idx; } // Trace the path from the *start* to the end. std::reverse(beam_path.begin(), beam_path.end()); MasterTrace master_trace; for (int i = 0; i < pipeline.size(); ++i) { *master_trace.add_component_trace() = component_traces[pipeline[i]][batch_idx][beam_path[i]]; } traces.push_back(master_trace); } } return traces; }
c++
17
0.603922
79
36.847826
46
inline
package com.brewedbros.app.controllers; import com.brewedbros.app.dtos.UserDto; import com.brewedbros.app.entities.User; import com.brewedbros.app.exceptions.UserNotFoundException; import com.brewedbros.app.security.ApplicationUserDetails; import com.brewedbros.app.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/users") public class UserRestController { @Autowired private UserService service; @GetMapping("/me") public UserDto currentUser(@AuthenticationPrincipal ApplicationUserDetails userDetails) { User user = service.getUser(userDetails.getUserId()) .orElseThrow(() -> new UserNotFoundException(userDetails .getUserId())); return UserDto.fromUser(user); } }
java
14
0.771529
78
38.241379
29
starcoderdata
import json import sys with open(sys.argv[1]) as jsonfile: json = json.load(jsonfile) for key in json: print ("Key", key) if hasattr(json[key], '__iter__'): for elt in json[key]: print (elt) else: print (json[key])
python
10
0.563218
38
19.076923
13
starcoderdata
package org.endeavourhealth.transform.homertonhi.transforms; import com.google.common.base.Strings; import org.endeavourhealth.common.fhir.FhirCodeUri; import org.endeavourhealth.common.fhir.ReferenceHelper; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.common.resourceBuilders.CodeableConceptBuilder; import org.endeavourhealth.transform.common.resourceBuilders.ConditionBuilder; import org.endeavourhealth.transform.homertonhi.HomertonHiCsvHelper; import org.endeavourhealth.transform.homertonhi.schema.Condition; import org.endeavourhealth.transform.homertonhi.schema.ConditionDelete; import org.hl7.fhir.instance.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class ConditionTransformer { private static final Logger LOG = LoggerFactory.getLogger(ConditionTransformer.class); public static void transform(List parsers, FhirResourceFiler fhirResourceFiler, HomertonHiCsvHelper csvHelper) throws Exception { for (ParserI parser: parsers) { if (parser != null) { while (parser.nextRecord()) { if (!csvHelper.processRecordFilteringOnPatientId((AbstractCsvParser) parser)) { continue; } try { transform((Condition) parser, fhirResourceFiler, csvHelper); } catch (Exception ex) { fhirResourceFiler.logTransformRecordError(ex, parser.getCurrentState()); } } } } //call this to abort if we had any errors, during the above processing fhirResourceFiler.failIfAnyErrors(); } public static void delete(List parsers, FhirResourceFiler fhirResourceFiler, HomertonHiCsvHelper csvHelper) throws Exception { for (ParserI parser: parsers) { if (parser != null) { while (parser.nextRecord()) { try { ConditionDelete conditionDeleteParser = (ConditionDelete) parser; CsvCell hashValueCell = conditionDeleteParser.getHashValue(); //lookup the localId value set when the Condition was initially transformed String conditionId = csvHelper.findLocalIdFromHashValue(hashValueCell); if (!Strings.isNullOrEmpty(conditionId)) { //get the resource to perform the deletion on org.hl7.fhir.instance.model.Condition existingCondition = (org.hl7.fhir.instance.model.Condition) csvHelper.retrieveResourceForLocalId(ResourceType.Condition, conditionId); if (existingCondition != null) { ConditionBuilder conditionBuilder = new ConditionBuilder(existingCondition); conditionBuilder.setDeletedAudit(hashValueCell); //delete the condition resource. mapids is always false for deletions fhirResourceFiler.deletePatientResource(parser.getCurrentState(), false, conditionBuilder); } } else { TransformWarnings.log(LOG, parser, "Delete failed. Unable to find Condition HASH_VALUE_TO_LOCAL_ID using hash_value: {}", hashValueCell.toString()); } } catch (Exception ex) { fhirResourceFiler.logTransformRecordError(ex, parser.getCurrentState()); } } } } //call this to abort if we had any errors, during the above processing fhirResourceFiler.failIfAnyErrors(); } public static void transform(Condition parser, FhirResourceFiler fhirResourceFiler, HomertonHiCsvHelper csvHelper) throws Exception { CsvCell conditionIdCell = parser.getConditionId(); ConditionBuilder conditionBuilder = new ConditionBuilder(); conditionBuilder.setId(conditionIdCell.getString(), conditionIdCell); CsvCell personEmpiIdCell = parser.getPersonEmpiId(); Reference patientReference = ReferenceHelper.createReference(ResourceType.Patient, personEmpiIdCell.getString()); conditionBuilder.setPatient(patientReference, personEmpiIdCell); //NOTE:deletions are done using the hash values in the deletion transforms linking back to the local Id //so, save an InternalId link between the hash value and the local Id for this resource, i.e. condition_id CsvCell hashValueCell = parser.getHashValue(); csvHelper.saveHashValueToLocalId(hashValueCell, conditionIdCell); CsvCell confirmationCell = parser.getConditionConfirmationStatusDisplay(); if (!confirmationCell.isEmpty()) { String confirmation = confirmationCell.getString(); if (confirmation.equalsIgnoreCase("confirmed")) { conditionBuilder.setVerificationStatus(org.hl7.fhir.instance.model.Condition.ConditionVerificationStatus.CONFIRMED, confirmationCell); } else { //only interested in Confirmed conditions/problems return; } } else { //only interested in Confirmed conditions/problems return; } CsvCell rankTypeCell = parser.getRankType(); if (!rankTypeCell.isEmpty()) { conditionBuilder.setIsPrimary(rankTypeCell.getString().equalsIgnoreCase("PRIMARY"), rankTypeCell); } //is it a problem or a diagnosis? Homerton send the type using a specific code CsvCell conditionTypeCodeCell = parser.getConditionTypeCode(); if (conditionTypeCodeCell.getString().equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_CONDITION_PROBLEM)) { conditionBuilder.setAsProblem(true); conditionBuilder.setCategory("complaint", conditionTypeCodeCell); CsvCell problemStatusDisplayCell = parser.getProblemStatusDisplay(); String problemStatus = problemStatusDisplayCell.getString(); if (problemStatus.equalsIgnoreCase("active")) { conditionBuilder.setEndDateOrBoolean(null, problemStatusDisplayCell); } else if (problemStatus.equalsIgnoreCase("resolved") || problemStatus.equalsIgnoreCase("inactive") || problemStatus.equalsIgnoreCase("cancelled")) { //Status date confirmed as problem changed to Resolved/Inactive date for example CsvCell statusDateTimeCell = parser.getProblemStatusDtm(); if (!statusDateTimeCell.isEmpty()) { DateType dt = new DateType(statusDateTimeCell.getDateTime()); conditionBuilder.setEndDateOrBoolean(dt, problemStatusDisplayCell, statusDateTimeCell); } else { //if we don't have a status date, use a boolean to indicate the end conditionBuilder.setEndDateOrBoolean(new BooleanType(true), problemStatusDisplayCell); } } } else if (conditionTypeCodeCell.getString().equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_CONDITION_DIAGNOSIS)) { conditionBuilder.setAsProblem(false); conditionBuilder.setCategory("diagnosis", conditionTypeCodeCell); //an active Diagnosis conditionBuilder.setEndDateOrBoolean(null); } else { //catch any unknown condition types throw new TransformException("Unknown Condition type [" + conditionTypeCodeCell.getString() + "]"); } CsvCell encounterIdCell = parser.getEncounterId(); if (!encounterIdCell.isEmpty()) { Reference encounterReference = ReferenceHelper.createReference(ResourceType.Encounter, encounterIdCell.getString()); conditionBuilder.setEncounter(encounterReference, encounterIdCell); } CsvCell effectiveDateTimeCell = parser.getEffectiveDtm(); if (!effectiveDateTimeCell.isEmpty()) { DateTimeType dateTimeType = new DateTimeType(effectiveDateTimeCell.getDateTime()); conditionBuilder.setOnset(dateTimeType, effectiveDateTimeCell); } // Conditions are coded either as Snomed, ICD10 or occasionally Patient Care(PTCARE) or Cerner CsvCell conditionRawCodeCell = parser.getConditionRawCode(); if (!conditionRawCodeCell.isEmpty()) { CodeableConceptBuilder codeableConceptBuilder = new CodeableConceptBuilder(conditionBuilder, CodeableConceptBuilder.Tag.Condition_Main_Code); //check for code system first, then raw code system if blank CsvCell conditionCodeSystemCell = parser.getConditionCodingSystemId(); CsvCell conditionRawCodeSystemCell = parser.getConditionRawCodingSystemId(); if (!conditionCodeSystemCell.isEmpty()) { String conceptCodeSystem = conditionCodeSystemCell.getString(); if (conceptCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_SNOMED_URN) || conceptCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_SNOMED_CT_URN)) { codeableConceptBuilder.addCoding(FhirCodeUri.CODE_SYSTEM_SNOMED_CT, conditionCodeSystemCell); String conditionCode = conditionRawCodeCell.getString(); codeableConceptBuilder.setCodingCode(conditionCode, conditionRawCodeCell); CsvCell conditionCodeDisplayCell = parser.getConditionDisplay(); codeableConceptBuilder.setCodingDisplay(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); codeableConceptBuilder.setText(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); } else if (conceptCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_ICD10_URN) || conceptCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_ICD10_CM_URN)) { codeableConceptBuilder.addCoding(FhirCodeUri.CODE_SYSTEM_ICD10, conditionCodeSystemCell); String conditionCode = conditionRawCodeCell.getString(); codeableConceptBuilder.setCodingCode(conditionCode, conditionRawCodeCell); CsvCell conditionCodeDisplayCell = parser.getConditionDisplay(); codeableConceptBuilder.setCodingDisplay(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); codeableConceptBuilder.setText(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); } else if (conceptCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_CERNER_APRDRG)) { //unknown code types checked, set as free text CsvCell conditionCodeDisplayCell = parser.getConditionDisplay(); codeableConceptBuilder.setText(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); } else { throw new TransformException( "Unknown Condition code system [" + conceptCodeSystem + "] for code value [" + conditionRawCodeCell.getString()+"] with term [" + parser.getConditionDisplay().getString()+"]"); } } else if (!conditionRawCodeSystemCell.isEmpty()) { String conceptRawCodeSystem = conditionRawCodeSystemCell.getString(); if (conceptRawCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_PTCARE_URN)) { codeableConceptBuilder.addCoding(FhirCodeUri.CODE_SYSTEM_PATIENT_CARE, conditionRawCodeSystemCell); String conditionCode = conditionRawCodeCell.getString(); codeableConceptBuilder.setCodingCode(conditionCode, conditionRawCodeCell); CsvCell conditionCodeDisplayCell = parser.getConditionDisplay(); codeableConceptBuilder.setCodingDisplay(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); codeableConceptBuilder.setText(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); } else if (conceptRawCodeSystem.equalsIgnoreCase(HomertonHiCsvHelper.CODE_TYPE_CERNER_URN)) { codeableConceptBuilder.addCoding(FhirCodeUri.CODE_SYSTEM_BARTS_CERNER_CODE_ID, conditionRawCodeSystemCell); String conditionCode = conditionRawCodeCell.getString(); codeableConceptBuilder.setCodingCode(conditionCode, conditionRawCodeCell); CsvCell conditionCodeDisplayCell = parser.getConditionDisplay(); codeableConceptBuilder.setCodingDisplay(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); codeableConceptBuilder.setText(conditionCodeDisplayCell.getString(), conditionCodeDisplayCell); } else { throw new TransformException( "Unknown Condition raw code system [" + conceptRawCodeSystem + "] for code value [" + conditionRawCodeCell.getString() + "] with term [" + parser.getConditionDisplay().getString() + "]"); } } } else { //if there's no code, create a non coded code so we retain the text from the non code element CsvCell termCell = parser.getConditionDescription(); CodeableConceptBuilder codeableConceptBuilder = new CodeableConceptBuilder(conditionBuilder, CodeableConceptBuilder.Tag.Condition_Main_Code); codeableConceptBuilder.setText(termCell.getString(), termCell); } fhirResourceFiler.savePatientResource(parser.getCurrentState(), conditionBuilder); } }
java
23
0.644908
152
51.51087
276
starcoderdata
import { get, writable } from '../dist'; import test from 'ava'; test('Runs start function when going from 0 to 1 subscribers', t => { let count = 0; const store = writable({}, () => void (count += 1)); store.set({}); store.update(() => []); t.is(count, 0); const unsub1 = store.subscribe(() => {}); t.is(count, 1); const unsub2 = store.subscribe(() => {}); t.is(count, 1); unsub1(); unsub2(); t.is(count, 1); store.subscribe(() => {}); t.is(count, 2); }); test('Runs stop function when going from 1 to 0 subscribers', t => { let count = 0; const store = writable({}, () => { count += 1; return () => (count -= 1); }); const unsub = store.subscribe(() => {}); t.is(count, 1); unsub(); t.is(count, 0); }); test('.set() :: Replaces value', t => { const store = writable({}); const a = get(store); store.set({}); const b = get(store); t.not(a, b); }); test('.update() :: Replaces value with result of updater function', t => { const store = writable({}); const a = get(store); store.update(() => ({})); const b = get(store); t.not(a, b); }); test('.subscribe() :: Registers a subscription that runs when the value changes', t => { let count = 0; const store = writable({}); store.subscribe(() => void (count += 1)); t.is(count, 1); store.set({}); t.is(count, 2); }); test('.subscribe() :: Returns an unsubscribe function to remove subscriber', t => { let count = 0; const store = writable({}); const unsub = store.subscribe(() => void (count += 1)); store.set({}); t.is(count, 2); unsub(); store.set({}); t.is(count, 2); });
javascript
16
0.556238
88
22.926471
68
starcoderdata
/* * Name: * CS 2400 Fall 2018 Project 3 */ /* * An interface for ADT Tree */ public interface TreeInterface { public T getRootData(); public int getHeight(); public int getNumberOfNodes(); public boolean isEmpty(); public void clear(); } // end TreeInterface
java
5
0.601881
34
11.291667
24
starcoderdata
#!/usr/bin/python # -*- coding: utf-8 -*- #controller.py import copy, datetime, multiprocessing import dataListener, strategyActuator from DataApi_32 import CDataProcess #载入策略 import signalStrategy, multipleStrategy #----------------------- #定义全局变量 #----------------------- #数据监听对象 g_listenerList = [] #总共3个对象 #策略执行器对象列表 g_StrategyActuatorDict = {} #每个股票一个对象 #订阅股票列表 g_subStocks = [] #----------------------- #注册策略 #----------------------- #单只股票策略对象池 g_SSDict = {} g_SSDict["baseSignal"] = signalStrategy.CBaseSignal #多只股票策略对象池 g_MSDict = {} g_MSDict["baseMultiple"] = multipleStrategy.CBaseMultiple #----------------------- #实现函数 #----------------------- #读取设置参数 execfile("config.ini") #读取订阅股票 def loadSubStocks(): global g_subStocks _fileReader = open("./subStock.csv","r") while 1: line = _fileReader.readline() line = line.replace("\n","") if not line: break g_subStocks.append(line) #创建策略对象 def creatStrategyObject(needSignal, stock): strategyObjDict = {} if needSignal: #单信号策略 if not SUB_SIGNALS: #如果没有订阅 return False for signalName in SUB_SIGNALS: strategyObjDict[signalName] = g_SSDict[signalName](stock) return strategyObjDict else: #多信号策略 if not SUB_MULTIPLES: #如果没有订阅 return False for multipeName in SUB_MULTIPLES: strategyObjDict[multipeName] = g_MSDict[multipeName]("Multiple") strategyObjDict[multipeName].getActuatorDict(g_StrategyActuatorDict) return strategyObjDict #创建监听对象 def creatListener(bufferStack): global g_listenerList listenersNum = 1 if len(g_subStocks) >= listenersNum: perListenerStocksNum = len(g_subStocks)/listenersNum for i in xrange(listenersNum): if listenersNum - i == 1: actuatorDict = creatActuators(g_subStocks[i*perListenerStocksNum:], bufferStack, True) listener = dataListener.CDataListerner(g_subStocks[i*perListenerStocksNum:], actuatorDict, bufferStack) listener.start() else: actuatorDict = creatActuators(g_subStocks[i*perListenerStocksNum:i*perListenerStocksNum+perListenerStocksNum], bufferStack, False) listener = dataListener.CDataListerner(g_subStocks[i*perListenerStocksNum:i*perListenerStocksNum+perListenerStocksNum], actuatorDict, bufferStack) listener.start() g_listenerList.append(listener) else: actuatorDict = creatActuators(g_subStocks, bufferStack, True) listener = dataListener.CDataListerner(g_subStocks, actuatorDict, bufferStack) listener.start() g_listenerList.append(listener) #创建监听对象 def creatActuators(stocks, bufferStack, isLast): global g_StrategyActuatorDict actuatorDict = {} #单股票策略监听 for stock in stocks: strategyObjDict = creatStrategyObject(True, stock) if strategyObjDict: newActuator = strategyActuator.CStrategyActuator(bufferStack[stock]) newActuator.getSignalStrategyObj(strategyObjDict) g_StrategyActuatorDict[stock] = newActuator actuatorDict[stock] = newActuator if isLast: #多股票策略监听 strategyObjDict = creatStrategyObject(False, "Multiple") if strategyObjDict: newActuator = strategyActuator.CStrategyActuator(bufferStack["Multiple"]) newActuator.getmultipleStrategyObj(strategyObjDict) g_StrategyActuatorDict["Multiple"] = newActuator actuatorDict["Multiple"] = newActuator return actuatorDict #主入口 def main(): #注册策略 #载入订阅股票代码 loadSubStocks() #创建数据连接对象 dataServerInstance = CDataProcess( HOST,PORT, SUB_ALL_STOCK, g_subStocks, REQUEST_TYPE, REQUEST_FLAG, datetime.datetime.strptime(START_TIME,"%Y-%m-%d %H:%M:%S"), datetime.datetime.strptime(END_TIME,"%Y-%m-%d %H:%M:%S")) #创建数据监听器 creatListener(dataServerInstance.bufferStack) dataServerInstance.run()
python
18
0.732281
150
30.692982
114
starcoderdata
/* * Copyright (c) 2017 MediaTek Inc. * Author: Kevin Chen <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _DT_BINDINGS_CLK_MT6797_H #define _DT_BINDINGS_CLK_MT6797_H /* TOPCKGEN */ #define CLK_TOP_MUX_ULPOSC_AXI_CK_MUX_PRE 1 #define CLK_TOP_MUX_ULPOSC_AXI_CK_MUX 2 #define CLK_TOP_MUX_AXI 3 #define CLK_TOP_MUX_MEM 4 #define CLK_TOP_MUX_DDRPHYCFG 5 #define CLK_TOP_MUX_MM 6 #define CLK_TOP_MUX_PWM 7 #define CLK_TOP_MUX_VDEC 8 #define CLK_TOP_MUX_VENC 9 #define CLK_TOP_MUX_MFG 10 #define CLK_TOP_MUX_CAMTG 11 #define CLK_TOP_MUX_UART 12 #define CLK_TOP_MUX_SPI 13 #define CLK_TOP_MUX_ULPOSC_SPI_CK_MUX 14 #define CLK_TOP_MUX_USB20 15 #define CLK_TOP_MUX_MSDC50_0_HCLK 16 #define CLK_TOP_MUX_MSDC50_0 17 #define CLK_TOP_MUX_MSDC30_1 18 #define CLK_TOP_MUX_MSDC30_2 19 #define CLK_TOP_MUX_AUDIO 20 #define CLK_TOP_MUX_AUD_INTBUS 21 #define CLK_TOP_MUX_PMICSPI 22 #define CLK_TOP_MUX_SCP 23 #define CLK_TOP_MUX_ATB 24 #define CLK_TOP_MUX_MJC 25 #define CLK_TOP_MUX_DPI0 26 #define CLK_TOP_MUX_AUD_1 27 #define CLK_TOP_MUX_AUD_2 28 #define CLK_TOP_MUX_SSUSB_TOP_SYS 29 #define CLK_TOP_MUX_SPM 30 #define CLK_TOP_MUX_BSI_SPI 31 #define CLK_TOP_MUX_AUDIO_H 32 #define CLK_TOP_MUX_ANC_MD32 33 #define CLK_TOP_MUX_MFG_52M 34 #define CLK_TOP_SYSPLL_CK 35 #define CLK_TOP_SYSPLL_D2 36 #define CLK_TOP_SYSPLL1_D2 37 #define CLK_TOP_SYSPLL1_D4 38 #define CLK_TOP_SYSPLL1_D8 39 #define CLK_TOP_SYSPLL1_D16 40 #define CLK_TOP_SYSPLL_D3 41 #define CLK_TOP_SYSPLL_D3_D3 42 #define CLK_TOP_SYSPLL2_D2 43 #define CLK_TOP_SYSPLL2_D4 44 #define CLK_TOP_SYSPLL2_D8 45 #define CLK_TOP_SYSPLL_D5 46 #define CLK_TOP_SYSPLL3_D2 47 #define CLK_TOP_SYSPLL3_D4 48 #define CLK_TOP_SYSPLL_D7 49 #define CLK_TOP_SYSPLL4_D2 50 #define CLK_TOP_SYSPLL4_D4 51 #define CLK_TOP_UNIVPLL_CK 52 #define CLK_TOP_UNIVPLL_D7 53 #define CLK_TOP_UNIVPLL_D26 54 #define CLK_TOP_SSUSB_PHY_48M_CK 55 #define CLK_TOP_USB_PHY48M_CK 56 #define CLK_TOP_UNIVPLL_D2 57 #define CLK_TOP_UNIVPLL1_D2 58 #define CLK_TOP_UNIVPLL1_D4 59 #define CLK_TOP_UNIVPLL1_D8 60 #define CLK_TOP_UNIVPLL_D3 61 #define CLK_TOP_UNIVPLL2_D2 62 #define CLK_TOP_UNIVPLL2_D4 63 #define CLK_TOP_UNIVPLL2_D8 64 #define CLK_TOP_UNIVPLL_D5 65 #define CLK_TOP_UNIVPLL3_D2 66 #define CLK_TOP_UNIVPLL3_D4 67 #define CLK_TOP_UNIVPLL3_D8 68 #define CLK_TOP_ULPOSC_CK_ORG 69 #define CLK_TOP_ULPOSC_CK 70 #define CLK_TOP_ULPOSC_D2 71 #define CLK_TOP_ULPOSC_D3 72 #define CLK_TOP_ULPOSC_D4 73 #define CLK_TOP_ULPOSC_D8 74 #define CLK_TOP_ULPOSC_D10 75 #define CLK_TOP_APLL1_CK 76 #define CLK_TOP_APLL2_CK 77 #define CLK_TOP_MFGPLL_CK 78 #define CLK_TOP_MFGPLL_D2 79 #define CLK_TOP_IMGPLL_CK 80 #define CLK_TOP_IMGPLL_D2 81 #define CLK_TOP_IMGPLL_D4 82 #define CLK_TOP_CODECPLL_CK 83 #define CLK_TOP_CODECPLL_D2 84 #define CLK_TOP_VDECPLL_CK 85 #define CLK_TOP_TVDPLL_CK 86 #define CLK_TOP_TVDPLL_D2 87 #define CLK_TOP_TVDPLL_D4 88 #define CLK_TOP_TVDPLL_D8 89 #define CLK_TOP_TVDPLL_D16 90 #define CLK_TOP_MSDCPLL_CK 91 #define CLK_TOP_MSDCPLL_D2 92 #define CLK_TOP_MSDCPLL_D4 93 #define CLK_TOP_MSDCPLL_D8 94 #define CLK_TOP_NR 95 /* APMIXED_SYS */ #define CLK_APMIXED_MAINPLL 1 #define CLK_APMIXED_UNIVPLL 2 #define CLK_APMIXED_MFGPLL 3 #define CLK_APMIXED_MSDCPLL 4 #define CLK_APMIXED_IMGPLL 5 #define CLK_APMIXED_TVDPLL 6 #define CLK_APMIXED_CODECPLL 7 #define CLK_APMIXED_VDECPLL 8 #define CLK_APMIXED_APLL1 9 #define CLK_APMIXED_APLL2 10 #define CLK_APMIXED_NR 11 /* INFRA_SYS */ #define CLK_INFRA_PMIC_TMR 1 #define CLK_INFRA_PMIC_AP 2 #define CLK_INFRA_PMIC_MD 3 #define CLK_INFRA_PMIC_CONN 4 #define CLK_INFRA_SCP 5 #define CLK_INFRA_SEJ 6 #define CLK_INFRA_APXGPT 7 #define CLK_INFRA_SEJ_13M 8 #define CLK_INFRA_ICUSB 9 #define CLK_INFRA_GCE 10 #define CLK_INFRA_THERM 11 #define CLK_INFRA_I2C0 12 #define CLK_INFRA_I2C1 13 #define CLK_INFRA_I2C2 14 #define CLK_INFRA_I2C3 15 #define CLK_INFRA_PWM_HCLK 16 #define CLK_INFRA_PWM1 17 #define CLK_INFRA_PWM2 18 #define CLK_INFRA_PWM3 19 #define CLK_INFRA_PWM4 20 #define CLK_INFRA_PWM 21 #define CLK_INFRA_UART0 22 #define CLK_INFRA_UART1 23 #define CLK_INFRA_UART2 24 #define CLK_INFRA_UART3 25 #define CLK_INFRA_MD2MD_CCIF_0 26 #define CLK_INFRA_MD2MD_CCIF_1 27 #define CLK_INFRA_MD2MD_CCIF_2 28 #define CLK_INFRA_FHCTL 29 #define CLK_INFRA_BTIF 30 #define CLK_INFRA_MD2MD_CCIF_3 31 #define CLK_INFRA_SPI 32 #define CLK_INFRA_MSDC0 33 #define CLK_INFRA_MD2MD_CCIF_4 34 #define CLK_INFRA_MSDC1 35 #define CLK_INFRA_MSDC2 36 #define CLK_INFRA_MD2MD_CCIF_5 37 #define CLK_INFRA_GCPU 38 #define CLK_INFRA_TRNG 39 #define CLK_INFRA_AUXADC 40 #define CLK_INFRA_CPUM 41 #define CLK_INFRA_AP_C2K_CCIF_0 42 #define CLK_INFRA_AP_C2K_CCIF_1 43 #define CLK_INFRA_CLDMA 44 #define CLK_INFRA_DISP_PWM 45 #define CLK_INFRA_AP_DMA 46 #define CLK_INFRA_DEVICE_APC 47 #define CLK_INFRA_L2C_SRAM 48 #define CLK_INFRA_CCIF_AP 49 #define CLK_INFRA_AUDIO 50 #define CLK_INFRA_CCIF_MD 51 #define CLK_INFRA_DRAMC_F26M 52 #define CLK_INFRA_I2C4 53 #define CLK_INFRA_I2C_APPM 54 #define CLK_INFRA_I2C_GPUPM 55 #define CLK_INFRA_I2C2_IMM 56 #define CLK_INFRA_I2C2_ARB 57 #define CLK_INFRA_I2C3_IMM 58 #define CLK_INFRA_I2C3_ARB 59 #define CLK_INFRA_I2C5 60 #define CLK_INFRA_SYS_CIRQ 61 #define CLK_INFRA_SPI1 62 #define CLK_INFRA_DRAMC_B_F26M 63 #define CLK_INFRA_ANC_MD32 64 #define CLK_INFRA_ANC_MD32_32K 65 #define CLK_INFRA_DVFS_SPM1 66 #define CLK_INFRA_AES_TOP0 67 #define CLK_INFRA_AES_TOP1 68 #define CLK_INFRA_SSUSB_BUS 69 #define CLK_INFRA_SPI2 70 #define CLK_INFRA_SPI3 71 #define CLK_INFRA_SPI4 72 #define CLK_INFRA_SPI5 73 #define CLK_INFRA_IRTX 74 #define CLK_INFRA_SSUSB_SYS 75 #define CLK_INFRA_SSUSB_REF 76 #define CLK_INFRA_AUDIO_26M 77 #define CLK_INFRA_AUDIO_26M_PAD_TOP 78 #define CLK_INFRA_MODEM_TEMP_SHARE 79 #define CLK_INFRA_VAD_WRAP_SOC 80 #define CLK_INFRA_DRAMC_CONF 81 #define CLK_INFRA_DRAMC_B_CONF 82 #define CLK_INFRA_MFG_VCG 83 #define CLK_INFRA_13M 84 #define CLK_INFRA_NR 85 /* IMG_SYS */ #define CLK_IMG_FDVT 1 #define CLK_IMG_DPE 2 #define CLK_IMG_DIP 3 #define CLK_IMG_LARB6 4 #define CLK_IMG_NR 5 /* MM_SYS */ #define CLK_MM_SMI_COMMON 1 #define CLK_MM_SMI_LARB0 2 #define CLK_MM_SMI_LARB5 3 #define CLK_MM_CAM_MDP 4 #define CLK_MM_MDP_RDMA0 5 #define CLK_MM_MDP_RDMA1 6 #define CLK_MM_MDP_RSZ0 7 #define CLK_MM_MDP_RSZ1 8 #define CLK_MM_MDP_RSZ2 9 #define CLK_MM_MDP_TDSHP 10 #define CLK_MM_MDP_COLOR 11 #define CLK_MM_MDP_WDMA 12 #define CLK_MM_MDP_WROT0 13 #define CLK_MM_MDP_WROT1 14 #define CLK_MM_FAKE_ENG 15 #define CLK_MM_DISP_OVL0 16 #define CLK_MM_DISP_OVL1 17 #define CLK_MM_DISP_OVL0_2L 18 #define CLK_MM_DISP_OVL1_2L 19 #define CLK_MM_DISP_RDMA0 20 #define CLK_MM_DISP_RDMA1 21 #define CLK_MM_DISP_WDMA0 22 #define CLK_MM_DISP_WDMA1 23 #define CLK_MM_DISP_COLOR 24 #define CLK_MM_DISP_CCORR 25 #define CLK_MM_DISP_AAL 26 #define CLK_MM_DISP_GAMMA 27 #define CLK_MM_DISP_OD 28 #define CLK_MM_DISP_DITHER 29 #define CLK_MM_DISP_UFOE 30 #define CLK_MM_DISP_DSC 31 #define CLK_MM_DISP_SPLIT 32 #define CLK_MM_DSI0_MM_CLOCK 33 #define CLK_MM_DSI1_MM_CLOCK 34 #define CLK_MM_DPI_MM_CLOCK 35 #define CLK_MM_DPI_INTERFACE_CLOCK 36 #define CLK_MM_LARB4_AXI_ASIF_MM_CLOCK 37 #define CLK_MM_LARB4_AXI_ASIF_MJC_CLOCK 38 #define CLK_MM_DISP_OVL0_MOUT_CLOCK 39 #define CLK_MM_FAKE_ENG2 40 #define CLK_MM_DSI0_INTERFACE_CLOCK 41 #define CLK_MM_DSI1_INTERFACE_CLOCK 42 #define CLK_MM_NR 43 /* VDEC_SYS */ #define CLK_VDEC_CKEN_ENG 1 #define CLK_VDEC_ACTIVE 2 #define CLK_VDEC_CKEN 3 #define CLK_VDEC_LARB1_CKEN 4 #define CLK_VDEC_NR 5 /* VENC_SYS */ #define CLK_VENC_0 1 #define CLK_VENC_1 2 #define CLK_VENC_2 3 #define CLK_VENC_3 4 #define CLK_VENC_NR 5 #endif /* _DT_BINDINGS_CLK_MT6797_H */
c
3
0.705759
71
29.52669
281
research_code
// Do not remove the include below #include "RemoteControlTransmiter.h" #include #include #include #include #include "Signal.h" #include "StandardCplusplus.h" #include LiquidCrystal_I2C lcd(0x27, 16, 2); Signal a = Signal(A0); Signal b = Signal(A1); Signal c = Signal(A2); Signal d = Signal(A3); Button button1 = Button(9, PULLUP); Button button2 = Button(7, PULLUP); Button button3 = Button(5, PULLUP); const int led_pin = 11; const int transmit_pin = 10; const int receive_pin = 2; const int transmit_en_pin = 3; void setup() { lcd.init(); lcd.backlight(); Serial.begin(9600); vw_set_tx_pin(transmit_pin); vw_set_rx_pin(receive_pin); vw_set_ptt_pin(transmit_en_pin); vw_set_ptt_inverted(true); // Required for DR3100 vw_setup(8000); // Bits per sec } void disply() { lcd.clear(); lcd.setCursor(0, 0); lcd.print(a.getTiltRod()); lcd.setCursor(4, 0); lcd.print(":"); lcd.print(b.getTiltRod()); lcd.setCursor(10, 0); lcd.print("A:"); lcd.print(button1.isPressed()); lcd.setCursor(0, 1); lcd.print(c.getTiltRod()); lcd.setCursor(4, 1); lcd.print(":"); lcd.print(d.getTiltRod()); lcd.setCursor(10, 1); lcd.print("B:"); lcd.print(!button2.isPressed()); lcd.print("C:"); lcd.print(button3.isPressed()); } void send(std::vector signals) { std::string str; for (unsigned int i = 0; i < signals.size(); i++) { str += RemoteControl::transformSignalToString(signals[i]).c_str(); } vw_send((uint8_t*) str.c_str(), str.length()); vw_wait_tx(); } unsigned long previousMillis = 0; const long interval = 125; unsigned long int timestamp = 0; int8_t lastValues[4]; void loop() { if (button1.isPressed()) { Signal::setCalibrationOn(); } else { Signal::setCalibrationOff(); } a.read(); b.read(); c.read(); d.read(); std::vector signals; signals.push_back( { 0, a.getTiltRod() }); signals.push_back( { 1, b.getTiltRod() }); signals.push_back( { 2, c.getTiltRod() }); signals.push_back( { 3, d.getTiltRod() }); send(signals); unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; disply(); timestamp = micros(); } }
c++
13
0.668248
68
20.462963
108
starcoderdata
package org.prebid.server.bidder.adform; import com.iab.openrtb.request.Regs; import org.junit.Before; import org.junit.Test; import org.prebid.server.VertxTest; import org.prebid.server.proto.openrtb.ext.request.ExtRegs; import org.prebid.server.proto.openrtb.ext.request.ExtUser; import static org.assertj.core.api.Assertions.assertThat; public class AdformRequestUtilTest extends VertxTest { private AdformRequestUtil requestUtil; @Before public void setUp() { requestUtil = new AdformRequestUtil(); } @Test public void getGdprAppliesShouldReturnEmptyValueWhenRegsIsNull() { // given and when final String gdpr = requestUtil.getGdprApplies(null); // then assertThat(gdpr).isEmpty(); } @Test public void getGdprAppliesShouldReturnEmptyValueWhenRegsExtIsNull() { // given and when final String gdpr = requestUtil.getGdprApplies(Regs.of(null, null)); // then assertThat(gdpr).isEmpty(); } @Test public void getGdprAppliesShouldReturnEmptyValueWhenRegsExtGdprIsNoEqualsToOneOrZero() { // given and when final String gdpr = requestUtil.getGdprApplies(Regs.of(null, ExtRegs.of(2, null))); // then assertThat(gdpr).isEmpty(); } @Test public void getGdprAppliesShouldReturnOne() { // given and when final String gdpr = requestUtil.getGdprApplies(Regs.of(null, ExtRegs.of(1, null))); // then assertThat(gdpr).isEqualTo("1"); } @Test public void getGdprAppliesShouldReturnZero() { // given and when final String gdpr = requestUtil.getGdprApplies(Regs.of(null, ExtRegs.of(0, null))); // then assertThat(gdpr).isEqualTo("0"); } @Test public void getConsentShouldReturnEmptyValueWhenExtUserIsNull() { // given and when final String consent = requestUtil.getConsent(null); // then assertThat(consent).isEmpty(); } @Test public void getConsentShouldReturnEmptyValueWhenConsentIsNull() { // given and when final String consent = requestUtil.getConsent(ExtUser.builder().build()); // then assertThat(consent).isEmpty(); } @Test public void getConsentShouldReturnConsent() { // given and when final String consent = requestUtil.getConsent(ExtUser.builder().consent("consent").build()); // then assertThat(consent).isEqualTo("consent"); } }
java
13
0.663253
100
26.301075
93
starcoderdata
const Command = require("../../../inventory/base/Command"); const Discord = require("discord.js"); const registries = require('../../../inventory/models/registries'); const { checkDays } = require("../../helpers/functionz"); const stats = require('../../../inventory/models/voicestat'); const fs = require("fs"); //const exporter = require('highcharts-export-server'); const low = require('lowdb'); const { PieChart } = require("canvas-pie-chart"); // import chart generator //const d3 = require('d3-shape'); const Chart = require('chart.js'); const Canvas = require('canvas'); class Confirm extends Command { constructor(client) { super(client, { name: "oran", description: "Kanallardaki aktifliğe dayalı grafiği verir", usage: "oran gün @etiket/id", examples: ["oran 5", "oran 3 674565119161794560"], aliases: [], permLvl: [], cooldown: 3000, enabled: true, adminOnly: false, ownerOnly: false, onTest: true, rootOnly: false, dmCmd: false }); } async run(client, message, args, data) { const chart = new PieChart({ labels: [ { text: "Public", size: 4 }, { text: "Stream", size: 7 }, { text: "Alone", size: 15 } ], blackOrWhiteInvert: false, size: 4096 }); //console.log(chart); const canvas = Canvas.createCanvas(4096, 4096); const ctx = canvas.getContext("2d"); // draw chart output const buffer = chart.draw(); //fs.writeFileSync('./inventory/src/esle.png', buffer, {encoding: 'binary'}); //document var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); console.log(allah); fs.writeFileSync('./inventory/src/desole.png', grafik.toBase64Image(), { encoding: 'base64' }); } } module.exports = Confirm;
javascript
23
0.412789
85
30.00885
113
starcoderdata
/** */ package de.fhdo.lemma.service.intermediate; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object ' * <!-- end-user-doc --> * * <!-- begin-model-doc --> * * * Endpoint * <!-- end-model-doc --> * * * The following features are supported: * * * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getCommunicationType Type * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getProtocol * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getDataFormat Format * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getAddresses * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getTechnology * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getMicroservice * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getInterface * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getOperation * de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getReferredOperation Operation * * * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint() * @model * @generated */ public interface IntermediateEndpoint extends EObject { /** * Returns the value of the ' Type attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' Type attribute. * @see #setCommunicationType(String) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_CommunicationType() * @model unique="false" * @generated */ String getCommunicationType(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getCommunicationType Type attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' Type attribute. * @see #getCommunicationType() * @generated */ void setCommunicationType(String value); /** * Returns the value of the ' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' attribute. * @see #setProtocol(String) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_Protocol() * @model unique="false" * @generated */ String getProtocol(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getProtocol attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' attribute. * @see #getProtocol() * @generated */ void setProtocol(String value); /** * Returns the value of the ' Format attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' Format attribute. * @see #setDataFormat(String) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_DataFormat() * @model unique="false" * @generated */ String getDataFormat(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getDataFormat Format attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' Format attribute. * @see #getDataFormat() * @generated */ void setDataFormat(String value); /** * Returns the value of the ' attribute list. * The list contents are of type {@link java.lang.String}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' attribute list. * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_Addresses() * @model unique="false" * @generated */ EList getAddresses(); /** * Returns the value of the ' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' reference. * @see #setTechnology(IntermediateTechnology) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_Technology() * @model * @generated */ IntermediateTechnology getTechnology(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getTechnology reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' reference. * @see #getTechnology() * @generated */ void setTechnology(IntermediateTechnology value); /** * Returns the value of the ' container reference. * It is bidirectional and its opposite is '{@link de.fhdo.lemma.service.intermediate.IntermediateMicroservice#getEndpoints * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' container reference. * @see #setMicroservice(IntermediateMicroservice) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_Microservice() * @see de.fhdo.lemma.service.intermediate.IntermediateMicroservice#getEndpoints * @model opposite="endpoints" transient="false" * @generated */ IntermediateMicroservice getMicroservice(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getMicroservice container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' container reference. * @see #getMicroservice() * @generated */ void setMicroservice(IntermediateMicroservice value); /** * Returns the value of the ' container reference. * It is bidirectional and its opposite is '{@link de.fhdo.lemma.service.intermediate.IntermediateInterface#getEndpoints * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' container reference. * @see #setInterface(IntermediateInterface) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_Interface() * @see de.fhdo.lemma.service.intermediate.IntermediateInterface#getEndpoints * @model opposite="endpoints" transient="false" * @generated */ IntermediateInterface getInterface(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getInterface container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' container reference. * @see #getInterface() * @generated */ void setInterface(IntermediateInterface value); /** * Returns the value of the ' container reference. * It is bidirectional and its opposite is '{@link de.fhdo.lemma.service.intermediate.IntermediateOperation#getEndpoints * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' container reference. * @see #setOperation(IntermediateOperation) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_Operation() * @see de.fhdo.lemma.service.intermediate.IntermediateOperation#getEndpoints * @model opposite="endpoints" transient="false" * @generated */ IntermediateOperation getOperation(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getOperation container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' container reference. * @see #getOperation() * @generated */ void setOperation(IntermediateOperation value); /** * Returns the value of the ' Operation container reference. * It is bidirectional and its opposite is '{@link de.fhdo.lemma.service.intermediate.IntermediateReferredOperation#getEndpoints * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the ' Operation container reference. * @see #setReferredOperation(IntermediateReferredOperation) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getIntermediateEndpoint_ReferredOperation() * @see de.fhdo.lemma.service.intermediate.IntermediateReferredOperation#getEndpoints * @model opposite="endpoints" transient="false" * @generated */ IntermediateReferredOperation getReferredOperation(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.IntermediateEndpoint#getReferredOperation Operation container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the ' Operation container reference. * @see #getReferredOperation() * @generated */ void setReferredOperation(IntermediateReferredOperation value); } // IntermediateEndpoint
java
7
0.665581
164
41.940678
236
starcoderdata
#include const int inf=2147483647; char c[3001][3001]; int d[3001],q[3001]; main() { int i,j,k,n,m,x,T; scanf("%d",&T); while(T--) { scanf("%d %d",&n,&m); for(i=0;i<n;i++) for(j=0,d[i]=inf;j<n;j++) c[i][j]=0; for(i=0;i<m;i++) { scanf("%d %d",&j,&k); j--,k--; c[j][k]=c[k][j]=1; } scanf("%d",&x); while(x--) { scanf("%d %d",&j,&k); j--,k--; c[j][k]^=1; c[k][j]^=1; } d[q[0]=0]=0; for(i=0,j=1;i<j;i++) for(k=0;k<n;k++) if(c[q[i]][k] && d[q[i]]+1<d[k]) d[q[j++]=k]=d[q[i]]+1; for(i=j=0;i<n;i++) if(d[i]>10 && d[i]<inf)j++; printf("%d\n",j); } }
c++
16
0.292005
48
21.128205
39
starcoderdata
<?php namespace App\Contracts\Repositories; interface BaseRepositoryInterface { public function all(); public function create(array $data); public function destroy($id); public function find($id); public function getModel(); public function setModel($model); public function update(array $data, object $entity); public function with($relations); public function select(array $type); public function search(array $data, $type, $value); public function where($type, $value); public function getByeOffsetLimit($offset, $limit); public function updateOrCreate(array $if, array $value); }
php
8
0.688822
60
19.6875
32
starcoderdata
def turn_on( self, speed: str = None, percentage: int = None, preset_mode: str = None, **kwargs, ) -> None: """Turns fan to medium speed.""" updated = False if preset_mode is not None: self.set_preset_mode(preset_mode) updated = True if percentage is not None: self.set_percentage(percentage) updated = True if speed is not None: self.set_speed(speed) updated = True _LOGGER.warning("turn_on %s %s", self._attr_percentage, updated) if ( not updated and (self._attr_percentage or 0) < self._fan_speeds[self._on_speed] ): self.set_preset_mode(self._on_speed)
python
10
0.515544
79
31.208333
24
inline
// Approach 1: (Simple BFS) // TC: O(n*n) // SC: O(n) // Approach 2: (Topo Sort + BFS) // TC: O(n) // SC: O(n) #include using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" class Graph { private: // pair<index, weight> vector<vector<pair<int, int>>> List; public: Graph(int n); void addEdge(int u, int v, int w); void displayList(); // Approach 1 vector shortestDistance1(int start); // Approach 2 stack topoSort(); void topoHelper(int start, vector &visited, stack &nodeSt); vector shortestDistance2(int start); }; Graph::Graph(int n) { List.resize(n); } void Graph::addEdge(int u, int v, int w) { List[u].push_back({v, w}); } void Graph::displayList() { int size = List.size(); int count{}; for (auto i : List) { cout << count++ << ": "; for (auto j : i) cout << j.first << " - " << j.second << " "; cout << "\n"; } cout << "\n"; } // Approach 1 vector Graph::shortestDistance1(int start) { int n = List.size(); vector distance(n, INT_MAX); queue<pair<int, int>> nodeQu; distance[start] = 0; nodeQu.push({start, 0}); while (!nodeQu.empty()) { int currNode = nodeQu.front().first; nodeQu.pop(); for (auto i : List[currNode]) { if (distance[currNode] + i.second < distance[i.first]) { distance[i.first] = distance[currNode] + i.second; nodeQu.push(i); } } } return distance; } // Approach 2 void Graph::topoHelper(int start, vector &visited, stack &nodeSt) { visited[start] = true; for (auto i : List[start]) if (!visited[i.first]) topoHelper(i.first, visited, nodeSt); nodeSt.push(start); } stack Graph::topoSort() { int n = List.size(); vector visited(n, false); stack nodeSt; for (int i = 0; i < n; ++i) if (!visited[i]) topoHelper(i, visited, nodeSt); return nodeSt; } vector Graph::shortestDistance2(int start) { int n = List.size(); stack sortedNodes = topoSort(); vector distance(n, INT_MAX); distance[start] = 0; while (!sortedNodes.empty()) { int curr = sortedNodes.top(); sortedNodes.pop(); // To make sure we start with the 'start' node if (distance[curr] != INT_MAX) for (auto i : List[curr]) if (distance[curr] + i.second < distance[i.first]) distance[i.first] = distance[curr] + i.second; } return distance; } void solve() { // 0 Based Indexing int n = 6; Graph g(n); vector U{0, 0, 1, 2, 4, 4, 5}; vector V{1, 4, 2, 3, 2, 5, 3}; vector W{2, 1, 3, 6, 2, 4, 1}; for (int i = 0; i < U.size(); ++i) g.addEdge(U[i], V[i], W[i]); // Displays Adjacency List cout << "List: \n"; g.displayList(); vector distance; distance = g.shortestDistance1(0); cout << "Shortest Distance 1:\n"; for (int i = 0; i < n; ++i) cout << i << ": " << distance[i] << endl; distance = g.shortestDistance2(0); cout << "Shortest Distance 2:\n"; for (int i = 0; i < n; ++i) cout << i << ": " << distance[i] << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
c++
14
0.525547
76
20.208333
168
starcoderdata
class Solution { public: int countElements(vector nums) { sort(begin(nums), end(nums)); int n = nums.size(), ans = 0; for (int i = 0; i < n; ++i) { bool left = false, right = false; for (int j = 0; j < i; ++j) { if (nums[j] < nums[i]) left = true; } for (int j = i + 1; j < n; ++j) { if (nums[i] < nums[j]) right = true; } if (left and right) ++ans; } return ans; } };
c++
10
0.54329
49
23.368421
19
starcoderdata
package protocol import ( "io" "time" ) // FieldUnmarshaler used by protocol unmarshaling to unmarshal a type's nested fields. type FieldUnmarshaler interface { UnmarshalFields(FieldDecoder) error } // A FieldValue is a value that will be unmarshalered from the decoder to // a concrete value. type FieldValue interface{} // ListDecoder provides the interface for unmarshaling list elements from the // underlying decoder. type ListDecoder interface { ListGet(fn func(v FieldValue)) ListGetList(fn func(n int, ld ListDecoder)) ListGetMap(fn func(ks []string, md MapDecoder)) ListGetFields(m FieldUnmarshaler) } // MapDecoder provides the interface for unmarshaling map elements from the // underlying decoder. The map key the value is retrieved from is k. type MapDecoder interface { MapGet(k string, fn func(v FieldValue)) MapGetList(k string, fn func(n int, ld ListDecoder)) MapGetMap(k string, fn func(ks []string, fd FieldDecoder)) MapGetFields(k string, fn func() FieldUnmarshaler) } // FieldDecoder provides the interface for unmarshaling values from a type. The // value is retrieved from the location referenced to by the Target. The field // name that the value is retrieved from is k. type FieldDecoder interface { Get(t Target, k string, fn func(v FieldValue), meta Metadata) GetList(t Target, k string, fn func(n int, ld ListDecoder), meta Metadata) GetMap(t Target, k string, fn func(ks []string, md MapDecoder), meta Metadata) GetFields(t Target, k string, fn func() FieldUnmarshaler, meta Metadata) } // DecodeBool converts a FieldValue into a bool pointer, updating the value // pointed to by the input. func DecodeBool(vp **bool) func(FieldValue) { return func(v FieldValue) { *vp = new(bool) **vp = v.(bool) } } // DecodeString converts a FieldValue into a string pointer, updating the value // pointed to by the input. func DecodeString(vp **string) func(FieldValue) { return func(v FieldValue) { *vp = new(string) **vp = v.(string) } } // DecodeInt64 converts a FieldValue into an int64 pointer, updating the value // pointed to by the input. func DecodeInt64(vp **int64) func(FieldValue) { return func(v FieldValue) { *vp = new(int64) **vp = v.(int64) } } // DecodeFloat64 converts a FieldValue into a float64 pointer, updating the value // pointed to by the input. func DecodeFloat64(vp **float64) func(FieldValue) { return func(v FieldValue) { *vp = new(float64) **vp = v.(float64) } } // DecodeTime converts a FieldValue into a time pointer, updating the value // pointed to by the input. func DecodeTime(vp **time.Time) func(FieldValue) { return func(v FieldValue) { *vp = new(time.Time) **vp = v.(time.Time) } } // DecodeBytes converts a FieldValue into a bytes slice, updating the value // pointed to by the input. func DecodeBytes(vp *[]byte) func(FieldValue) { return func(v FieldValue) { *vp = v.([]byte) } } // DecodeReadCloser converts a FieldValue into an io.ReadCloser, updating the value // pointed to by the input. func DecodeReadCloser(vp *io.ReadCloser) func(FieldValue) { return func(v FieldValue) { *vp = v.(io.ReadCloser) } } // DecodeReadSeeker converts a FieldValue into an io.ReadCloser, updating the value // pointed to by the input. func DecodeReadSeeker(vp *io.ReadSeeker) func(FieldValue) { return func(v FieldValue) { *vp = v.(io.ReadSeeker) } }
go
12
0.73467
86
29.017699
113
starcoderdata
package de.bergwerklabs.framework.commons.bungee.chat; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; /** * Created by on 29.11.2017. * * as the PluginMessenger in SpigotCommons but this time re-implemented for BungeeCord. * * @author */ public class PluginMessenger { private String prefix; /** @param name */ public PluginMessenger(String name) { this.prefix = "§6>> §e" + name + " §6❘§7 "; } /** * @param message * @param player */ public void message(String message, ProxiedPlayer player) { player.sendMessage(ChatMessageType.CHAT, TextComponent.fromLegacyText(prefix + message)); } }
java
13
0.720794
105
26.612903
31
starcoderdata
#ifndef SDK_COMMON_H_8710A968_FB61_435A_B9F6_166D668B92A9 #define SDK_COMMON_H_8710A968_FB61_435A_B9F6_166D668B92A9 #pragma once /* sdk_common.h Типы и определения, отсутствующие в SDK. */ /* Copyright (c) 1996 Copyright (c) 2000 Far Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. */ // winnt.h #ifndef IO_REPARSE_TAG_DRIVE_EXTENDER #define IO_REPARSE_TAG_DRIVE_EXTENDER 0x80000005L #endif #ifndef IO_REPARSE_TAG_FILTER_MANAGER #define IO_REPARSE_TAG_FILTER_MANAGER 0x8000000BL #endif #ifndef IO_REPARSE_TAG_IIS_CACHE #define IO_REPARSE_TAG_IIS_CACHE 0xA0000010L #endif #ifndef IO_REPARSE_TAG_APPXSTRM #define IO_REPARSE_TAG_APPXSTRM 0xC0000014L #endif #ifndef IO_REPARSE_TAG_DFM #define IO_REPARSE_TAG_DFM 0x80000016L #endif #ifndef IO_REPARSE_TAG_PROJFS #define IO_REPARSE_TAG_PROJFS 0x9000001CL #endif #ifndef IO_REPARSE_TAG_LX_SYMLINK #define IO_REPARSE_TAG_LX_SYMLINK 0xA000001DL #endif #ifndef IO_REPARSE_TAG_STORAGE_SYNC #define IO_REPARSE_TAG_STORAGE_SYNC 0x8000001EL #endif #ifndef IO_REPARSE_TAG_WCI_TOMBSTONE #define IO_REPARSE_TAG_WCI_TOMBSTONE 0xA000001FL #endif #ifndef IO_REPARSE_TAG_UNHANDLED #define IO_REPARSE_TAG_UNHANDLED 0x80000020L #endif #ifndef IO_REPARSE_TAG_ONEDRIVE #define IO_REPARSE_TAG_ONEDRIVE 0x80000021L #endif #ifndef IO_REPARSE_TAG_PROJFS_TOMBSTONE #define IO_REPARSE_TAG_PROJFS_TOMBSTONE 0xA0000022L #endif #ifndef IO_REPARSE_TAG_AF_UNIX #define IO_REPARSE_TAG_AF_UNIX 0x80000023L #endif #ifndef IO_REPARSE_TAG_LX_FIFO #define IO_REPARSE_TAG_LX_FIFO 0x80000024L #endif #ifndef IO_REPARSE_TAG_LX_CHR #define IO_REPARSE_TAG_LX_CHR 0x80000025L #endif #ifndef IO_REPARSE_TAG_LX_BLK #define IO_REPARSE_TAG_LX_BLK 0x80000026L #endif // ntrtl.h #define RTL_RESOURCE_FLAG_LONG_TERM 0x00000001ul typedef struct _RTL_RESOURCE { RTL_CRITICAL_SECTION Lock; HANDLE SharedSemaphore; ULONG SharedWaiters; HANDLE ExclusiveSemaphore; ULONG ExclusiveWaiters; LONG NumberActive; HANDLE OwningThread; ULONG Flags; PVOID DebugInfo; } RTL_RESOURCE, *PRTL_RESOURCE; #endif // SDK_COMMON_H_8710A968_FB61_435A_B9F6_166D668B92A9
c
6
0.796014
73
27.198347
121
starcoderdata
@Override public boolean performAction() { collectQuerySpecs(); CodeSearchQuery query = null; ISearchResultViewPart activeSearchView = null; if (prefStore.getBoolean(ICodeSearchPrefs.REUSE_LAST_SEARCH_QUERY) && previousQuery != null) { // if the query is still running, reusing it is not possible if (NewSearchUI.isQueryRunning(previousQuery)) { MessageDialog.openError(getShell(), Messages.CodeSearchDialog_queryStillRunningError_xtit, Messages.CodeSearchDialog_queryReuseNotPossibleErrorText_xmsg); return false; } query = previousQuery; activeSearchView = NewSearchUI.getSearchResultView(); query.setQuerySpecs(querySpecs); } else { query = new CodeSearchQuery(querySpecs); } writeDialogSettings(); query.setProjectProvider(projectProvider); NewSearchUI.runQueryInBackground(query, activeSearchView); return true; }
java
12
0.719786
98
35
26
inline
def init_table(connection, table): '''drops and recreates table''' t = tables(table) columns = ', '.join(['{} {}'.format(c[0],c[1]) for c in t]) drop = 'DROP TABLE IF EXISTS {}'.format(table) create = 'CREATE TABLE {} ({})'.format(table,columns) print(drop) print(create) with connection: cr = connection.cursor() cr.execute(drop) connection.commit() cr.execute(create) connection.commit() connection.close()
python
11
0.583505
63
29.375
16
inline
#ifndef X_RESOURCES_H #define X_RESOURCES_H #ifdef __APPLE__ #include #define EXTLD(NAME) \ extern const unsigned char _section$__DATA__ ## NAME []; #define LDVAR(NAME) _section$__DATA__ ## NAME #define LDLEN(NAME) (getsectbyname("__DATA", "__" #NAME)->size) #elif (defined __WIN32__) /* mingw */ #define EXTLD(NAME) \ extern const unsigned char binary_ ## NAME ## _start[]; \ extern const unsigned char binary_ ## NAME ## _end[]; #define LDVAR(NAME) \ binary_ ## NAME ## _start #define LDLEN(NAME) \ ((binary_ ## NAME ## _end) - (binary_ ## NAME ## _start)) #else /* gnu/linux ld */ #define EXTLD(NAME) \ extern const unsigned char _binary_ ## NAME ## _start[]; \ extern const unsigned char _binary_ ## NAME ## _end[]; #define LDVAR(NAME) \ _binary_ ## NAME ## _start #define LDLEN(NAME) \ ((_binary_ ## NAME ## _end) - (_binary_ ## NAME ## _start)) #endif #endif /* X_RESOURCES_H */
c
7
0.619733
63
26.8
35
starcoderdata
/** * @file logic_operation_inl.hpp * * @brief LogicOperation クラスの実装 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_GL_DETAIL_INL_LOGIC_OPERATION_INL_HPP #define BKSGE_CORE_RENDER_GL_DETAIL_INL_LOGIC_OPERATION_INL_HPP #include #if BKSGE_CORE_RENDER_HAS_GL_RENDERER #include #include namespace bksge { namespace render { namespace gl { namespace detail { inline ::GLenum ToGlLogicOperation(bksge::LogicOperation logic_operation) { switch (logic_operation) { case bksge::LogicOperation::kClear: return GL_CLEAR; case bksge::LogicOperation::kSet: return GL_SET; case bksge::LogicOperation::kCopy: return GL_COPY; case bksge::LogicOperation::kCopyInverted: return GL_COPY_INVERTED; case bksge::LogicOperation::kNoop: return GL_NOOP; case bksge::LogicOperation::kInvert: return GL_INVERT; case bksge::LogicOperation::kAnd: return GL_AND; case bksge::LogicOperation::kNand: return GL_NAND; case bksge::LogicOperation::kOr: return GL_OR; case bksge::LogicOperation::kNor: return GL_NOR; case bksge::LogicOperation::kXor: return GL_XOR; case bksge::LogicOperation::kEquiv: return GL_EQUIV; case bksge::LogicOperation::kAndReverse: return GL_AND_REVERSE; case bksge::LogicOperation::kAndInverted: return GL_AND_INVERTED; case bksge::LogicOperation::kOrReverse: return GL_OR_REVERSE; case bksge::LogicOperation::kOrInverted: return GL_OR_INVERTED; } return GL_COPY; } } // namespace detail BKSGE_INLINE LogicOperation::LogicOperation(bksge::LogicOperation logic_operation) : m_logic_operation(detail::ToGlLogicOperation(logic_operation)) {} BKSGE_INLINE LogicOperation::operator ::GLenum() const { return m_logic_operation; } } // namespace gl } // namespace render } // namespace bksge #endif // BKSGE_CORE_RENDER_HAS_GL_RENDERER #endif // BKSGE_CORE_RENDER_GL_DETAIL_INL_LOGIC_OPERATION_INL_HPP
c++
18
0.700939
69
26.026316
76
starcoderdata
import static org.junit.Assert.*; /** * Tests for FunUtilTest */ public class FunUtilTest { }
java
4
0.780488
107
21.888889
9
starcoderdata
import importlib import os import sys def _from_install_import(name): install_module_path = os.path.join( os.path.dirname(__file__), '..', '..', 'install') original_sys_path = sys.path.copy() try: sys.path.append(install_module_path) return importlib.import_module(name) finally: sys.path = original_sys_path
python
10
0.629526
57
24.642857
14
starcoderdata
#define _GNU_SOURCE 1 #include "stdio.h" #include #include #include #include #include #include "/root/libpruio-0.2/src/c_wrapper/pruio.h" // include header #include "/root/libpruio-0.2/src/c_wrapper/pruio_pins.h" //#include "./pruio_c_wrapper.h" // include /header //#include "./pruio_pins.h" // include header #define P1 P8_13 #define P2 P8_15 #define P3 P8_17 #define P4 P8_19 #define POLL 6 #define PAUSE 1000 #define SENSORS 80 //5*8*2 FILE *file; // int isleep(unsigned int mseconds) // { // fd_set set; // struct timeval timeout; // /* Initialize the file descriptor set. */ // FD_ZERO(&set); // FD_SET(STDIN_FILENO, &set); // Initialize the timeout data structure. // timeout.tv_sec = 0; // timeout.tv_usec = mseconds * 1; // return TEMP_FAILURE_RETRY(select(FD_SETSIZE, // &set, NULL, NULL, // &timeout)); // } int cState[SENSORS]; int pState[SENSORS]; int readSensors(pruIo *Io, int* o) { printf("c: +readSensors\n"); int i, v1, v2, v3, v4; for (i=0; i<SENSORS; i++){ o[i] = 0; } for (i=0; i<16; i++){ v1 = i&1; v2 = (i&2)>>1; v3 = (i&4)>>2; v4 = (i&8)>>3; pruio_gpio_setValue(Io, P1, v1); pruio_gpio_setValue(Io, P2, v2); pruio_gpio_setValue(Io, P3, v3); pruio_gpio_setValue(Io, P4, v4); int x = 0; while( pruio_gpio_Value(Io,P1) != v1 && pruio_gpio_Value(Io,P2) != v2 && pruio_gpio_Value(Io,P3) != v3 && pruio_gpio_Value(Io,P4) != v4 && x++ < 10000 ); usleep(1); if (x >= 10000) { printf("c: not setting values\n"); } o[i+00] = Io->Adc->Value[1]; o[i+16] = Io->Adc->Value[2]; o[i+32] = Io->Adc->Value[3]; o[i+48] = Io->Adc->Value[4]; o[i+64] = Io->Adc->Value[5]; } printf("c: -readSensors\n"); return 0; } int initSensors(pruIo *Io) { if (pruio_config(Io, 1, 0x1FE, 0, 4)){ // upload (default) settings, start IO mode printf("config failed (%s)\n", Io->Errr);} return 0; } int stopSensors (pruIo *io){ pruio_destroy(io); return 0; } int printSensors(int sensors[]){ printf("c: printSensors\n"); int bank, i; int changed = 0; for (bank=0; bank<5; bank++){ printf("%i >",bank); /* all steps */ for(i = 1; i < 16; i++) { if(sensors[i+bank*16]>15000){ cState[i+bank*16] = 1; } else { cState[i+bank*16] = 0; } if(cState[i+bank*16] != pState[i+bank*16]){ changed=1; } } } for (i=0; i<SENSORS; i++){ pState[i] = cState[i]; } if (changed > 0){ for (bank=0; bank<5; bank++){ printf("%i >",bank); /* all steps */ for(i = 1; i < 16; i++) { if(cState[i+bank*16] == 1){ printf("X "); } else { printf("- "); } } printf("\n"); } printf("\n"); } return 0; } void dumpsensors (int sensors[]){ int i, bank; for (bank=0; bank<5; bank++){ for(i = 0; i < 16; i++) { fprintf(file, "%i,", sensors[i+bank*16]); } } fprintf(file,"\n"); } int main2(int argc, char **argv) { file = fopen("file.txt", "w"); if (file == NULL) { printf("Error opening file!\n"); exit(1); } int sensors[SENSORS]; int i; for (i=0; i<SENSORS; i++){ sensors[i]=0; } //PruIo* io = pruio_new(0, 0x98, 0, 1); pruIo *Io = pruio_new(PRUIO_DEF_ACTIVE, 0x98, 10, 0); if (pruio_config(Io, 1, 0x1FE, 0, 4)){ // upload (default) settings, start IO mode printf("config failed (%s)\n", Io->Errr);} { while(1){ readSensors(Io, sensors); //printSensors(sensors); dumpsensors(sensors); } stopSensors(Io); } fclose(file); return 0; }
c
16
0.526399
84
21.957576
165
starcoderdata
@FunctionalInterface interface D { void accept(T t); } class Foo { void test() { } }
java
9
0.755556
127
21.583333
12
starcoderdata
from src.city import City from unittest import TestCase class TestCity(TestCase): def setUp(self): self.cities = City() self.cities._load_from_xml(cities_xml='tests/data/city.xml') def test_can_fetch_cities_from_the_web(self): self.cities.fetch() self.assertGreater(len(self.cities), 0) def test_can_get_correct_city_with_name(self): athabasca_dict = { 'id': 's0000001', 'english_name': 'Athabasca', 'french_name': 'Athabasca', 'province': 'AB', } athabasca = self.cities['Athabasca'] self.assertEqual(athabasca, athabasca_dict) def test_cannot_get_city_that_doesnt_exist(self): incorrect_city = self.cities['Atlantis'] self.assertIsNone(incorrect_city) def test_can_iterate_on_all_cities(self): expected_cities = [ { "id": "s0000001", "english_name": "Athabasca", "french_name": "Athabasca", "province": "AB" }, { "id": "s0000002", "english_name": "Clearwater", "french_name": "Clearwater", "province": "BC" }, { "id": "s0000003", "english_name": "Valemount", "french_name": "Valemount", "province": "BC" }, { "id": "s0000004", "english_name": "Grand Forks", "french_name": "Grand Forks", "province": "BC" }, ] cities_list = [city for city in self.cities] self.assertListEqual(expected_cities, cities_list) def test_can_check_if_city_is_in_cities(self): self.assertIn('Athabasca', self.cities) self.assertNotIn('Atlantis', self.cities)
python
11
0.501577
68
27.818182
66
starcoderdata
import pandas as pd import pathlib from sklearn.externals import joblib import helper import extractor def load_model(model_version): """ Load pre-trained model """ model_path = pathlib.Path(__file__).parent / f"pre-trained-models/{model_version}.pkl" return joblib.load(str(model_path)) class Inferencer: def __init__(self, model_version = "v0.2.0"): self.model = load_model(model_version) def predict_proba(self, statement): statement = pd.DataFrame({'content': [statement]}) return self.model.predict_proba(statement)[0][1]
python
12
0.685764
90
27.8
20
starcoderdata
protected TimedResource resourceWatcherStart(final IServiceProviderPlace place) { TimedResource tr = TimedResource.EMPTY; // CoordinationPlaces are tracked individually if (!(place instanceof CoordinationPlace)) { try { tr = ResourceWatcher.lookup().starting(this, place); } catch (EmissaryException ex) { logger.debug("No resource monitoring enabled"); } } return tr; }
java
12
0.607884
81
39.25
12
inline
/** * Copyright 2009 */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * Auto-generated: 2009-11-22 20:21:34.324313 * * @author ( * @author ( implemented Parcelable. */ public class Checkin implements FoursquareType, Parcelable { private String mCreated; private String mDisplay; private String mDistance; private String mId; private boolean mIsmayor; private boolean mPing; private String mShout; private User mUser; private Venue mVenue; public Checkin() { mPing = false; } private Checkin(Parcel in) { mCreated = ParcelUtils.readStringFromParcel(in); mDisplay = ParcelUtils.readStringFromParcel(in); mDistance = ParcelUtils.readStringFromParcel(in); mId = ParcelUtils.readStringFromParcel(in); mIsmayor = in.readInt() == 1; mPing = in.readInt() == 1; mShout = ParcelUtils.readStringFromParcel(in); if (in.readInt() == 1) { mUser = in.readParcelable(User.class.getClassLoader()); } if (in.readInt() == 1) { mVenue = in.readParcelable(Venue.class.getClassLoader()); } } public static final Parcelable.Creator CREATOR = new Parcelable.Creator { public Checkin createFromParcel(Parcel in) { return new Checkin(in); } @Override public Checkin[] newArray(int size) { return new Checkin[size]; } }; public String getCreated() { return mCreated; } public void setCreated(String created) { mCreated = created; } public String getDisplay() { return mDisplay; } public void setDisplay(String display) { mDisplay = display; } public String getDistance() { return mDistance; } public void setDistance(String distance) { mDistance = distance; } public String getId() { return mId; } public void setId(String id) { mId = id; } public boolean ismayor() { return mIsmayor; } public void setIsmayor(boolean ismayor) { mIsmayor = ismayor; } public boolean getPing() { return mPing; } public void setPing(boolean ping) { mPing = ping; } public String getShout() { return mShout; } public void setShout(String shout) { mShout = shout; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mCreated); ParcelUtils.writeStringToParcel(out, mDisplay); ParcelUtils.writeStringToParcel(out, mDistance); ParcelUtils.writeStringToParcel(out, mId); out.writeInt(mIsmayor ? 1 : 0); out.writeInt(mPing ? 1 : 0); ParcelUtils.writeStringToParcel(out, mShout); if (mUser != null) { out.writeInt(1); out.writeParcelable(mUser, flags); } else { out.writeInt(0); } if (mVenue != null) { out.writeInt(1); out.writeParcelable(mVenue, flags); } else { out.writeInt(0); } } @Override public int describeContents() { return 0; } }
java
13
0.579173
97
21.719512
164
starcoderdata
@Override protected FilterPipeline initialize() { logger.debug("Lazy initializing filter pipeline for '{}'", getPath()); // If the dataset has filters get the message if (oh.hasMessageOfType(FilterPipelineMessage.class)) { FilterPipelineMessage filterPipelineMessage = oh.getMessageOfType(FilterPipelineMessage.class); return FilterManager.getPipeline(filterPipelineMessage); } else { // No filters return null; } }
java
10
0.598921
111
41.846154
13
inline
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using ILNumerics.Drawing; using ILNumerics.Drawing.Plotting; namespace ILNEditor.Drawing.Plotting { [TypeConverter(typeof(LinePlotConverter))] public class LinePlotWrapper : GroupWrapper { private readonly LinesWrapper line; private readonly MarkerWrapper marker; private readonly ReadOnlyCollection positions; private readonly LinePlot source; public LinePlotWrapper(LinePlot source, PanelEditor editor, string path, string name = null, string label = null) : base(source, editor, path, BuildName(name, editor.Panel, source, LinePlot.LinePlotTag), String.IsNullOrEmpty(label) ? GetLinePlotLabelFromLegend(source, editor.Panel) : label) { this.source = source; line = new LinesWrapper(source.Line, editor, Path, LinePlot.LineTag, "Line"); marker = new MarkerWrapper(source.Marker, editor, Path, LinePlot.MarkerTag, "Marker"); positions = new ReadOnlyCollection } #region LinePlot [Category("Format")] public LinesWrapper Line { get { return line; } } [Category("Format")] public MarkerWrapper Marker { get { return marker; } } [Category("Positions")] [TypeConverter(typeof(PositionsConverter))] public ReadOnlyCollection Positions { // TODO: Make this editable get { return positions; } } #endregion #region Overrides of GroupWrapper internal override void Traverse(IEnumerable nodes = null) { base.Traverse((nodes ?? source.Children).Except(new Node[] { source.Line, source.Marker })); } #endregion #region Helpers private static string GetLinePlotLabelFromLegend(LinePlot source, Panel panel) { int index = GetNodeIndex(panel, source); var legend = panel.Scene.First if (legend != null) { // Get text from LegendItem at the index if (legend.Items.Children.Count() > index) return $"{LinePlot.LinePlotTag} ('{legend.Items.Find } return null; } #endregion #region Nested type: LinePlotConverter private class LinePlotConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is LinePlotWrapper) return ((LinePlotWrapper) value).Label; return base.ConvertTo(context, culture, value, destType); } } #endregion #region Nested type: PositionsConverter private class PositionsConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is ReadOnlyCollection { var positions = (ReadOnlyCollection value; return $"Positions (N = {positions.Count})"; } return base.ConvertTo(context, culture, value, destType); } } #endregion } }
c#
20
0.603306
126
31.336207
116
starcoderdata
#include "Camera.h" #define _USE_MATH_DEFINES #include /* sin */ Camera::Camera() { } Camera::Camera(const Point3D& position, const Point3D& target, const uint32_t image_height, const uint32_t image_width, Renderer * renderer, const uint32_t near, const uint32_t far) : m_position(position), m_image_height(image_height), m_image_width(image_width), m_renderer(renderer) { m_renderer->set_camera(this); m_near = near; m_far = far; m_direction = (target - position); m_direction.normalize(); m_right = -(m_direction ^ Vector3D(0, 1, 0)); m_right.normalize(); m_up = m_direction ^ m_right; m_up.normalize(); glm::mat4 orientation; orientation[0][0] = m_right.x; orientation[0][1] = m_right.y; orientation[0][2] = m_right.z; orientation[0][3] = 0; orientation[1][0] = m_up.x; orientation[1][1] = m_up.y; orientation[1][2] = m_up.z; orientation[1][3] = 0; orientation[2][0] = m_direction.x; orientation[2][1] = m_direction.y; orientation[2][2] = m_direction.z; orientation[2][3] = 0; orientation[3][0] = 0; orientation[3][1] = 0; orientation[3][2] = 0; orientation[3][3] = 1; glm::mat4 translation; translation[0][0] = 1; translation[0][1] = 0; translation[0][2] = 0; translation[0][3] = -m_position.x; translation[1][0] = 0; translation[1][1] = 1; translation[1][2] = 0; translation[1][3] = -m_position.y; translation[2][0] = 0; translation[2][1] = 0; translation[2][2] = 1; translation[2][3] = -m_position.z; translation[3][0] = 0; translation[3][1] = 0; translation[3][2] = 0; translation[3][3] = 1; m_lookat = translation * orientation; m_lookat_inv = glm::inverse(m_lookat); } Camera::~Camera(){ } // Camera space to NDC [-1,1] const Point2D Camera::projectTransform(const Point3D& point_camera) const { // Prepare matrix for clipping const glm::vec4 point = glm::vec4(point_camera.x, point_camera.y, point_camera.z, 1); const glm::vec4 r = point * m_project; // Perspective divide return Point3D(r.x / r.w, r.y / r.w, r.z / r.w); } // World space to camera/view space const Point3D Camera::viewTransform(const Point3D& point_world) const { glm::vec4 p = glm::vec4(point_world.x, point_world.y, point_world.z, 1); glm::vec4 r = p * m_lookat; return Point3D(r.x, r.y, r.z); } // Camera/view space to World space const Point3D Camera::viewTransformInv(const Point3D& point_camera) const { glm::vec4 p = glm::vec4(point_camera.x, point_camera.y, point_camera.z, 1); glm::vec4 r = p * m_lookat_inv; return Point3D(r.x, r.y, r.z);; } // NDC [-1,1] to raster/screen space const Point2D Camera::viewportTransform(const Point2D& point_ndc) const { const double slopeX = m_image_width / 2.0; const double slopeY = m_image_height / 2.0; const Point2D point_raster = { slopeX * (point_ndc.x - -1), slopeY * (point_ndc.y - -1) }; return point_raster; } // Raster/screen space to NDC [-1,1] const Point2D Camera::viewportTransformInv(const Point2D& point_raster) const { const double slopeX = 2.0 / m_image_width; const double slopeY = 2.0 / m_image_height; const Point2D point_ndc = { -1 + slopeX * point_raster.x, -1 + slopeY * point_raster.y }; return point_ndc; } const bool Camera::insideFrustrum(const Point2D& point_raster, const float depth) const { return (point_raster.x < m_image_width && point_raster.x >= 0 && point_raster.y < m_image_height && point_raster.y >= 0 && depth >= m_near && depth <= m_far); }
c++
12
0.608228
181
35.831683
101
starcoderdata
<?php require_once (dirname(dirname(dirname(__FILE__)))) . '/_support/SynapseRestfulTestBase.php'; class CourseStudentViewCest extends SynapseRestfulTestBase { // These tests cover all aspects of the permissions View All Courses, View All Academic Updates, and View All Final Grades. // These are found in the Courses tab of a student's profile. private $studentIdHarry = 99422; private $studentIdHermione = 99423; // Full access permission set, with group connections to both Harry and Hermione private $staffP = [ 'email' => ' 'password' => ' 'id' => 99442, 'orgId' => 542, 'langId' => 1 ]; // Full access permission set, with course connections to both Harry and Hermione private $staffC = [ 'email' => ' 'password' => ' 'id' => 99437, 'orgId' => 542, 'langId' => 1 ]; // Full access permission set, with no connection to Harry, and an expired course connection to Hermione private $staffS = [ 'email' => ' 'password' => ' 'id' => 99447, 'orgId' => 542, 'langId' => 1 ]; // Minimum access permission set, with connections to both Harry and Hermione private $staffR = [ 'email' => ' 'password' => ' 'id' => 99710, 'orgId' => 542, 'langId' => 1 ]; // Aggregate only permission set, with connections to both Harry and Hermione private $staffA = [ 'email' => ' 'password' => 'password1!', 'id' => 99436, 'orgId' => 542, 'langId' => 1 ]; // Full access permission set, from another institution private $staffB = [ 'email' => ' 'password' => ' 'id' => 99705, 'orgId' => 543, 'langId' => 1 ]; // Has permission to view courses but not academic updates or final grades; has connections to both Harry and Hermione private $staffK = [ 'email' => ' 'password' => ' 'id' => 99711, 'orgId' => 542, 'langId' => 1 ]; // Has permission to view final grades, but has no connection to Hermione private $staffH = [ 'email' => ' 'password' => ' 'id' => 99445, 'orgId' => 542, 'langId' => 1 ]; private $coursesHarry = [ ['student_id' => 99422], ['course_id' => 435], ['course_id' => 436] ]; private $coursesHermione = [ ['student_id' => 99423], ['course_id' => 435], ['course_id' => 436], ['course_id' => 437], ['course_id' => 438] ]; // These currently show up in the JSON, but not on the front end (as of 7/22/15). private $academicUpdatesHarry = [ ['course_id' => 435, 'absense' => 6, // misspelled in the JSON 'in_progress_grade' => 'B'] ]; private $finalGradeHermione = [ ['course_id' => 437, 'final_grade' => 'A'] ]; // To keep these tests valid, we'll check if the term we're using includes today's date (which it did when these tests were written). // If not, we'll change the dates in the database of the year and term being used. public function keepTestsCurrent() { $now = mktime(); $termEndDate = mktime(0, 0, 0, 11, 30, 15); // The term ends 12/1/15; using the previous day to avoid time zone issues. if ($now > $termEndDate) { $date = $this->_DynamicDates(); $this->_academicYearsMySQLrunner($date["2WeeksAgo"], $date["2Weeks"], 110); $this->_academicTermsMySQLrunner($date["2WeeksAgo"], $date["1Week"], 123); } } // View all courses public function testViewCoursesForStudentInGroup(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view courses, with a group connection to the student, can view the student's courses."); $this->_getAPITestRunner($I, $this->staffP, 'courses/student/'.$this->studentIdHarry, [], 200, $this->coursesHarry); } public function testViewCoursesForStudentInCourse(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view courses, with a course connection to the student, can view the student's courses."); $this->_getAPITestRunner($I, $this->staffC, 'courses/student/'.$this->studentIdHarry, [], 200, $this->coursesHarry); } // It currently returns 200, but an empty course_list_table. public function testViewCoursesForInaccessibleStudent(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view courses, without a connection to the student, cannot view the student's courses."); $this->_getAPITestRunner($I, $this->staffS, 'courses/student/'.$this->studentIdHarry, [], null, [['course_list_table' => []]]); } // It currently returns 200, but an empty course_list_table. public function testViewStudentCoursesWithoutPermission(ApiAuthTester $I) { $I->wantTo("Verify a staff member without permission to view courses, cannot view the student's courses."); $this->_getAPITestRunner($I, $this->staffR, 'courses/student/'.$this->studentIdHarry, [], null, [['course_list_table' => []]]); } // It currently returns 200, but an empty course_list_table. public function testViewStudentCoursesAggOnly(ApiAuthTester $I) { $I->wantTo("Verify a staff member with an aggregate only permission set cannot view the student's courses."); $this->_getAPITestRunner($I, $this->staffA, 'courses/student/'.$this->studentIdHarry, [], null, [['course_list_table' => []]]); } public function testViewStudentCoursesOtherInstitution(ApiAuthTester $I) { $I->wantTo("Verify a staff member at another institution cannot view the student's courses."); $this->_getAPITestRunner($I, $this->staffB, 'courses/student/'.$this->studentIdHarry, [], 403, []); } // It currently returns 200, but an empty course_list_table. public function testViewCoursesForStudentInExpiredCourse(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view courses, with an expired course connection to the student, cannot view a student's courses."); $this->_getAPITestRunner($I, $this->staffS, 'courses/student/'.$this->studentIdHermione, [], 200, [['course_list_table' => []]]); } // Academic Updates public function testViewAcademicUpdatesForStudentInGroup(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view academic updates, with a group connection to the student, can view the student's academic updates."); $this->_getAPITestRunner($I, $this->staffP, 'courses/student/'.$this->studentIdHarry, [], 200, $this->academicUpdatesHarry); } public function testViewAcademicUpdatesForStudentInCourse(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view academic updates, with a course connection to the student, can view the student's academic updates."); $this->_getAPITestRunner($I, $this->staffC, 'courses/student/'.$this->studentIdHarry, [], 200, $this->academicUpdatesHarry); } public function testViewAcademicUpdatesForInaccessibleStudent(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view academic updates, without a connection to the student, cannot view the student's academic updates."); $this->_getAPITestRunner($I, $this->staffS, 'courses/student/'.$this->studentIdHarry, [], null, []); $I->dontSeeResponseContainsJson(['absense' => 6]); $I->dontSeeResponseContainsJson(['in_progress_grade' => 'B']); } public function testViewStudentAcademicUpdatesWithoutPermission(ApiAuthTester $I) { $I->wantTo("Verify a staff member without permission to view academic updates, cannot view the student's academic updates."); $this->_getAPITestRunner($I, $this->staffR, 'courses/student/'.$this->studentIdHarry, [], null, []); $I->dontSeeResponseContainsJson(['absense' => 6]); $I->dontSeeResponseContainsJson(['in_progress_grade' => 'B']); } public function testViewStudentAcademicUpdatesAggOnly(ApiAuthTester $I) { $I->wantTo("Verify a staff member with an aggregate only permission set cannot view the student's academic updates."); $this->_getAPITestRunner($I, $this->staffA, 'courses/student/'.$this->studentIdHarry, [], null, []); $I->dontSeeResponseContainsJson(['absense' => 6]); $I->dontSeeResponseContainsJson(['in_progress_grade' => 'B']); } public function testViewStudentAcademicUpdatesOtherInstitution(ApiAuthTester $I) { $I->wantTo("Verify a staff member at another institution cannot view the student's academic updates."); $this->_getAPITestRunner($I, $this->staffB, 'courses/student/'.$this->studentIdHarry, [], null, []); $I->dontSeeResponseContainsJson(['absense' => 6]); $I->dontSeeResponseContainsJson(['in_progress_grade' => 'B']); } public function testViewCoursesButNotAcademicUpdates(ApiAuthTester $I, $scenario) { $scenario->skip("Failed"); $I->wantTo("Verify permissions work correctly for a staff member with permission to view courses but without permission to view academic updates."); $this->_getAPITestRunner($I, $this->staffK, 'courses/student/'.$this->studentIdHarry, [], 200, $this->coursesHarry); $I->dontSeeResponseContainsJson(['absense' => 6]); $I->dontSeeResponseContainsJson(['in_progress_grade' => 'B']); } // Final Grades public function testViewFinalGradeForStudentInGroup(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view final grades, with a group connection to the student, can view a student's final grade."); $this->_getAPITestRunner($I, $this->staffP, 'courses/student/'.$this->studentIdHermione, [], 200, $this->finalGradeHermione); } public function testViewFinalGradeForStudentInCourse(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view final grades, with a course connection to the student, can view a student's final grade."); $this->_getAPITestRunner($I, $this->staffC, 'courses/student/'.$this->studentIdHermione, [], 200, $this->finalGradeHermione); } public function testViewFinalGradeForInaccessibleStudent(ApiAuthTester $I) { $I->wantTo("Verify a staff member with permission to view final grades, without a connection to the student, cannot view the student's final grades."); $this->_getAPITestRunner($I, $this->staffH, 'courses/student/'.$this->studentIdHermione, [], null, []); $I->dontSeeResponseContainsJson(['final_grade' => 'A']); } public function testViewStudentFinalGradeWithoutPermission(ApiAuthTester $I) { $I->wantTo("Verify a staff member without permission to view final grades, cannot view the student's final grades."); $this->_getAPITestRunner($I, $this->staffR, 'courses/student/'.$this->studentIdHermione, [], null, []); $I->dontSeeResponseContainsJson(['final_grade' => 'A']); } public function testViewStudentFinalGradeAggOnly(ApiAuthTester $I) { $I->wantTo("Verify a staff member with an aggregate only permission set cannot view the student's final grades."); $this->_getAPITestRunner($I, $this->staffA, 'courses/student/'.$this->studentIdHermione, [], null, []); $I->dontSeeResponseContainsJson(['final_grade' => 'A']); } public function testViewStudentFinalGradeOtherInstitution(ApiAuthTester $I) { $I->wantTo("Verify a staff member at another institution cannot view the student's final grades."); $this->_getAPITestRunner($I, $this->staffB, 'courses/student/'.$this->studentIdHermione, [], null, []); $I->dontSeeResponseContainsJson(['final_grade' => 'A']); } public function testViewCoursesButNotFinalGrade(ApiAuthTester $I) { $I->wantTo("Verify permissions work correctly for a staff member with permission to view courses but without permission to view final grades."); $this->_getAPITestRunner($I, $this->staffK, 'courses/student/'.$this->studentIdHermione, [], 200, $this->coursesHermione); $I->dontSeeResponseContainsJson(['final_grade' => 'A']); } public function databaseReload() { // Cleaning up data before ending test file $output = shell_exec('./runauthtests.sh --reload'); codecept_debug($output); } }
php
14
0.644567
168
43.367698
291
starcoderdata
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Reflection { public abstract partial class ConstructorInfo : MethodBase { protected ConstructorInfo() { } public override MemberTypes MemberType => MemberTypes.Constructor; [DebuggerHidden] [DebuggerStepThrough] public object Invoke(object[] parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); public abstract object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture); public override bool Equals(object obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ConstructorInfo left, ConstructorInfo right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test if (right is null) { // return true/false not the test result https://github.com/dotnet/coreclr/issues/914 return (left is null) ? true : false; } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals if ((object)left == (object)right) { return true; } return (left is null) ? false : left.Equals(right); } public static bool operator !=(ConstructorInfo left, ConstructorInfo right) => !(left == right); public static readonly string ConstructorName = ".ctor"; public static readonly string TypeConstructorName = ".cctor"; } }
c#
14
0.658404
135
39.34
50
starcoderdata
protected void onPostExecute(Void result){ // Single download completed if(downloadCallback instanceof DownloadSingle){ if(failedDownloads.size() >= 1){ ((DownloadSingle) downloadCallback).onCompleted(FAILED); }else{ ((DownloadSingle) downloadCallback).onCompleted(SUCCESS); } } // Multiple downloads completed if(downloadCallback instanceof DownloadMultiple){ ((DownloadMultiple) downloadCallback).onCompleted( successDownloads.toArray(new String[0]), failedDownloads.toArray(new String[0]) ); } // Multiple downloads completed in Parallel if(downloadCallback instanceof DownloadMultipleParallel){ // When all the download are completed if(urlsNumber == successDownloads.size() + failedDownloads.size()){ ((DownloadMultipleParallel) downloadCallback).onCompleted( successDownloads.toArray(new String[0]), failedDownloads.toArray(new String[0]) ); } } }
java
14
0.520913
83
40.483871
31
inline
/* * Copyright 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.aelstad.keccakj.provider; import java.security.NoSuchAlgorithmException; import java.security.Provider; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import com.github.aelstad.keccakj.cipher.CipherAdapter; import com.github.aelstad.keccakj.cipher.CipherInterface; import com.github.aelstad.keccakj.cipher.CipherProviderFactory; public final class KeccakjProvider extends Provider implements CipherProviderFactory { final static String cipherPrefix = "Cipher."; final static String messageDigestPrefix = "MessageDigest."; final static String secureRandomPrefix = "SecureRandom."; public KeccakjProvider() { super("com.github.aelstad.keccakj", 1.0, "Implementation of digests, ciphers and random generated based on the Keccack permutation. Includes SHA3 digests"); put(messageDigestPrefix + Constants.SHA3_224, "com.github.aelstad.keccakj.fips202.SHA3_224"); put(messageDigestPrefix + Constants.SHA3_256, "com.github.aelstad.keccakj.fips202.SHA3_256"); put(messageDigestPrefix + Constants.SHA3_384, "com.github.aelstad.keccakj.fips202.SHA3_384"); put(messageDigestPrefix + Constants.SHA3_512, "com.github.aelstad.keccakj.fips202.SHA3_512"); put(secureRandomPrefix + Constants.KECCAK_RND128, "com.github.aelstad.keccakj.spi.KeccakRnd128"); put(secureRandomPrefix + Constants.KECCAK_RND256, "com.github.aelstad.keccakj.spi.KeccakRnd256"); put(cipherPrefix + Constants.SHAKE128_STREAM_CIPHER, "com.github.aelstad.keccakj.spi.Shake128StreamCipher"); put(cipherPrefix + Constants.SHAKE256_STREAM_CIPHER, "com.github.aelstad.keccakj.spi.Shake256StreamCipher"); put(cipherPrefix + Constants.LAKEKEYAK_AUTHENTICATING_STREAM_CIPHER, "com.github.aelstad.keccakj.spi.LakeKeyakCipher"); } @Override public CipherInterface getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException { String clazzName = getProperty(cipherPrefix + transformation); if(clazzName == null) { return new CipherAdapter(Cipher.getInstance(transformation)); } else { try { return (CipherInterface) Class.forName(clazzName).newInstance(); } catch(ClassNotFoundException ex) { throw new NoSuchAlgorithmException(); } catch(ClassCastException ex) { throw new NoSuchAlgorithmException(); } catch (InstantiationException e) { throw new NoSuchAlgorithmException(); } catch (IllegalAccessException e) { throw new NoSuchAlgorithmException(); } } } }
java
14
0.773536
158
43.157143
70
starcoderdata
package com.example.kafkaeventalarm.controller; import com.example.kafkaeventalarm.admin.KafkaAdminClient; import org.apache.kafka.clients.admin.ConsumerGroupListing; import org.apache.kafka.clients.admin.DescribeTopicsResult; import org.apache.kafka.clients.admin.TopicDescription; import org.apache.kafka.clients.admin.TopicListing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; @RestController @RequestMapping(value = "/kafka") public class KafkaAdminController { @Autowired private KafkaAdminClient kafkaAdminClient; @GetMapping(value = "/getTopics") public Collection getTopics() throws Exception { Collection topicListings = kafkaAdminClient.getTopics().listings().get(); return topicListings.stream().map(topicListing -> topicListing.name()).collect(Collectors.toList()); } @GetMapping(value = "/getConsumerGroups") public Collection getConsumerGroups() throws Exception { Collection consumerGroupListings = kafkaAdminClient.getConsumeGroups().all().get(); return consumerGroupListings.stream().map(consumerGroupListing -> consumerGroupListing.groupId()).collect(Collectors.toList()); } @GetMapping(value = "/describeTopic/{topic}") public Map<String, TopicDescription> describeTopic(@RequestParam String topic) throws Exception { DescribeTopicsResult describeTopic = kafkaAdminClient.getDescribeTopic(topic); Map<String, TopicDescription> map = describeTopic.all().get(); // nothing useful for now return map; } }
java
12
0.776519
135
39.479167
48
starcoderdata
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*//*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIEXTENSIONTRACKER_H #define BERRYIEXTENSIONTRACKER_H #include #include "berrySmartPointer.h" #include namespace berry { struct IExtension; struct IExtensionChangeHandler; struct IExtensionPointFilter; class Object; /** * An extension tracker keeps associations between extensions and their derived * objects on an extension basis. All extensions being added in a tracker will * automatically be removed when the extension is uninstalled from the registry. * Users interested in extension removal can register a handler that will let * them know when an object is being removed. * * This interface is not intended to be implemented by clients. * * @noimplement This interface is not intended to be implemented by clients. */ struct org_blueberry_core_runtime_EXPORT IExtensionTracker { enum ReferenceType { /** * Constant for strong (normal) reference holding. */ REF_STRONG, /** * Constant for weak reference holding. */ REF_WEAK }; virtual ~IExtensionTracker(); /** * Register an extension change handler with this tracker using the given filter. * * @param handler the handler to be registered * @param filter the filter to use to choose interesting changes */ virtual void RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter) = 0; /** * Register an extension change handler with this tracker for the given extension point id. * * @param handler the handler to be registered * @param extensionPointId the extension point id to track */ virtual void RegisterHandler(IExtensionChangeHandler *handler, const QString& extensionPointId = QString()) = 0; /** * Unregister the given extension change handler previously registered with this tracker. * * @param handler the handler to be unregistered */ virtual void UnregisterHandler(IExtensionChangeHandler* handler) = 0; /** * Create an association between the given extension and the given object. * The referenceType indicates how strongly the object is being kept in memory. * There are 2 possible values: REF_STRONG and REF_WEAK. * * @param extension the extension * @param object the object to associate with the extension * @param referenceType one of REF_STRONG, REF_WEAK */ virtual void RegisterObject(const SmartPointer extension, const SmartPointer object, ReferenceType referenceType) = 0; /** * Remove an association between the given extension and the given object. * * @param extension the extension under which the object has been registered * @param object the object to unregister */ virtual void UnregisterObject(const SmartPointer extension, const SmartPointer object) = 0; /** * Remove all the objects associated with the given extension. Return * the removed objects. * * @param extension the extension for which the objects are removed * @return the objects that were associated with the extension */ virtual QList > UnregisterObject(const SmartPointer extension) = 0; /** * Return all the objects that have been associated with the given extension. * All objects registered strongly will be return unless they have been unregistered. * The objects registered softly or weakly may not be returned if they have been garbage collected. * Return an empty array if no associations exist. * * @param extension the extension for which the object must be returned * @return the array of associated objects */ virtual QList > GetObjects(const SmartPointer extension) const = 0; /** * Close the tracker. All registered objects are freed and all handlers are being automatically removed. */ virtual void Close() = 0; }; } #endif // BERRYIEXTENSIONTRACKER_H
c
13
0.699039
138
32.743243
148
starcoderdata
const images = [ 'https://img11.360buyimg.com/img/jfs/t1/32635/10/3447/151344/5c763938Ec1fbeb80/9c4d83d697b6aa00.jpg', 'https://img11.360buyimg.com/img/jfs/t1/21785/21/8350/89923/5c763915E59529762/fd55496b9af73a74.jpg', 'https://img14.360buyimg.com/img/jfs/t1/16771/16/8423/180825/5c763946Ee0c50d3e/95968ce75a3ad45a.jpg', 'https://img20.360buyimg.com/img/jfs/t1/22700/9/8428/227755/5c763e2aE7bf26546/0b3c714d9c385a00.jpg', 'https://img30.360buyimg.com/img/jfs/t1/14302/26/8422/168758/5c763e34E1e306376/0f805082f633ec4c.jpg', 'https://img11.360buyimg.com/img/jfs/t1/15514/10/8499/168587/5c763e43E7cef5c04/25d91bafc492ec61.jpg', ]; const config = { data: { images, currentIdxType3: 0, }, handleType3SwiperAnimationFinish(e) { const page = this; page.setData({ currentIdxType3: e.detail.current, }); }, }; Page(config);
javascript
13
0.738178
103
33.68
25
starcoderdata
class Solution { public: int maxProfit(vector prices) { if (prices.size() < 2) return 0; int buy = -prices[0]; int sell = -1; int cold = 0; int tmp; for (int i = 1; i < prices.size(); ++i) { tmp = buy; buy = max(tmp, cold-prices[i]); cold = max(cold, sell); sell = tmp+prices[i]; } return max(sell, cold); } };
c++
13
0.528864
112
28.888889
18
starcoderdata
// Copyright 2005 Google Inc. All Rights Reserved. // // 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. // // // far-far-superior implementation courtesy of ( // // Nth Derivative Coding // (In signal processing disciplines, this is known as N-th Delta Coding.) // // Good for varint coding integer sequences with polynomial trends. // // Instead of coding a sequence of values directly, code its nth-order discrete // derivative. Overflow in integer addition and subtraction makes this a // lossless transform. // // constant linear quadratic // trend trend trend // / \ / \ / \_ // input |0 0 0 0 1 2 3 4 9 16 25 36 // 0th derivative(identity) |0 0 0 0 1 2 3 4 9 16 25 36 // 1st derivative(delta coding) | 0 0 0 1 1 1 1 5 7 9 11 // 2nd derivative(linear prediction) | 0 0 1 0 0 0 4 2 2 2 // ------------------------------------- // 0 1 2 3 4 5 6 7 8 9 10 11 // n in sequence // // Higher-order codings can break even or be detrimental on other sequences. // // random oscillating // / \ / \_ // input |5 9 6 1 8 8 2 -2 4 -4 6 -6 // 0th derivative(identity) |5 9 6 1 8 8 2 -2 4 -4 6 -6 // 1st derivative(delta coding) | 4 -3 -5 7 0 -6 -4 6 -8 10 -12 // 2nd derivative(linear prediction) | -7 -2 12 -7 -6 2 10 -14 18 -22 // --------------------------------------- // 0 1 2 3 4 5 6 7 8 9 10 11 // n in sequence // // Note that the nth derivative isn't available until sequence item n. Earlier // values are coded at lower order. For the above table, read 5 4 -7 -2 12 ... // // A caveat on class usage. Encode() and Decode() share state. Using both // without a Reset() in-between probably doesn't make sense. #ifndef S2_UTIL_CODING_NTH_DERIVATIVE_H_ #define S2_UTIL_CODING_NTH_DERIVATIVE_H_ #include "s2/base/integral_types.h" #include "s2/base/logging.h" class NthDerivativeCoder { public: // range of supported Ns: [ N_MIN, N_MAX ] enum { N_MIN = 0, N_MAX = 10, }; // Initialize a new NthDerivativeCoder of the given N. explicit NthDerivativeCoder(int n); // Encode the next value in the sequence. Don't mix with Decode() calls. int32 Encode(int32 k); // Decode the next value in the sequence. Don't mix with Encode() calls. int32 Decode(int32 k); // Reset state. void Reset(); // accessors int n() const { return n_; } private: int n_; // derivative order of the coder (the N in NthDerivative) int m_; // the derivative order in which to code the next value(ramps to n_) int32 memory_[N_MAX]; // value memory. [0] is oldest }; // Implementation below. // // Inlining the implementation roughly doubled the speed. All other // optimization tricks failed miserably. #if ~0 != -1 #error Sorry, this code needs twos complement integers. #endif inline NthDerivativeCoder::NthDerivativeCoder(int n) : n_(n) { if (n < N_MIN || n > N_MAX) { S2_LOG(ERROR) << "Unsupported N: " << n << ". Using 0 instead."; n_ = 0; } Reset(); } inline int32 NthDerivativeCoder::Encode(int32 k) { for (int i = 0; i < m_; ++i) { uint32 delta = static_cast - memory_[i]; memory_[i] = k; k = delta; } if (m_ < n_) memory_[m_++] = k; return k; } inline int32 NthDerivativeCoder::Decode(int32 k) { if (m_ < n_) m_++; for (int i = m_ - 1; i >= 0; --i) k = memory_[i] = memory_[i] + static_cast return k; } inline void NthDerivativeCoder::Reset() { for (int i = 0; i < n_; ++i) memory_[i] = 0; m_ = 0; } #endif // S2_UTIL_CODING_NTH_DERIVATIVE_H_
c
12
0.54378
80
34.785185
135
starcoderdata
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Application_model extends CI_Model { private $table = 'application'; public function __construct() { parent::__construct(); $this->load->database(); } public function get_name() { $query = $this->db->get($this->table); $row = $query->row_array(); $name = $row['name']; return $name; } public function get_version_number() { $query = $this->db->get($this->table); $result = $query->result_array(); $version_number = $result['major_version'] . '.' . $result['minor_version'] . '.' . $result['patch']; } }
php
13
0.539073
63
21.205882
34
starcoderdata
private void repeatChaos() { // Check if repeating chaos is configured if (integrationTestingConfig.getRepeatChaos() > 0) { // Check if chaos has been created if (thrownExceptionInfo != null) { int count = thrownExceptionInfo.getCount(); if (count < integrationTestingConfig.getRepeatChaos()) { // More chaos thrownExceptionInfo.setCount(++count); if (thrownExceptionInfo.getExceptionType() == RUNTIME_EXCEPTION) { throwRuntime(); } else { throwDenied(); } } else { // No more repeated chaos thrownExceptionInfo = null; } } } }
java
14
0.575182
76
31.666667
21
inline
'use strict'; angular.module('myApp.adminTestimonios', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/admin/testimonios', { templateUrl: 'admin/testimonios/testimonios.html', controller: 'TestimoniosAdminCtrl' }); }]) .controller('TestimoniosAdminCtrl', function($scope, $http, $filter, $log, $location, auth, $mdDialog, licenses, testimonios, MSG_ALERT) { var update = false; $scope.testimonio = {}; $scope.disabled = true; var alertType; var alertText; $scope.alerts = []; // Obtenemos el nombre del usuario logueado $scope.name = auth.getName(); // Obtenemos los permisos licenses.getLicenses().then(function(data){ $scope.licenses = data; }) $scope.logout = function() { auth.logout(); } /** * Método para establecer cuantos elementos están presentes en la página */ $scope.setItemsPerPage = function(num) { $scope.itemsPerPage = num; $scope.currentPage = 1; //reset to first page } /* * Método para habilitar la pantalla de creación de nuevos patrocinadores. */ $scope.fnew = function() { $scope.new = true; $scope.testimonio = {}; update = false; $scope.disabled = false; } $scope.save = function() { if(update === false){ testimonios.insert($scope.testimonio.NOMBRE, $scope.testimonio.CONTENIDO).then(function(insertado){ if(insertado == 'true'){ obtenerTodo(); $scope.new = false; alertType = MSG_ALERT.TYPE_SUCCESS; alertText = MSG_ALERT.SAVE_OK; } else { alertType = MSG_ALERT.TYPE_ERROR; alertText = MSG_ALERT.SAVE_KO; } showAlert(); }) } else { testimonios.update($scope.testimonio.ID, $scope.testimonio.NOMBRE, $scope.testimonio.CONTENIDO).then(function(actualizado){ if(actualizado == 'true'){ obtenerTodo(); $scope.new = false; alertType = MSG_ALERT.TYPE_SUCCESS; alertText = MSG_ALERT.SAVE_OK; } else { alertType = MSG_ALERT.TYPE_ERROR; alertText = MSG_ALERT.SAVE_KO; } showAlert(); }) } } /** * Método para mostrar el dialogo de confirmación de la eliminación */ $scope.showConfirm = function(ev, item) { var confirm = $mdDialog.confirm() .title('¿Estas seguro que deseas eliminar este testimonio?') .textContent('Una vez eliminada no se podrá recuperar posteriormente.') .ariaLabel('Lucky day') .targetEvent(ev) .ok('Si') .cancel('No'); $mdDialog.show(confirm).then(function() { $scope.delete(item); }, function() { $mdDialog.hide(); }); } /* * Método para eliminar una entrada de la tabla noticias */ $scope.delete = function(item){ testimonios.delete(item.ID).then(function(borrado){ if(borrado == 'true'){ obtenerTodo(); alertType = MSG_ALERT.TYPE_SUCCESS; alertText = MSG_ALERT.DELETE_OK; } else { alertType = MSG_ALERT.TYPE_ERROR; alertText = MSG_ALERT.SAVE_KO; } showAlert(); }) } $scope.ver = function(item){ $scope.testimonio = item; $scope.testimonio.FECHA = new Date(item.FECHA); $scope.new = true; update = true; } /** * Método para mostrar la alerta */ var showAlert = function() { $scope.alert = { type: alertType, msg: alertText }; $scope.alerts.push($scope.alert); } /** * Método para cerrar la alerta */ $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); } /* * Método para deshabilitar la pantalla de creación de nuevos patrocinadores y volver * a la pantalla de consulta de patrocinadores. */ $scope.return = function() { $scope.new = false; $scope.disabled = true; $scope.testimonio = {}; obtenerTodo(); update = false; } /** * Método para inicializar algunas variables */ function inicialize() { // Configuración alertas alertType = ""; alertText = ""; $scope.viewby = '10'; $scope.currentPage = 4; $scope.itemsPerPage = $scope.viewby; } /** * Método para obtener todos los patrocinadores */ var obtenerTodo =function(){ //Consulta de todos los patrocinadores testimonios.getAll().then(function(data){ $scope.testimonios = data; $scope.totalItems = $scope.testimonios.length; }) } inicialize() obtenerTodo(); });
javascript
26
0.525043
138
27.172973
185
starcoderdata
<?php // 添加自定义编辑器按钮 function add_my_media_button() { echo '<span id="custom-html-transform" class="button">html尖括号转义 id="custom-inser-code" class="button">插入代码 } function appthemes_add_quicktags() { ?> <link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/include/css/custom-editor.css"> var $ = jQuery; var aLanguage = ['html', 'css', 'sass', 'scss', 'less', 'javascript', 'typescript', 'tsx', 'json', 'php', 'sql', 'http', 'nginx', 'git', 'markdown', 'yaml']; if (typeof QTags !== 'undefined') { for (var i = 0, length = aLanguage.length; i < length; i++) { QTags.addButton(aLanguage[i], aLanguage[i], '\n<pre class="language-' + aLanguage[i] + ' line-numbers"><code class="language-' + aLanguage[i] + '">\n', '\n } QTags.addButton('h2', 'h2', ' ' QTags.addButton('2-text', '2-text', '<span style="display:inline-block; width:28px;">', ' QTags.addButton('star', 'star', '<i class="iconfont icon-star c-theme">', ' QTags.addButton('arrow-right', 'arrow-right', '<i class="iconfont icon-arrow-right-f">', ' } // 添加html转换容器 $(function () { (function () { var $editor = $('<div id="custom-code-editor" style="display: none"> var $editorContent = $('<div class="custom-code-editor--content" />'); var $form = $('<form />'); var $inner = $('<textarea class="custom-code-inner" />'); var $htmlBtn = $('<button class="button button-primary button-large">HTML 转义 var $copyBtn = $('<button class="button button-primary button-large">复制代码 var $closeBtn = $('<button class="preview button">关闭 var $footerBtns = $('<div class="custom-code-footer" />').append($htmlBtn).append($copyBtn).append($closeBtn); var $hideInput = $('<textarea class="custom-code-hide" />'); aLanguage.forEach(function(item, index) { var $radio = $('<input id="custom-radio-'+ item +'" name="custom-radio" type="radio" style="vertical-align: bottom" />'); var $label = $('<label for="custom-radio-'+ item +'" style="vertical-align: middle" />'); var $span = $('<span style="margin: 0 10px 10px 0" />'); if (index === 0) $radio.attr('checked', true); $label.text(item); $radio.val(item); $span.append($radio).append($label).appendTo($form); }); $htmlBtn.click(function () { $inner.val(function () { return $(this).val().replace(/</g, '&lt;').replace(/>/g, '&gt;'); }); }); $copyBtn.click(function () { var codeLanguage = $form.serializeArray()[0].value; var code = '\n<pre class="language-' + codeLanguage + ' line-numbers"><code class="language-' + codeLanguage + '">\n' + $inner.val() + '\n console.log(code) $hideInput.val(code); $hideInput[0].select(); console.log($hideInput.val()) if (document.execCommand('Copy')) { $(this).text('复制成功'); setTimeout(function () { $copyBtn.text('复制'); }, 1500); } }); $closeBtn.click(function () { $editor.hide(); $inner.val(''); }); $editorContent.click(function (event) { event.stopPropagation(); }); $editorContent.append($hideInput).append($form).append($inner).append($footerBtns).appendTo($editor); $editor.click(function () { $closeBtn.click(); }); $('body').append($editor); $('#custom-inser-code').click(function () { $editor.show(); }); })(); $('#custom-html-transform').click(function () { $('body').append( '<div id="custom-html-transform-content">' + '<textarea name="name" rows="15" cols="100"> + '<span id="xm-transfom-btn">转换 + '<span id="xm-copy-btn">复制 + ' ); $('#custom-html-transform-content') .css({ position: 'fixed', top: 0, left: 0, zIndex: 99999, width: '100%', height: '100%', background: 'rgba(255,255,255,0.7)' }) .children('textarea').css({ resize: 'none', position: 'absolute', top: '50%', left: '50%', width: '60%', height: '300px', transform: 'translate(-50%, -50%)' }) .siblings('span').css({ position: 'absolute', top: '90%', left: '50%', width: '100px', height: '40px', borderRadius: '5px', background: '#2196F3', textAlign: 'center', lineHeight: '40px', color: '#fff', cursor: 'pointer' }); $('textarea').click(function (e) { e.stopPropagation(); }); $('#xm-transfom-btn') .css('transform', 'translateX(-115%)') .click(function (e) { e.stopPropagation(); $(this).siblings('textarea').val(function () { return $(this).val().replace(/</g, '&lt;').replace(/>/g, '&gt;'); }); }); $('#xm-copy-btn').click(function (e) { e.stopPropagation(); $(this).siblings('textarea')[0].select(); if (document.execCommand('Copy')) { $(this).text('复制成功'); } }); $('#custom-html-transform-content').click(function () { $(this).remove(); }); }); }); <?php } add_action('media_buttons', 'add_my_media_button'); add_action('admin_print_footer_scripts', 'appthemes_add_quicktags');
php
8
0.416434
189
46.713333
150
starcoderdata
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # aïvázis # orthologue # (c) 1998-2022 all rights reserved # """ Create and dump a virtual filesystem """ def test(interactive=False): # change to True to see the dump # access the package import pyre.filesystem # create a virtual filesystem fs = pyre.filesystem.virtual() # create a few nodes and insert them into the filesystem fs["/home/users/mga/tools/bin/hello"] = fs.node() fs["/home/users/mga/tools/bin/goodbye"] = fs.node() fs["/home/users/mga/tools/lib/libhello.a"] = fs.node() fs["/home/users/mga/tools/lib/libgoodbye.a"] = fs.node() fs["/home/users/mga/dv/pyre-1.0/packages/pyre/__init__.py"] = fs.node() fs["/home/users/mga/dv/pyre-1.0/packages/journal/__init__.py"] = fs.node() # dump fs.dump(interactive) # change to True to see the dump return fs # main if __name__ == "__main__": # request debugging support for the pyre.calc package pyre_debug = { "pyre.filesystem" } # skip pyre initialization since we don't rely on the executive pyre_noboot = True # do... test() # check that the nodes were all destroyed from pyre.filesystem.Node import Node # print("Node extent:", len(Node.pyre_extent)) assert len(Node.pyre_extent) == 0 # end of file
python
8
0.645723
78
26.520833
48
starcoderdata
# Copyright 2019 RedLotus # Author: RedLotus # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid import arrow from pprint import pformat from loguru import logger def mongon_opts_str(opts): url = "mongodb://{username}:{password}@{host}:{port}/{db}".format(**opts) return url def celery_worker_formatter(worker_info): """ e.g. {'celery@RedLotus': { '61421e6b-b933-412b-8f62-65425f312b69': [ 'active', { 'id': '61421e6b-b933-412b-8f62-65425f312b69', 'name': 'send_mail', 'args': '()', 'kwargs': '{}', 'type': 'send_mail', 'hostname': 'celery@RedLotus', 'time_start': 1565752238.579593, 'acknowledged': False, 'delivery_info': { 'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None }, 'worker_pid': 19696 } ] } } """ from flask_babel import get_timezone result = [] for _, task_info in worker_info.items(): for _, details in task_info.items(): state, info_dict = details tmp = {} tmp["state"] = state tmp.update(info_dict) tmp["time_start"] = arrow.get(tmp["time_start"]).to(str(get_timezone())) _id = uuid.UUID(tmp.pop("id")) tmp["id"] = _id result.append(tmp) return result def pretty_string(text, printer=logger.debug): """美化字符串输出""" for line in pformat(text).split("\n"): printer(line)
python
15
0.526998
84
28.303797
79
starcoderdata
#! /usr/bin/python import boto3, ConfigParser, os, yaml, sys script_dir = os.path.dirname(os.path.realpath(__file__)) aws_config = ConfigParser.ConfigParser() aws_config.read(script_dir + '/creds/' + sys.argv[1] + '/test_user-aws_services.ini') aws_creds = { 'aws_access_key_id': aws_config.get('DEFAULT', 'aws_access_key'), 'aws_secret_access_key': aws_config.get('DEFAULT', 'aws_secret_key'), } pdf_bucket_info = aws_config.get('DEFAULT', 'pdf_bucket').split(':', 2) pdf_storage_class = pdf_bucket_info[2] signing_events_topic_info = aws_config.get('DEFAULT', 'signing_events_topic').split(':', 1) pdf_bucket = boto3.session.Session( region_name=pdf_bucket_info[0], **aws_creds ).resource('s3').Bucket(pdf_bucket_info[1]) signing_events_topic = boto3.session.Session( region_name=signing_events_topic_info[0], **aws_creds ).resource('sns').Topic(signing_events_topic_info[1]) templates = set() for file_name in os.listdir(os.path.join(script_dir, 'profiles')): if file_name.endswith('.yaml'): profile_file = os.path.join(script_dir, 'profiles', file_name) print("Uploading: profiles/" + file_name) pdf_bucket.upload_file(profile_file, 'profiles/' + file_name, { "ServerSideEncryption": "AES256", "StorageClass": pdf_storage_class }) with open(profile_file) as stream: profile = yaml.load(stream) templates.add(profile['pdf_template']) for template in templates: print("Uploading: template/" + template) pdf_bucket.upload_file(os.path.join(script_dir, 'templates', template), 'templates/' + template, { "ServerSideEncryption": "AES256", "StorageClass": pdf_storage_class }) with open(script_dir + '/test_data.yaml') as stream: test_data = yaml.load(stream) for subscriber in test_data['sns_subscribers']: print("Subscribing: " + subscriber) subscribe_result = signing_events_topic.subscribe( Protocol='email', Endpoint=subscriber )
python
11
0.653582
102
36.054545
55
starcoderdata
@Test public void migrationFrom1To2() throws IOException { // Create the database in version 1 SupportSQLiteDatabase db = testHelper.createDatabase(TEST_DB_NAME, 1); db.execSQL("INSERT INTO app_data_table VALUES (1, '1', 2, '/flite/voices', 'today'," + " '/sim/voices', 'today')"); db.execSQL("INSERT INTO voice_table VALUES (1, 'Álfur', 'male', 'Alfur', 'is-IS', 'Íslenska(icelandic)'," + " '', 'tiro', 'now', 'now', 'http://someurl', 'downloadpath', 'API1', 'nomd5sum', 0)"); db.execSQL("INSERT INTO voice_table VALUES (3, 'Dóra', 'female', 'Dora', 'is-IS', 'Íslenska(icelandic)'," + " '', 'tiro', 'now', 'now', 'http://someurl', 'downloadpath', 'API1', 'nomd5sum', 0)"); // index is just created on name, internal_name may be redundant. That's why schema v2 was created db.execSQL("INSERT INTO voice_table VALUES (2, 'Alfur', 'male', 'Alfur', 'is-IS', 'Íslenska(icelandic)'," + " '', 'tiro', 'now', 'now', 'http://someurl', 'downloadpath', 'API1', 'nomd5sum', 0)"); db.execSQL("INSERT INTO voice_table VALUES (4, 'Dora', 'female', 'Dora', 'is-IS', 'Íslenska(icelandic)'," + " '', 'tiro', 'now', 'now', 'http://someurl', 'downloadpath', 'API1', 'nomd5sum', 0)"); db.close(); testHelper.runMigrationsAndValidate(TEST_DB_NAME, 2, true, ApplicationDb.MIGRATION_1_2); }
java
8
0.569559
115
71.65
20
inline
<?hh // strict namespace PLC\Module\Error; use Exception; use PLC\Controller\Controllable; use PLC\Controller\ViewController; use PLC\Exception\Forbidden; use PLC\Exception\NotFound; use PLC\Model\View\BaseModel; use PLC\Util\ResponseCode; use Viewable; /** * Renders error page based on thrown excpetion. */ class Controller extends ViewController implements Controllable { public function __construct(Viewable $view, private Exception $_exception) { parent::__construct($view); } protected async function _buildModel(): Awaitable { $code = ResponseCode::INTERNAL_SERVER_ERROR; $message = 'Internal Server Error'; if ($this->_exception instanceof Forbidden) { $code = ResponseCode::FORBIDDEN; $message = 'Forbidden'; } else if ($this->_exception instanceof NotFound) { $code = ResponseCode::NOT_FOUND; $message = 'Not Found'; } return new Model($this->_exception, $code, $message); } }
php
12
0.647834
78
25.55
40
starcoderdata
async fn update_airtable_record(&mut self, _record: ConferenceRoom) { // Set the building to right building link. // Get the current buildings in Airtable so we can link to it. // TODO: make this more dry so we do not call it every single damn time. let buildings = Buildings::get_from_airtable().await; // Iterate over the buildings to get the ID. for building in buildings.values() { if self.building == building.fields.name { // Set the ID. self.link_to_building = vec![building.id.to_string()]; // Break the loop and return early. break; } } }
rust
14
0.574101
80
45.4
15
inline
public void generateResolverForType(JavacNode typeNode, JavacNode annotationNode, PartialFieldsResolver annotationInstance, AccessLevel level, boolean checkForTypeLevelResolver, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { if (checkForTypeLevelResolver) { if (hasAnnotation(PartialFieldsResolver.class, typeNode)) { // The annotation will make it happen, so we can skip it. return; } } JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; if (typeDecl == null || notAClass) { annotationNode.addError("@PartialFieldsResolver is only supported on a class."); return; } // Generate list of fields JavacNode fieldsListNode = createFieldsListField(typeNode, annotationNode, annotationInstance); // Generate Constructors createConstructors(typeNode, fieldsListNode, annotationNode, annotationInstance); for (JavacNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); // Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; // Skip static fields. if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; // Skip final fields. if ((fieldDecl.mods.flags & Flags.FINAL) != 0) continue; // Skip Fields List field if ((fieldDecl.name.toString().equals(FIELDS_LIST_FIELD_NAME))) continue; generateResolverForField(field, annotationNode, level, onMethod, onParam, fieldsListNode, annotationInstance); } }
java
12
0.730791
236
43.410256
39
inline
<?php namespace AppBundle\Service; use Doctrine\ORM\EntityManager; use Symfony\Component\DependencyInjection\ContainerInterface; use AppBundle\Entity\turn; use AppBundle\Entity\turnLine; use AppBundle\Entity\turnType; use AppBundle\Entity\turnState; use AppBundle\Entity\position; use AppBundle\Entity\agent; use AppBundle\Entity\agentState; use AppBundle\Entity\agentSession; class Session { protected $em; protected $container; /** * * @param EntityManager $em * @param ContainerInterface $container */ public function __construct(EntityManager $em, ContainerInterface $container) { $this->container = $container; $this->em = $em; } /** * * @param position $position * @param agent $agent * @return agentSession */ public function open(position $position, agent $agent) { /* Se crea la sesion activa luego del logueo y de la seleccion de la posicion */ $session = new agentSession(); $session->setAgent($agent) ->setPosition($position) ->setLogin(new \DateTime('now')) ->setIsOpen(true) ; $this->em->persist($session); $this->em->flush(); /* pongo la posicion en ocupada y le pongo el usuario activo */ $position->setState($this->em->getRepository(\AppBundle\Entity\positionState::class)->findOneByDescription('busy')); $position->setActiveAgent($agent); /* marco la session como sesion activa en el agente y marco al agente como idle */ $agent->setState($this->em->getRepository(\AppBundle\Entity\agentState::class)->findOneByDescription('idle')); $agent->setActiveSession($session); $this->em->flush(); return $session; } /** * * @param agentSession $session * @return agentSession */ public function close(agentSession $session) { /* Limpio la posicion al cerrar sesion */ $this->container->get('position.service')->clean($session->getPosition()); /* Limpio sesion*/ $session->setLogout(new \DateTime('now')) ->setIsOpen(false); $session->getPosition()->setState($this->em->getRepository(\AppBundle\Entity\positionState::class)->findOneByDescription('idle')); $session->getAgent()->setActiveSession(NULL); /* reestructuro estado de turnos */ foreach ($session->getTurns() as $turn) { switch ($turn->getState()->getDescription()) { case "assigned": $turn->setState($this->em->getRepository(\AppBundle\Entity\turnState::class)->findOneByDescription('attended')); break; case "calling": $turn->setState($this->em->getRepository(\AppBundle\Entity\turnState::class)->findOneByDescription('created')); $turn->setAgent(null)->setSession(null)->setPosition(null); break; default: break; } } $this->em->flush(); return $session; } /** * * @param agentSession $session */ public function getSessionTime(agentSession $session) { $time = $session->getLogin(); echo $timestamp = $time->format('H:i:s'); dump($time->format('H:i:s')); } /** * */ public function closeActiveSessions(){ $opened_session = $this->em->getRepository(\AppBundle\Entity\agentSession::class)->findBy(['isOpen' => true]); foreach ($opened_session as $s){ $this->close($s); } } }
php
22
0.576231
138
28.286822
129
starcoderdata
def add(self): location = Location() form = Form( LocationForm().bind( request=self.request), buttons=('Save', Button(name='cancel', type='button'))) if self.request.method == "POST": data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: self.request.session.flash( _(u"Please fix the errors indicated below."), "error") else: # add location if values['parent_id'] is None: values['parent_id'] = None location = Location(**values) location.save() self.request.session.flash( _("{} {} saved").format( location.name, location.location_type), 'success') # Create new location return HTTPFound( self.request.route_url( 'locations', traverse=(location.id, 'edit'))) # return form return { 'form': form, 'location': location, 'period': self.period }
python
16
0.448441
74
31.947368
38
inline
import os import random # 打乱数据 def shuffle_data(data_list_path): with open(data_list_path, 'r', encoding='utf-8') as f: lines = f.readlines() random.shuffle(lines) print("训练数据:%d 张" % len(lines)) with open(data_list_path, 'w', encoding='utf-8') as f: f.writelines(lines) # 生成数据 def run(data_dir, train_list_path, test_list_path, label_path): f_train = open(train_list_path, 'w', encoding='utf-8') f_test = open(test_list_path, 'w', encoding='utf-8') f_label = open(label_path, 'w', encoding='utf-8') label_dict = dict() class_label = 0 class_dirs = os.listdir(data_dir) for class_dir in class_dirs: if class_dir not in label_dict: label_dict[class_dir] = class_label class_sum = 0 path = data_dir + "/" + class_dir img_paths = os.listdir(path) for img_path in img_paths: name_path = path + '/' + img_path if class_sum % 10 == 0: f_test.write(name_path + " %d" % class_label + "\n") else: f_train.write(name_path + " %d" % class_label + "\n") class_sum += 1 class_label += 1 label_str = str(label_dict).replace("'", '"') f_label.write(label_str) f_label.close() f_train.close() f_test.close() print('create data list done!') # 打乱数据 shuffle_data(train_list_path) if __name__ == '__main__': data_dir = 'dataset/images' train_list = 'dataset/train_list.txt' test_list = 'dataset/test_list.txt' label_file = 'dataset/labels.txt' run(data_dir, train_list, test_list, label_file)
python
17
0.573625
69
30.314815
54
starcoderdata
func ToMontgomery(out, in *common.Fp2) { var aRR common.FpX2 // a*R*R mulP751(&aRR, &in.A, &P751R2) // a*R mod p rdcP751(&out.A, &aRR) mulP751(&aRR, &in.B, &P751R2) rdcP751(&out.B, &aRR) }
go
8
0.617347
40
18.7
10
inline
const Crawler = require('node-web-crawler'); const { extend, uniq, flatten, some, compact } = require('lodash'); const validator = require('email-validator'); const gather = (config) => (links) => { return new Promise((resolve, reject) => { if( !config ) reject("No crawler config provided"); if( !links ) reject("No links array provided"); const list = []; console.log(`Nr of Links: ${links.length}`); const client = new Crawler(extend( config.crawler, { callback: (error, res, $) => { if( error ) reject(error); if( !res ) resolve([]); const emails = res.body.match( config.regex.email ); list.push( emails ); }, onDrain: () => { console.log("Before", list); const cleanList = clean(config, list); console.log(cleanList); console.log(`Nr of emails: ${cleanList.length}`); resolve(cleanList); } } )); client.queue( links ); }); } const clean = (config, emails) => uniq( removeBlocked( config, removeFalsePositive( compact( flatten(emails) ) ) ) ); const removeBlocked = (config, emails) => { return emails.filter(email => !some(config.rules.blocked, (domain) => email.includes(domain) ) ); }; const removeFalsePositive = (emails) => emails.filter(email => validator.validate(email)); module.exports = (config) => ({ gather: gather(config) });
javascript
23
0.574369
90
24.116667
60
starcoderdata
'use strict'; module.exports = app => { app.get('helper', '/helper', function* () { yield this.render('helper.tpl', { user: 'egg' }); }); app.get('escape', '/escape', function* () { yield this.render('escape.tpl', { user: 'egg' }); }); app.get('filters', '/nunjucks_filters', function* () { this.body = yield this.renderString('{{ helper.upper(user) }}', { user: 'egg' }); }); };
javascript
18
0.553922
85
24.5
16
starcoderdata
"""Functions required for real-time image processing.""" import cv2 import numpy as np import mediapipe as mp mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands hands = mp_hands.Hands( max_num_hands=1, min_detection_confidence=0.4, min_tracking_confidence=0.4 ) bg = None def find_biggest_contour(image): contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) biggest = np.array([]) max_area = 0 for i in contours: area = cv2.contourArea(i) if area > 50: peri = cv2.arcLength(i, True) approx = cv2.approxPolyDP(i, 0.02 * peri, True) if area > max_area and len(approx) == 4: biggest = approx max_area = area return biggest def run_avg(image, aWeight): """Set real-time background. Args: image: the background image. aWeight: accumulated weight. """ global bg # initialize the background if bg is None: bg = image.copy().astype("float") return # compute weighted average, accumulate it and update the background cv2.accumulateWeighted(image, bg, aWeight) def segment(image, threshold=25): """Segment the image. Args: image: the image to be segmented. threshold: the threshold value, 25 by default. """ global bg # find the absolute difference between background and current frame diff = cv2.absdiff(bg.astype("uint8"), image) # threshold the diff image so that we get the foreground thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1] # get the contours in the thresholded image (cnts, _) = cv2.findContours( thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) # return None, if no contours detected if len(cnts) == 0: return else: # based on contour area, get the maximum contour which is the hand segmented = max(cnts, key=cv2.contourArea) return (thresholded, segmented) def detect_hands(image, draw_image): """Return hand part of image. Args: image: the image to be processed. draw_image: image to display mediapipe skeleton. Returns: roi: image of hand. """ height, width, channels = image.shape image.flags.writeable = False results = hands.process(image) image.flags.writeable = True if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: mp_drawing.draw_landmarks( draw_image, hand_landmarks, mp_hands.HAND_CONNECTIONS ) landmarks = hand_landmarks.landmark coords_x = [] coords_y = [] for l in landmarks: coords_x.append(int(l.x * width)) coords_y.append(int(l.y * height)) bounded_hands = get_hands(image, coords_x, coords_y) return draw_image return None def get_hands(image, x, y): """Return hand part of image. Args: image: the image to be processed. x: x coordinates. y: y coordinates. Returns: roi: image of hand. """ minx = min(x) miny = min(y) maxx = max(x) maxy = max(y) final_coords = (minx-25, miny-25, maxx+25, maxy+25) top, bottom = final_coords[1], final_coords[3] right, left = final_coords[2], final_coords[0] roi = image[top:bottom, left:right+left] if roi.shape[0]*roi.shape[1] > 50: cv2.imwrite("temp_mp.png", roi) cv2.imshow("ROI", roi)
python
16
0.61434
87
25.875912
137
starcoderdata
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; using Net5.System; using Net5.System.Security.Cryptography; using Net5.System.Security.Cryptography.X509Certificates; namespace Net5.Internal.Cryptography.Pal { internal static class CertificateExtensionsCommon { public static T GetPublicKey this X509Certificate2 certificate, Predicate matchesConstraints = null) where T : AsymmetricAlgorithm { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); string oidValue = GetExpectedOidValue PublicKey publicKey = certificate.PublicKey; Oid algorithmOid = publicKey.Oid; if (oidValue != algorithmOid.Value) return null; if (matchesConstraints != null && !matchesConstraints(certificate)) return null; byte[] rawEncodedKeyValue = publicKey.EncodedKeyValue.RawData; byte[] rawEncodedParameters = publicKey.EncodedParameters.RawData; return (T)(X509Pal.Instance.DecodePublicKey(algorithmOid, rawEncodedKeyValue, rawEncodedParameters, certificate.Pal)); } public static T GetPrivateKey this X509Certificate2 certificate, Predicate matchesConstraints = null) where T : AsymmetricAlgorithm { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); string oidValue = GetExpectedOidValue if (!certificate.HasPrivateKey || oidValue != certificate.PublicKey.Oid.Value) return null; if (matchesConstraints != null && !matchesConstraints(certificate)) return null; if (typeof(T) == typeof(RSA)) return (T)(object)certificate.Pal.GetRSAPrivateKey(); if (typeof(T) == typeof(ECDsa)) return (T)(object)certificate.Pal.GetECDsaPrivateKey(); if (typeof(T) == typeof(DSA)) return (T)(object)certificate.Pal.GetDSAPrivateKey(); Debug.Fail("Expected GetExpectedOidValue() to have thrown before we got here."); throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } private static string GetExpectedOidValue where T : AsymmetricAlgorithm { if (typeof(T) == typeof(RSA)) return Oids.Rsa; if (typeof(T) == typeof(ECDsa)) return Oids.EcPublicKey; if (typeof(T) == typeof(DSA)) return Oids.Dsa; throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } }
c#
15
0.632286
130
37.658228
79
starcoderdata
func (s *ServiceSuite) TestHookCleanup(c *gc.C) { // Manually delete the existing control point. s.ts.RegisterControlPoint("foo", nil) // Register a new hook and ensure it works. cleanup := s.ts.RegisterControlPoint("foo", functionControlHook) err := s.ts.foo("cleanuptest", false) c.Assert(err, gc.IsNil) c.Assert(s.ts.label, gc.Equals, "cleanuptest") // Use the cleanup func to remove the hook and check the result. cleanup() err = s.ts.foo("again", false) c.Assert(err, gc.IsNil) c.Assert(s.ts.label, gc.Equals, "cleanuptest") // Ensure that only the specified hook was removed and the other remaining one still works. err = s.ts.bar() c.Assert(err, gc.IsNil) c.Assert(s.ts.label, gc.Equals, "foobar") }
go
8
0.713693
92
37.105263
19
inline
//>>built define("dijit/_TemplatedMixin",["dojo/cache","dojo/_base/declare","dojo/dom-construct","dojo/_base/lang","dojo/on","dojo/sniff","dojo/string","./_AttachMixin"],function(_1,_2,_3,_4,on,_5,_6,_7){ var _8=_2("dijit._TemplatedMixin",_7,{templateString:null,templatePath:null,_skipNodeCache:false,searchContainerNode:true,_stringRepl:function(_9){ var _a=this.declaredClass,_b=this; return _6.substitute(_9,this,function(_c,_d){ if(_d.charAt(0)=="!"){ _c=_4.getObject(_d.substr(1),false,_b); } if(typeof _c=="undefined"){ throw new Error(_a+" template:"+_d); } if(_c==null){ return ""; } return _d.charAt(0)=="!"?_c:_c.toString().replace(/"/g,"&quot;"); },this); },buildRendering:function(){ if(!this._rendered){ if(!this.templateString){ this.templateString=_1(this.templatePath,{sanitize:true}); } var _e=_8.getCachedTemplate(this.templateString,this._skipNodeCache,this.ownerDocument); var _f; if(_4.isString(_e)){ _f=_3.toDom(this._stringRepl(_e),this.ownerDocument); if(_f.nodeType!=1){ throw new Error("Invalid template: "+_e); } }else{ _f=_e.cloneNode(true); } this.domNode=_f; } this.inherited(arguments); if(!this._rendered){ this._fillContent(this.srcNodeRef); } this._rendered=true; },_fillContent:function(_10){ var _11=this.containerNode; if(_10&&_11){ while(_10.hasChildNodes()){ _11.appendChild(_10.firstChild); } } }}); _8._templateCache={}; _8.getCachedTemplate=function(_12,_13,doc){ var _14=_8._templateCache; var key=_12; var _15=_14[key]; if(_15){ try{ if(!_15.ownerDocument||_15.ownerDocument==(doc||document)){ return _15; } } catch(e){ } _3.destroy(_15); } _12=_6.trim(_12); if(_13||_12.match(/\$\{([^\}]+)\}/g)){ return (_14[key]=_12); }else{ var _16=_3.toDom(_12,doc); if(_16.nodeType!=1){ throw new Error("Invalid template: "+_12); } return (_14[key]=_16); } }; if(_5("ie")){ on(window,"unload",function(){ var _17=_8._templateCache; for(var key in _17){ var _18=_17[key]; if(typeof _18=="object"){ _3.destroy(_18); } delete _17[key]; } }); } return _8; });
javascript
24
0.63409
194
22.827586
87
starcoderdata
package uimevents import ( "encoding/json" "github.com/xopenapi/uim-api-go" ) type MessageActionResponse struct { ResponseType string `json:"response_type"` ReplaceOriginal bool `json:"replace_original"` Text string `json:"text"` } type MessageActionEntity struct { ID string `json:"id"` Domain string `json:"domain"` Name string `json:"name"` } type MessageAction struct { Type string `json:"type"` Actions []uim.AttachmentAction `json:"actions"` CallbackID string `json:"callback_id"` Team MessageActionEntity `json:"team"` Channel MessageActionEntity `json:"channel"` User MessageActionEntity `json:"user"` ActionTimestamp json.Number `json:"action_ts"` MessageTimestamp json.Number `json:"message_ts"` AttachmentID json.Number `json:"attachment_id"` Token string `json:"token"` Message uim.Message `json:"message"` OriginalMessage uim.Message `json:"original_message"` ResponseURL string `json:"response_url"` TriggerID string `json:"trigger_id"` }
go
8
0.58216
66
33.540541
37
starcoderdata
import sys d, n = [], {} for i in sys.stdin: if i.rstrip() == "": break a, b = map(str, i.split()) d.append([a, b]) if a in n: n[a] += 1 else: n[a] = 1 d = sorted(d, key=lambda x: (x[1], x[0])) for k, v in d: if n[k] > 1: print(k, v) else: print(k)
python
9
0.45614
41
14
19
starcoderdata
void rlc_menu_action(rlc_console c, menu_data *data) { RlcData b = rlc_get_data(c); if ( !data || !data->magic == MEN_MAGIC ) return; if ( data->menu ) /* rlc_insert_menu_item() */ { HMENU popup; if ( (popup = findPopup(b, data->menu, NULL)) ) data->rc = insertMenu(popup, data->label, data->before); else data->rc = FALSE; } else /* insert_menu() */ { HMENU mb; HWND hwnd = rlc_hwnd(c); if ( !(mb = GetMenu(hwnd)) ) { data->rc = FALSE; return; } if ( !findPopup(b, data->label, NULL) ) /* already there */ { MENUITEMINFO info; int bid = -1; if ( data->before ) findPopup(b, data->before, &bid); memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_TYPE|MIIM_SUBMENU; info.fType = MFT_STRING; info.hSubMenu = CreatePopupMenu(); info.dwTypeData = (TCHAR *)data->label; info.cch = (int)_tcslen(data->label); InsertMenuItem(mb, bid, TRUE, &info); /* force redraw; not automatic! */ DrawMenuBar(hwnd); } data->rc = TRUE; } }
c
14
0.552561
63
23.217391
46
inline
'use strict'; //// IMPORTS var del = require('del'), util = require('util'); var utils = require('./utils'); //// TASKS const OPTIONS = { // String Gulp will display for the generated task. name: 'clean', // String Gulp will display in help output. description: 'Remove generated files.', // Paths to delete. paths: ['tmp', 'dist'] }; // Creates a task which deletes the specified directories. function generateCleanTask(overrides) { var options = utils.merge(OPTIONS, overrides); var task = function clean() { return del(options.paths); }; task.displayName = options.name; task.description = options.description; return task; } //// EXPORTS module.exports = generateCleanTask;
javascript
10
0.672109
58
17.846154
39
starcoderdata
wait.js /* auto wait - https://schedulebuilder.yorku.ca */ /* https://github.com/WuWaA/York-University-Course-Autotaker */ /* * AUTHOR: WuWaA (GitHub) * LICENSE: MIT License * 转载/使用/修改,须保留此信息 */ var timer = ( 60000 ); // 60000 -> 60 seconds -> 1 minute // console.log(timer); var vsb_url = "https://schedulebuilder.yorku.ca/vsb/criteria.jsp?term=2020102119&locs=any&course_0_0=LE-EECS-3101-3.00-EN-&cs_0_0=--2020070_E39F01-E39F02-&ca_0_0=0"; // The URL in Visual Schedule Builder, details in readme: https://github.com/WuWaA/York-University-Course-Autotaker // 虚拟选课VSB的URL, 说明详见:https://github.com/WuWaA/York-University-Course-Autotaker setTimeout( function () { if ( $( ".seatText" ).length > 0 ) { console.log( '[' + new Date().toTimeString() + '] Case 1' ); autojump(); } else { console.log( '[' + new Date().toTimeString() + '] Case 2' ); setTimeout( function () { autoreload(); }, timer ); } }, 5000 ); function autojump () { window.location.href = "https://wrem.sis.yorku.ca/Apps/WebObjects/REM.woa/wa/DirectAction/rem"; } function autoreload () { window.location.href = vsb_url; }
javascript
18
0.635433
165
31.5
38
starcoderdata
<?php /** * This file is part of the Tarantool Client package. * * (c) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Tarantool\Client\Tests\Integration\Connection; use Tarantool\Client\Exception\CommunicationFailed; use Tarantool\Client\Exception\InvalidGreeting; use Tarantool\Client\Tests\Integration\ClientBuilder; use Tarantool\Client\Tests\Integration\FakeServer\FakeServerBuilder; use Tarantool\Client\Tests\Integration\FakeServer\Handler\WriteHandler; use Tarantool\Client\Tests\Integration\TestCase; final class ParseGreetingTest extends TestCase { /** * @dataProvider \Tarantool\Client\Tests\GreetingDataProvider::provideGreetingsWithInvalidServerName */ public function testParseGreetingWithInvalidServerName(string $greeting) : void { $clientBuilder = ClientBuilder::createFromEnvForTheFakeServer(); FakeServerBuilder::create(new WriteHandler($greeting)) ->setUri($clientBuilder->getUri()) ->start(); $client = $clientBuilder->build(); try { $client->ping(); } catch (CommunicationFailed $e) { self::assertSame('Unable to read greeting.', $e->getMessage()); return; } catch (InvalidGreeting $e) { self::assertSame('Unable to recognize Tarantool server.', $e->getMessage()); return; } self::fail(); } /** * @dataProvider \Tarantool\Client\Tests\GreetingDataProvider::provideGreetingsWithInvalidSalt */ public function testParseGreetingWithInvalidSalt(string $greeting) : void { $clientBuilder = ClientBuilder::createFromEnvForTheFakeServer(); FakeServerBuilder::create(new WriteHandler($greeting)) ->setUri($clientBuilder->getUri()) ->start(); $client = $clientBuilder->build(); $this->expectException(InvalidGreeting::class); $this->expectExceptionMessage('Unable to parse salt.'); $client->ping(); } }
php
15
0.678322
104
29.211268
71
starcoderdata
<?php include('header.php'); include('sidebardosen.php'); ?> <div class="container-fluid"> <div class="card text-center"> <h2 class="card-header bg-gray-100 text-gray-800">Selamat Datang!!! <div class="card-body"> <blockquote class="blockquote mb-0"> datang <?php echo $nama; ?> di aplikasi Absensi Online Mahasiswa berbasis web. Ini adalah halaman khusus dosen pengampu mata kuliah. <?php include('footer.php'); ?>
php
5
0.594512
163
28.863636
22
starcoderdata
// <copyright file="EditorCells.xaml.cs" company="Traced-Ideas, Czech republic"> // Copyright (c) 1990-2021 All Right Reserved // // // // // of Largo Composer using LargoSharedClasses.Music; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace EditorPanels.Detail { /// /// Interact logic. /// public partial class EditorCells { #region Fields /// /// Singleton variable. /// private static EditorCells singleton; #endregion #region Constructors /// /// Initializes a new instance of the <see cref="EditorCells"/> class. /// public EditorCells() { this.InitializeComponent(); singleton = this; } #endregion #region Static properties /// /// Gets the InspectorHeader Singleton. /// /// Property description. public static EditorCells Singleton { get { Contract.Ensures(Contract.Result != null); if (singleton == null) { throw new InvalidOperationException("Singleton EditorCells is null."); } return singleton; } } #endregion #region Properties /// /// Gets or sets the units. /// /// /// The units. /// public List Elements { get; set; } #endregion /// /// Handles the SelectionChanged event of the dataGridStatus control. /// /// <param name="sender">The source of the event. /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data. private void DataGridStatus_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { } /// /// Handles the MouseDoubleClick event of the dataGridStatus control. /// /// <param name="sender">The source of the event. /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data. private void DataGridStatus_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (this.DataGridStatus.SelectedItem is MusicalElement selectedElement) { //// var w = WindowManager.OpenWindow("LargoEditor", "LineMelodicEdit", null); //// w.LoadData(); } } } }
c#
18
0.580034
139
31.472527
91
starcoderdata
/* oclif command to burn a specific quantity of Avalanche native tokens. Burning tokens is exactly the same as sending tokens without change. The only difference is that the output indicates the difference. e.g. If you have 100 tokens and want to burn 10, you use the 100 token UTXO as input, and set the output with a quantity of 90. That will effectively burn 10 tokens. */ 'use strict' const GetAddress = require('./get-address') const UpdateBalances = require('./update-balances') const AppUtils = require('../util') const Send = require('./send') const SendTokens = require('./send-tokens') const { Avalanche, BinTools, BN } = require('avalanche') const avm = require('avalanche/dist/apis/avm') // Used for debugging and error reporting. const util = require('util') util.inspect.defaultOptions = { depth: 2 } const { Command, flags } = require('@oclif/command') class BurnTokens extends Command { constructor (argv, config) { super(argv, config) // _this = this // this.ava = new Avalanche(globalConfig.AVAX_IP, parseInt(globalConfig.AVAX_PORT)) this.ava = new Avalanche('api.avax.network', 443, 'https') this.bintools = BinTools.getInstance() this.xchain = this.ava.XChain() this.avm = avm this.BN = BN // Encapsulate local libraries for each mocking for unit tests. this.appUtils = new AppUtils() this.updateBalances = new UpdateBalances() this.send = new Send() this.sendTokens = new SendTokens() this.getAddress = new GetAddress() } async run () { try { const { flags } = this.parse(BurnTokens) const name = flags.name // Name of the wallet. const burnQty = flags.qty // Amount to send in token. const tokenId = flags.tokenId // token ID. if (!flags.memo) { flags.memo = '' } // Open the wallet data file. const filename = `${__dirname}/../../wallets/${name}.json` let walletInfo = this.appUtils.openWallet(filename) // Update balances before sending. walletInfo = await this.updateBalances.updateBalances(flags) // Get a list of token UTXOs from the wallet for this token. const tokenUtxos = this.sendTokens.getTokenUtxos(tokenId, walletInfo) // Instatiate the Send class so this function can reuse its selectUTXO() code. const avaxUtxo = await this.send.selectUTXO(0.001, walletInfo.avaxUtxos) // Exit if there is no UTXO big enough to fulfill the transaction. if (!avaxUtxo.amount) { this.log('Could not find a UTXO big enough for this transaction. More avax needed.') throw new Error('Could not find a UTXO big enough for this transaction') } // Generate a new address, for sending change to. const getAddress = new GetAddress() const changeAddress = await getAddress.getAvalancheAddress(filename) const tx = await this.burnTokens( avaxUtxo, tokenUtxos, burnQty, changeAddress, walletInfo, flags.memo ) const txid = await this.appUtils.broadcastAvaxTx(tx) this.appUtils.displayAvaxTxid(txid) return txid } catch (err) { console.log('Error in burn-tokens.js/run(): ') console.log(err) return 0 } } // Generates the avalanche transaction, ready to broadcast to network. async burnTokens (avaxUtxo, tokenUtxos, burnQty, changeAddress, walletInfo, memo) { try { changeAddress = this.xchain.parseAddress(changeAddress) if (!tokenUtxos || tokenUtxos.length === 0) { throw new Error('At least one utxo with tokens must be provided') } // Generate a KeyChain for the wallet with the avax to pay the fee let xkeyChain = this.appUtils.avalancheChangeAddress(walletInfo, avaxUtxo.hdIndex) // add all the keys for the addresses with tokens for (let i = 0; i < tokenUtxos.length; i++) { const thisUTXO = tokenUtxos[i] const kc = this.appUtils.avalancheChangeAddress(walletInfo, thisUTXO.hdIndex) xkeyChain = xkeyChain.union(kc) } // encode memo const memoBuffer = Buffer.from(memo) const avaxIDBuffer = await this.xchain.getAVAXAssetID() // calculate remainder in navax const fee = this.xchain.getDefaultTxFee() const utxoBalance = new this.BN(avaxUtxo.amount) const remainder = utxoBalance.sub(fee) if (remainder.isNeg()) { throw new Error('Not enough avax in the selected utxo') } // add token utxos as input let tokenAmount = new this.BN(0) const assetID = tokenUtxos[0].assetID const assetIDBuffer = this.bintools.cb58Decode(assetID) const inputs = tokenUtxos.reduce((inputCol, utxo) => { const utxoAddr = this.xchain.parseAddress(walletInfo.addresses[utxo.hdIndex]) const amount = new this.BN(utxo.amount) tokenAmount = tokenAmount.add(amount) const tokenTransferInput = new this.avm.SECPTransferInput(amount) tokenTransferInput.addSignatureIdx(0, utxoAddr) const tokenTxInput = new this.avm.TransferableInput( this.bintools.cb58Decode(utxo.txid), Buffer.from(utxo.outputIdx, 'hex'), assetIDBuffer, tokenTransferInput ) inputCol.push(tokenTxInput) return inputCol }, []) // add avax utxo as input const transferInput = new this.avm.SECPTransferInput(utxoBalance) const avaxAddr = this.xchain.parseAddress(walletInfo.addresses[avaxUtxo.hdIndex]) transferInput.addSignatureIdx(0, avaxAddr) const txInput = new this.avm.TransferableInput( this.bintools.cb58Decode(avaxUtxo.txid), Buffer.from(avaxUtxo.outputIdx, 'hex'), avaxIDBuffer, transferInput ) inputs.push(txInput) // calculate remainder token quantity after burning const { denomination } = await this.xchain.getAssetDescription(assetIDBuffer) burnQty = burnQty * Math.pow(10, denomination) const burnBN = new this.BN(burnQty) const remainderTokens = tokenAmount.sub(burnBN) if (remainderTokens.isNeg()) { throw new Error('Not enough tokens in the selected utxos') } // get the desired outputs for the transaction if any const outputs = [] if (!remainderTokens.isZero()) { const tokenTransferOutput = new this.avm.SECPTransferOutput( remainderTokens, [changeAddress] ) const tokenTransferableOutput = new this.avm.TransferableOutput( assetIDBuffer, tokenTransferOutput ) outputs.push(tokenTransferableOutput) } // if there's avax remaining after the tx, add them to the outputs if (!remainder.isZero()) { const avaxTransferOutput = new this.avm.SECPTransferOutput( remainder, [changeAddress] ) const avaxTransferableOutput = new this.avm.TransferableOutput( avaxIDBuffer, avaxTransferOutput ) // Add the AVAX output = the avax input minus the fee outputs.push(avaxTransferableOutput) } // Build the transcation const baseTx = new this.avm.BaseTx( this.ava.getNetworkID(), this.bintools.cb58Decode(this.xchain.getBlockchainID()), outputs, inputs, memoBuffer ) const unsignedTx = new this.avm.UnsignedTx(baseTx) return unsignedTx.sign(xkeyChain) } catch (err) { console.log('Error in send-token.js/sendTokens()') throw err } } // Validate the proper flags are passed in. validateFlags (flags) { // console.log(`flags: ${JSON.stringify(flags, null, 2)}`) // Exit if wallet not specified. const name = flags.name if (typeof name !== 'string' || !name.length) { throw new Error('You must specify a wallet with the -n flag.') } const qty = flags.qty if (isNaN(Number(qty))) { throw new Error('You must specify a quantity of tokens with the -q flag.') } const tokenId = flags.tokenId if (typeof tokenId !== 'string' || !tokenId.length) { throw new Error('You must specifcy the SLP token ID') } return true } } BurnTokens.description = 'Burn Avalanche native tokens.' BurnTokens.flags = { name: flags.string({ char: 'n', description: 'Name of wallet' }), tokenId: flags.string({ char: 't', description: 'Token ID' }), memo: flags.string({ char: 'm', description: 'Memo field' }), qty: flags.string({ char: 'q', decription: 'Quantity of tokens to send' }) } module.exports = BurnTokens
javascript
20
0.656652
92
32.414729
258
starcoderdata
#pragma once #include "../mem/mem.hpp" #include "../mem_protect/mem_protect.hpp" namespace shared::hook { struct hook_t { /// /// Creates default hook object /// hook_t() = default; /// /// Sets up a hook with given object pointer /// /// <param name="ptr">Address of object from desired vtable hook_t( uintptr_t ptr ) : m_vtable( reinterpret_cast< uintptr_t** >( ptr ) ), m_table_length( 0 ), m_orig( nullptr ), m_replace( nullptr ) {}; /// /// Sets up a hook with given object pointer /// /// <param name="ptr">Address of object from desired vtable hook_t( void* ptr ) : m_vtable( reinterpret_cast< uintptr_t** >( ptr ) ), m_table_length( 0 ), m_orig( nullptr ), m_replace( nullptr ) {}; /// /// Sets up a hook with given object pointer /// /// <param name="ptr">Address of object from desired vtable hook_t( address_t ptr ) : m_vtable( ptr.cast ), m_table_length( 0 ), m_orig( nullptr ), m_replace( nullptr ) {}; /// /// Sets up hook and replaces the vtable with new one /// /// true if hooks was successfully initialized bool init() { if ( !m_vtable ) return false; INIT_MEM_PROTECT_RW( m_vtable, sizeof( uintptr_t ) ); /// Store old vtable m_orig = *m_vtable; m_table_length = mem::get_vtable_length( m_orig ); /// Either faulty vtable or function fail if ( !m_table_length ) return false; /// Allocate new vtable ( +1 for RTTI ) m_replace = std::make_unique m_table_length + 1 ); /// instantiate all values with 0 std::memset( m_replace.get(), NULL, m_table_length * sizeof( uintptr_t ) + sizeof( uintptr_t ) ); /// The following two memcpy's could be just made /// into 1 call but for demonstration purposes /// I'll leave it like that /// Copy old table /// Skip first 4 bytes to later insert RTTI there std::memcpy( &m_replace[ 1 ], m_orig, m_table_length * sizeof( uintptr_t ) ); /// Copy RTTI std::memcpy( m_replace.get(), &m_orig[ -1 ], sizeof( uintptr_t ) ); /// Apply new vtable, again skipping the first 4 /// bytes since that's where the RTTI is now located *m_vtable = &m_replace[ 1 ]; return true; } /// /// Hooks a given index /// /// <param name="index"> /// Index of the function that should be replaced. /// Keep in mind that you have to +1 the index since /// In the new vtable the RTTI is stored at the first index /// and thus all indexes are shifted by 1 /// /// <param name="replace_function">The function which will be called instead of the original template< typename t > void hook( const uint16_t index, t replace_function ) { /// Is index out of bounds? if ( index < 0 || index > m_table_length ) return; m_replace[ index + 1 ] = reinterpret_cast< uintptr_t >( replace_function ); } /// /// Gets a pointer to the original function with a given index /// /// <param name="index">Index of the function that should be retrieved /// the function pointer casted into a given function type template< typename t > t get_original( const uint16_t index ) { /// Is index out of bounds? if ( index < 0 || index > m_table_length ) return nullptr; return reinterpret_cast< t >( m_orig[ index ] ); } /// /// Unhooks specific index /// /// <param name="index">Index of the function that should be unhooked void unhook( const uint16_t index ) { /// Is index out of bounds? if ( index < 0 || index > m_table_length ) return; m_replace[ index + 1 ] = m_orig[ index ]; } /// /// Restore old vtable and thus unhook all functions /// void unhook() { /// Check if it was already restored if ( !m_orig ) return; INIT_MEM_PROTECT_RW( m_vtable, sizeof( uintptr_t ) ); *m_vtable = m_orig; /// Prevent double unhook m_orig = nullptr; } /// /// The vtable that is being modified /// uintptr_t** m_vtable; /// /// Amount of all functions within the vtable /// uint16_t m_table_length; /// /// Pointer to the original vtable /// uintptr_t* m_orig; /// /// New custom vtable /// std::unique_ptr m_replace; }; }
c++
16
0.616738
144
26.579882
169
starcoderdata
public function widget( $args, $instance ) { if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } // Prepare options. $title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'Editors', 'wp-team-list' ); $role = ! empty( $instance['role'] ) ? $instance['role'] : 'editor'; $show_link = isset( $instance['show_link'] ) ? $instance['show_link'] : false; $page_link = isset( $instance['page_link'] ) ? absint( $instance['page_link'] ) : 0; $number = ! empty( $instance['number'] ) ? max( 1, absint( $instance['number'] ) ) : 3; /** * Filter the team list widget title. * * @param string $title The widget title. * @param array $instance An array of the widget's settings. * @param string $id_base The widget ID. */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); // A filter for all instances of this widget. $team_query_args = [ 'role' => $role, 'number' => $number, ]; echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput if ( $title ) { echo $args['before_title'] . $title . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput } ?> <div class="wp-team-list-widget-content"> <?php echo wp_team_list()->render( $team_query_args ); // phpcs:ignore WordPress.Security.EscapeOutput if ( $show_link && $page_link ) { printf( '<a href="%s" class="show-all">%s</a>', esc_url( get_permalink( $page_link ) ), esc_html__( 'Show all team members', 'wp-team-list' ) ); } ?> </div> <?php echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput }
php
14
0.590882
110
34.208333
48
inline