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 |
---|---|---|---|---|---|---|---|
def test_does_not_complete_pending_disconnect_op(self, mocker, stage):
# Set a pending disconnect operation
op = pipeline_ops_base.DisconnectOperation(callback=mocker.MagicMock())
stage.run_op(op)
assert not op.completed
assert stage._pending_connection_op is op
# Trigger connect completion
stage.transport.on_mqtt_connected_handler()
# Disconnect operation was NOT completed
assert not op.completed
assert stage._pending_connection_op is op
|
python
| 10 | 0.685115 | 79 | 39.384615 | 13 |
inline
|
#
# -------------------------------------------------------------------------
# Copyright (c) 2018 Intel Corporation Intellectual Property
#
# 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.
#
# -------------------------------------------------------------------------
#
"""Test case for RootController /"""
import json
from conductor import version
from conductor.tests.unit.api import base_api
class TestRoot(base_api.BaseApiTest):
def test_get_index(self):
actual_response = self.app.get('/')
req_json_file = './conductor/tests/unit/api/controller/versions.json'
expected_response = json.loads(open(req_json_file).read())
versions = expected_response.get('versions')
for version_obj in versions:
version_obj['version'] = "of-has:{}".format(version.version_info.version_string())
self.assertEqual(200, actual_response.status_int)
self.assertJsonEqual(expected_response,
json.loads(actual_response.body.decode()))
|
python
| 14 | 0.627337 | 94 | 37.775 | 40 |
starcoderdata
|
package org.hy.xflow.engine.dao;
import java.util.List;
import org.hy.common.xml.annotation.XType;
import org.hy.common.xml.annotation.Xjava;
import org.hy.common.xml.annotation.Xparam;
import org.hy.common.xml.annotation.Xsql;
import org.hy.xflow.engine.bean.FlowInfo;
import org.hy.xflow.engine.bean.FlowProcess;
/**
* 工作流模板表的DAO
*
* @author ZhengWei(HY)
* @createDate 2018-04-25
* @version v1.0
* v2.0 2019-09-12 添加:支持多路并行路由的流程
*/
@Xjava(id="FlowInfoDAO" ,value=XType.XSQL)
public interface IFlowInfoDAO
{
/**
* 查询某一工作流模板下的所有活动的工作流实例。
*
* @author ZhengWei(HY)
* @createDate 2019-08-29
* @version v1.0
*
* @param i_TemplateID 工作流模板ID
* @return
*/
@Xsql(id="XSQL_XFlow_FlowInfo_QueryByTemplateID_ForActivity")
public List queryActivitys(@Xparam(id="flowTemplateID") String i_TemplateID);
/**
* 工作流实例ID,查询工作流实例(活动及历史的均查询)
*
* @author ZhengWei(HY)
* @createDate 2018-04-27
* @version v1.0
*
* @param i_WorkID 工作流实例ID
* @return
*/
@Xsql(id="XSQL_XFlow_FlowInfo_QueryByWorkID_ServiceDataID" ,returnOne=true)
public FlowInfo queryByWorkID(@Xparam(id="workID" ,notNull=true) String i_WorkID);
/**
* 按第三方使用系统的业务数据ID,查询工作流实例
*
* @author ZhengWei(HY)
* @createDate 2018-04-25
* @version v1.0
*
* @param i_ServiceDataID 第三方使用系统的业务数据ID。即支持用第三方ID也能找到工作流信息
* @return
*/
@Xsql(id="XSQL_XFlow_FlowInfo_QueryByWorkID_ServiceDataID" ,returnOne=true)
public FlowInfo queryByServiceDataID(@Xparam(id="serviceDataID" ,notNull=true) String i_ServiceDataID);
/**
* 创建的工作流实例,当前活动节点为 "开始" 节点。
*
* @author ZhengWei(HY)
* @createDate 2018-04-26
* @version v1.0
*
* @param i_FlowInfo
* @param i_Process
* @return
*/
@Xsql("GXSQL_Flow_Create")
public boolean createFlow(@Xparam("flow") FlowInfo i_FlowInfo
,@Xparam("process") FlowProcess i_Process);
/**
* 工作流流转,并更新前一个流转信息。
*
* @author ZhengWei(HY)
* @createDate 2018-05-07
* @version v1.0
*
* @param i_Flow 工作流实例对象
* @param i_Process 新流转的过程集合信息(分单时会有多个,正常情况下均只有一个元素)
* @param i_Previous 前一个流转的过程信息
* @return
*/
@Xsql("GXSQL_Flow_ToNext")
public boolean toNext(@Xparam("flow") FlowInfo i_Flow
,@Xparam("process") FlowProcess i_Process
,@Xparam("previous") FlowProcess i_Previous);
/**
* 分单多路的工作流流转,并更新前一个流转信息。
*
* @author ZhengWei(HY)
* @createDate 2019-09-16
* @version v1.0
*
* @param i_Flow 工作流实例对象
* @param i_ProcessList 新流转的过程集合信息(分单时会有多个,正常情况下均只有一个元素)
* @param i_Previous 前一个流转的过程信息
* @return
*/
@Xsql("GXSQL_Flow_ToNext_Split")
public boolean toNextSplit(@Xparam("flow") FlowInfo i_Flow
,@Xparam("processList") List i_ProcessList
,@Xparam("previous") FlowProcess i_Previous);
/**
* 分单多路后的汇总,工作流流转,并更新前一个流转信息
*
* @author ZhengWei(HY)
* @createDate 2019-09-16
* @version v1.0
*
* @param i_Flow 工作流实例对象
* @param i_Process 新流转的过程集合信息(分单时会有多个,正常情况下均只有一个元素)
* @param i_Previous 前一个流转的过程信息
* @return
*/
@Xsql("GXSQL_Flow_ToNext_Summary")
public boolean toNextSummary(@Xparam("flow") FlowInfo i_Flow
,@Xparam("process") FlowProcess i_Process
,@Xparam("previous") FlowProcess i_Previous);
/**
* 工作流实例ID,全流转结束后转历史
*
* @author ZhengWei(HY)
* @createDate 2018-05-11
* @version v1.0
*
* @param i_WorkID 工作流实例ID
* @return
*/
@Xsql("GXSQL_Flow_ToHistory")
public boolean toHistory(@Xparam(id="workID" ,notNull=true) String i_WorkID);
/**
* 按第三方使用系统的业务数据ID,全流转结束后转历史
*
* @author ZhengWei(HY)
* @createDate 2018-05-11
* @version v1.0
*
* @param i_ServiceDataID 第三方使用系统的业务数据ID。即支持用第三方ID也能找到工作流信息
* @return
*/
@Xsql("GXSQL_Flow_ToHistory")
public boolean toHistoryByServiceDataID(@Xparam(id="serviceDataID" ,notNull=true) String i_ServiceDataID);
}
|
java
| 11 | 0.561388 | 110 | 25.045198 | 177 |
starcoderdata
|
package com.haumea.gitanalyzer.gitlab;
public class CommentType {
private String startType;
private String endType;
public CommentType(String startType, String endType) {
this.startType = startType;
this.endType = endType;
}
public String getStartType() {
return startType;
}
public void setStartType(String startType) {
this.startType = startType;
}
public String getEndType() {
return endType;
}
public void setEndType(String endType) {
this.endType = endType;
}
}
|
java
| 8 | 0.643234 | 58 | 20.074074 | 27 |
starcoderdata
|
void
finalize_return_check(dcontext_t *dcontext, fragment_t *f)
{
byte *start_pc = (byte *) FCACHE_ENTRY_PC(f);
byte *end_pc = fragment_body_end_pc(dcontext, f);
byte *pc, *prev_pc;
int leas_next = 0;
instr_t instr;
instr_init(dcontext, &instr);
LOG(THREAD, LOG_ALL, 3, "finalize_return_check\n");
SELF_PROTECT_CACHE(dcontext, f, WRITABLE);
/* must fix up indirect jmp */
pc = start_pc;
do {
prev_pc = pc;
instr_reset(dcontext, &instr);
pc = decode(dcontext, pc, &instr);
ASSERT(instr_valid(&instr)); /* our own code! */
if (leas_next == 2) {
loginst(dcontext, 3, &instr, "\tlea 2");
if (instr_get_opcode(&instr) == OP_lea) {
opnd_t op = instr_get_src(&instr, 0);
int scale = opnd_get_scale(op);
DEBUG_DECLARE(byte *nxt_pc;)
/* put in pc of instr after jmp: jmp is 2 bytes long */
instr_set_src(&instr, 0,
opnd_create_base_disp(REG_ECX, REG_ECX, scale,
(int)(pc+2), OPSZ_lea));
DEBUG_DECLARE(nxt_pc = ) instr_encode(dcontext, &instr, prev_pc);
ASSERT(nxt_pc != NULL);
}
leas_next = 0;
}
if (leas_next == 1) {
loginst(dcontext, 3, &instr, "\tlea 1");
if (instr_get_opcode(&instr) == OP_lea)
leas_next = 2;
else
leas_next = 0;
}
/* we don't allow program to use sse, so pextrw/pinsrw are all ours */
if (leas_next == 0 &&
instr_get_opcode(&instr) == OP_pextrw &&
opnd_is_reg(instr_get_src(&instr, 0)) &&
opnd_get_reg(instr_get_src(&instr, 0)) == REG_XMM7 &&
opnd_is_immed_int(instr_get_src(&instr, 1)) &&
opnd_get_immed_int(instr_get_src(&instr, 1)) == 7) {
loginst(dcontext, 3, &instr, "\tfound pextrw");
leas_next = 1;
}
else if (leas_next == 0 &&
instr_get_opcode(&instr) == OP_pinsrw &&
opnd_is_reg(instr_get_dst(&instr, 0)) &&
opnd_get_reg(instr_get_dst(&instr, 0)) == REG_XMM7 &&
opnd_is_immed_int(instr_get_src(&instr, 1)) &&
opnd_get_immed_int(instr_get_src(&instr, 1)) == 7) {
loginst(dcontext, 3, &instr, "\tfound pinsrw");
leas_next = 1;
}
} while (pc < end_pc);
instr_free(dcontext, &instr);
SELF_PROTECT_CACHE(dcontext, f, READONLY);
}
|
c
| 18 | 0.492076 | 81 | 38.212121 | 66 |
inline
|
#!/usr/bin/env python
# The pyfftw namespace
''' The core of ``pyfftw`` consists of the :class:`FFTW` class,
:ref:`wisdom functions <wisdom_functions>` and a couple of
:ref:`utility functions <utility_functions>` for dealing with aligned
arrays.
This module represents the full interface to the underlying `FFTW
library <http://www.fftw.org/>`_. However, users may find it easier to
use the helper routines provided in :mod:`pyfftw.builders`. Default values
used by the helper routines can be controlled as via
:ref:`configuration variables <configuration_variables>`.
'''
import os
from .pyfftw import (
FFTW,
export_wisdom,
import_wisdom,
forget_wisdom,
simd_alignment,
n_byte_align_empty,
n_byte_align,
is_n_byte_aligned,
byte_align,
is_byte_aligned,
empty_aligned,
ones_aligned,
zeros_aligned,
next_fast_len,
_supported_types,
_supported_nptypes_complex,
_supported_nptypes_real,
_all_types_human_readable,
_all_types_np,
_threading_type
)
from . import config
from . import builders
from . import interfaces
# clean up the namespace
del builders.builders
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
python
| 6 | 0.667424 | 74 | 24.882353 | 51 |
research_code
|
using MCPE.AlphaServer.Game;
using MCPE.AlphaServer.Utils;
using System;
using System.Collections.Generic;
using System.Text;
namespace MCPE.AlphaServer.Packets {
public class ExplodePacket : RakPacket {
public float X, Y, Z;
public float Radius;
public int Count;
public byte Records;
public byte _Counts;
public byte _Records;
public override byte[] Serialize() => throw new NotImplementedException();
}
}
|
c#
| 10 | 0.675789 | 82 | 25.388889 | 18 |
starcoderdata
|
// @flow
import { connectionDefinitions } from 'graphql-relay'
import AgentType from './AgentType'
export default connectionDefinitions({
name: 'Agents',
nodeType: AgentType,
})
|
javascript
| 7 | 0.735135 | 53 | 17.5 | 10 |
starcoderdata
|
package model.commands;
import java.util.List;
import model.TurtleController;
import model.TurtleModel;
/**
* Purpose: This class represents an abstraction of a command that will set the pen to either down
* and drawing, or up and not drawing. Classes that will specifically set the pen up or set the pen
* down can extend this class. Assumptions: This class will never be instantiated, only inherited
* from. Dependencies: List, TurtleController, TurtleModel
*
* Example: Create a class that sets the pen down that extends this class.
*
* @author
* @author
*/
public abstract class SetPenCommand implements Command {
private final boolean penPosition;
/**
* Purpose: Create a new SetPenCommand with a boolean determining whether the pen is up or down.
*
* @param penUpOrDown Boolean, if true pen is down and drawing, and if false pen is up and not
* drawing.
* @param args List of integers which should be empty.
* @throws IllegalArgumentException thrown if args is not empty since the set pen command
* does not require any arguments.
*/
public SetPenCommand(boolean penUpOrDown, List args) throws IllegalArgumentException {
if (!args.isEmpty()) {
throw new IllegalArgumentException();
}
this.penPosition = penUpOrDown;
}
/**
* Purpose: Set the pen either down or up for all the active turtles
*
* @param turtleController The turtle controller parameter will have a list of active turtles
*/
public void runCommand(TurtleController turtleController) {
for (TurtleModel turtleModel : turtleController.getActiveTurtles()) {
turtleModel.setPen(penPosition);
}
}
}
|
java
| 10 | 0.721541 | 99 | 34.6875 | 48 |
starcoderdata
|
func TestMergeAppsIntoRoute(t *testing.T) {
// error when no apps
h, err := MergeApplications()
assert.Error(t, err)
assert.Nil(t, h)
// one app should merge just fine
app := NewApp()
app.SetPrefix("foo")
app.AddMiddleware(MakeRecoveryLogger())
h, err = MergeApplications(app)
assert.NoError(t, err)
assert.NotNil(t, h)
// a bad app should error
bad := NewApp()
bad.AddRoute("/foo").version = -1
h, err = MergeApplications(bad)
assert.Error(t, err)
assert.Nil(t, h)
// even when it's combined with a good one
h, err = MergeApplications(bad, app)
assert.Error(t, err)
assert.Nil(t, h)
}
|
go
| 9 | 0.684124 | 43 | 20.857143 | 28 |
inline
|
def testIsPackageInstalled(self):
"""Test if checking the existence of an installed package works."""
self.assertTrue(portage_util.IsPackageInstalled(
'category1/package',
sysroot=self.fake_chroot))
self.assertFalse(portage_util.IsPackageInstalled(
'category1/foo',
sysroot=self.fake_chroot))
|
python
| 10 | 0.705357 | 71 | 41.125 | 8 |
inline
|
public CM_COV_Object cmOperations(CMOperator op) {
// dimension check for input column vectors
if ( this.getNumColumns() != 1) {
throw new DMLRuntimeException("Central Moment can not be computed on ["
+ this.getNumRows() + "," + this.getNumColumns() + "] matrix.");
}
CM_COV_Object cmobj = new CM_COV_Object();
// empty block handling (important for result corretness, otherwise
// we get a NaN due to 0/0 on reading out the required result)
if( isEmptyBlock(false) ) {
op.fn.execute(cmobj, 0.0, getNumRows());
return cmobj;
}
int nzcount = 0;
if(sparse && sparseBlock!=null) //SPARSE
{
for(int r=0; r<Math.min(rlen, sparseBlock.numRows()); r++)
{
if(sparseBlock.isEmpty(r))
continue;
int apos = sparseBlock.pos(r);
int alen = sparseBlock.size(r);
double[] avals = sparseBlock.values(r);
for(int i=apos; i<apos+alen; i++) {
op.fn.execute(cmobj, avals[i]);
nzcount++;
}
}
// account for zeros in the vector
op.fn.execute(cmobj, 0.0, this.getNumRows()-nzcount);
}
else if(denseBlock!=null) //DENSE
{
//always vector (see check above)
double[] a = getDenseBlockValues();
for(int i=0; i<rlen; i++)
op.fn.execute(cmobj, a[i]);
}
return cmobj;
}
|
java
| 14 | 0.627962 | 75 | 27.795455 | 44 |
inline
|
#ifndef INCLUDED_DAL_TABLEDRIVER
#define INCLUDED_DAL_TABLEDRIVER
// Library headers.
// PCRaster library headers.
// Module headers.
#ifndef INCLUDED_DAL_DRIVER
#include "dal_Driver.h"
#define INCLUDED_DAL_DRIVER
#endif
#ifndef INCLUDED_DAL_TABLE
#include "dal_Table.h"
#define INCLUDED_DAL_TABLE
#endif
namespace dal {
// TableDriver declarations.
}
namespace dal {
//! This class is a base class for i/o drivers for Table datasets.
/*!
\todo Refactor the TableDriver tree.
\todo GeoEASTableDriver::dataSpace contains code which is relevant for
all table drivers.
*/
class PCR_DAL_DECL TableDriver: public Driver
{
friend class TableDriverTest;
private:
//! Assignment operator. NOT IMPLEMENTED.
TableDriver& operator= (TableDriver const& rhs);
//! Copy constructor. NOT IMPLEMENTED.
TableDriver (TableDriver const& rhs);
template<typename T>
bool extremes (T& min,
T& max,
size_t col,
TypeId typeId,
std::string const& name,
DataSpace space) const;
protected:
TableDriver (Format const& format);
public:
//----------------------------------------------------------------------------
// CREATORS
//----------------------------------------------------------------------------
virtual ~TableDriver ();
//----------------------------------------------------------------------------
// MANIPULATORS
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// ACCESSORS
//----------------------------------------------------------------------------
virtual Table* open (std::string const& name,
DataSpace const& space,
DataSpaceAddress const& address) const;
virtual DataSpace dataSpace (std::string const& name,
DataSpace const& space,
DataSpaceAddress const& address) const;
Table* read (std::string const& name) const;
void read (Table& table,
std::string const& name) const;
Table* read (std::string const& name,
TypeId typeId) const;
virtual Table* read (std::string const& name,
dal::DataSpace const& space,
dal::DataSpaceAddress const& address) const;
virtual void read (dal::Table& table,
std::string const& name,
dal::DataSpace const& space,
dal::DataSpaceAddress const& address) const;
void read (void* cell,
TypeId typeId,
std::string const& name,
DataSpace const& space,
DataSpaceAddress const& address) const;
void write (Table const& table,
std::string const& name) const;
virtual void write (Table const& table,
DataSpace const& space,
DataSpaceAddress const& address,
std::string const& name) const;
void append (std::string const& name,
Table const& table) const;
virtual void append (std::string const& name,
DataSpace const& space,
DataSpaceAddress const& address,
Table const& table) const;
virtual bool extremes (boost::any& min,
boost::any& max,
size_t col,
TypeId typeId,
std::string const& name,
DataSpace const& space) const;
};
//------------------------------------------------------------------------------
// INLINE FUNCTIONS
//------------------------------------------------------------------------------
template<typename T>
inline bool TableDriver::extremes(
T& min,
T& max,
size_t col,
TypeId typeId,
std::string const& name,
DataSpace space) const
{
bool initialised = false;
// boost::filesystem::path path;
Table* table = 0;
// Prevent iterating over time steps by removing the time dimension.
if(space.hasTime()) {
space.eraseDimension(space.indexOf(Time));
}
// Prevent iterating over individual cells by removing the space dimensions.
space.eraseDimension(Space);
if(space.isEmpty()) {
// path = pathFor(boost::get
table = dynamic_cast
if(table) {
table->setTypeIds(TI_NR_TYPES);
table->setTypeId(col, typeId);
table->createCols();
read(*table, name);
Array const& array(table->template col
if(array.extremes(min, max)) {
initialised = true;
}
delete table;
}
}
else {
T colMin, colMax;
for(DataSpaceIterator it = space.begin(); it != space.end(); ++it) {
// path = pathForDataSpaceAddress(boost::get
// space, *it);
table = open(name, space, *it);
if(table) {
table->setTypeIds(TI_NR_TYPES);
table->setTypeId(col, typeId);
table->createCols();
read(*table, name, space, *it);
Array const& array(table->template col
if(array.extremes(colMin, colMax)) {
if(!initialised) {
min = colMin;
max = colMax;
initialised = true;
}
else {
min = std::min colMin);
max = std::max colMax);
}
}
delete table;
table = 0;
}
}
}
return initialised;
}
//------------------------------------------------------------------------------
// FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// FREE FUNCTIONS
//------------------------------------------------------------------------------
} // namespace dal
#endif
|
c
| 22 | 0.411238 | 84 | 29.442553 | 235 |
starcoderdata
|
def __init__(self, method_module=None):
'''Initialises class with given method
Parameters
----------
method_module : module, optional
Imported module for given method, by default None
'''
#Set setup, evolution, and update functions
self._method_module = method_module
|
python
| 6 | 0.587537 | 61 | 29.727273 | 11 |
inline
|
package com.mastercard.azuretraining.persistence;
import com.mastercard.azuretraining.model.Hero;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface HeroRepository extends JpaRepository<Hero, Long> {
}
|
java
| 7 | 0.847458 | 67 | 28.5 | 10 |
starcoderdata
|
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
namespace GADev.BarberPoint.Application.Notifications.BarberShop
{
// public class EnviarEmail : INotificationHandler
// {
// public async Task Handle(CreateBarberShopNotification notification, CancellationToken cancellationToken)
// {
// Debug.WriteLine("Enviando e-mail");
// }
// }
}
|
c#
| 6 | 0.717391 | 115 | 29.733333 | 15 |
starcoderdata
|
package com.networkedassets.autodoc.transformer.manageSettings.provide.in;
public interface SourceRemover {
/**
* Removes all sources with matching id or url
*
* @param source
* - should contain id OR url of the source meant to be removed
* @return true if the source was removed
*/
boolean removeSource(int sourceId);
}
|
java
| 8 | 0.715517 | 75 | 28 | 12 |
starcoderdata
|
using System;
namespace BFC.BackgroundWorker.Exceptions
{
public class BackgroundQueueException : Exception
{
public BackgroundQueueException(string message) : base(message)
{
}
}
}
|
c#
| 9 | 0.704545 | 71 | 21 | 12 |
starcoderdata
|
#pragma once
#include
#include
#include "simulation_cycle.hpp"
#include "types.hpp"
namespace ccs
{
class simulation_builder
{
public:
simulation_builder() = default;
std::optional build(const sol::table& lua) &&;
};
} // namespace ccs
|
c++
| 10 | 0.731507 | 68 | 16.428571 | 21 |
starcoderdata
|
private void notifyConfigChanged(int item, String value) {
// can be null in testing
if (mCallbacks == null) {
return;
}
mCallbacks.broadcast(c -> {
try {
c.onStringConfigChanged(item, value);
} catch (RemoteException e) {
Log.w(TAG, "notifyConfigChanged(string): dead binder in notify, skipping.");
}
});
}
|
java
| 15 | 0.512761 | 92 | 32.230769 | 13 |
inline
|
import csp from 'js-csp';
import path from 'path';
export default function(recordToFile, fs) {
const result = csp.chan();
csp.go(function*() {
while(true) {
const {record, done} = yield csp.take(recordToFile);
const file = path.join(
'/var/lib/hypertext4/user/',
record.token + '.caml',
);
const exists = fs.existsSync(file);
if(!exists) {
fs.writeFileSync(file, '');
}
for(const line of record.lines) {
fs.appendFileSync(
file,
line === '' ? '\n' : line + '\n'
);
}
if(done) {
csp.putAsync(done);
}
csp.putAsync(result, record);
}
});
return result;
}
|
javascript
| 18 | 0.456044 | 64 | 27.4375 | 32 |
starcoderdata
|
public static HashSet<StockVertex> getNodesWithZeroCCLevel2(StockGraph g, int lower, int upper, int l2Lower, int l2Upper, double l2RatioLower) {
int count = 0;
HashSet<StockVertex> results = new HashSet<StockVertex>();
for(StockVertex v : g.getVertices()) {
Collection<StockVertex> neighbors = g.getNeighbors(v);
if(neighbors.size() >= lower && neighbors.size() <= upper) {
boolean isZeroCC = true;
for(StockVertex vi : neighbors) {
for(StockVertex vj : neighbors) {
if(g.findEdge(vi, vj)!= null) {
isZeroCC = false;
break;
}
}
if(isZeroCC == true) {
// Check 0: the grandchildren should not be the same
/*
Collection grand = g.getNeighbors(vi);
for(Iterator itg = grand.iterator(); itg.hasNext(); ) {
Integer gc = (Integer)itg.next();
if(gc.intValue() != v.intValue()) {
if(grandchildren.contains(gc)) {
isZeroCC = false;
break;
}
else {
grandchildren.add(gc);
}
}
}
*/
//HashSet hs = getNodesWithZeroCCLevel2(g, vi, v, l2Lower, l2Upper);
// Check 1: see if grandchildren are connected to each other
/*
if(hs.size() == 0) {
isZeroCC = false;
}
*/
// Check 2: see if ratio is higher enough
/*
double l2Ratio = (double)hs.size() / (double)neighbors.size();
if(l2Ratio < l2RatioLower) {
isZeroCC = false;
}
*/
// Check 3: see if grandchildren are the same
/*
for(Iterator iths = hs.iterator(); iths.hasNext(); ) {
Integer gc = (Integer)iths.next();
if(grandchildren.contains(gc)) {
isZeroCC = false;
break;
}
else {
grandchildren.add(gc);
}
}
*/
}
if(isZeroCC == false) {
break;
}
}
if(isZeroCC == true) {
results.add(v);
count++;
if(count%50 == 0) {
System.out.print(".");
}
}
}
}
System.out.println();
return results;
}
|
java
| 16 | 0.511531 | 144 | 24.463415 | 82 |
inline
|
#originally inspired by http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html ,
#but substantially modified from that
import numpy as np
from sklearn import datasets, linear_model
from sklearn.cross_validation import cross_val_score, KFold
import csv
#Load the data
#TODO: allow loading from an arbitrary input
f = open('../solves.csv', 'rb')
reader = csv.reader(f)
firstRow = True
targets_basic = []
data_basic = []
labels = []
for row in reader:
if firstRow:
firstRow = False
labels = row
continue
convertedRow = [float(a) for a in row]
targets_basic.append(convertedRow[:1][0])
data_basic.append(convertedRow[1:])
#TODO: figure out if I can just create a numpy array from the beginning
targets = np.array(targets_basic)
data = np.array(data_basic)
# Create linear regression object
regr = linear_model.Ridge(alpha=1.0)
# Train the model using the training sets
regr.fit(data, targets)
print("Coefficients")
print("Constant = " + str(regr.intercept_))
for i in xrange(0, len(regr.coef_)):
print(labels[i+1] + " = " + str(regr.coef_[i]))
# # The mean square error
# print("Residual sum of squares: %.2f"
# % np.mean((regr.predict(data_test) - targets_test) ** 2))
# # Explained variance score: 1 is perfect prediction
# print('Variance score: %.2f' % regr.score(data_test, targets_test))
K = 20 #folds
R2 = cross_val_score(regr, data, y=targets, cv=KFold(targets.size, K)).mean()
print("The %d-Folds estimate of the coefficient of determination is R2 = %s"
% (K, R2))
#TODO: export the model in a way that Go can run it
|
python
| 11 | 0.707937 | 97 | 26.649123 | 57 |
starcoderdata
|
package com.example.mobile.safe.utils;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
/**
* 检查服务状态的工具类
*/
public class ServiceStatusUtils {
/**
* 判断某个服务是否处于运行状态
* @param 上下文
* @param 服务的全路径名称
*/
public static boolean isServiceRunning(Context context,String serviceFullName){
//得到系统进程的管理器
ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
//得到系统里面正在运行的服务
List services = am.getRunningServices(200);
for(RunningServiceInfo info:services){
if(serviceFullName.equals(info.service.getClassName())){
return true;
}
}
return false;
}
}
|
java
| 13 | 0.757866 | 92 | 22.580645 | 31 |
starcoderdata
|
from brownie import reverts, ZERO_ADDRESS, chain, RewardsManager
from utils.config import (
rewards_amount,
gift_index,
initial_rewards_duration_sec
)
def test_owner_is_deployer(rewards_manager, farming_rewards, ape):
assert rewards_manager.owner() == ape
assert len(rewards_manager.tx.events) == 2
assert rewards_manager.tx.events['RewardsContractSet']['rewards_contract'] == farming_rewards
assert rewards_manager.tx.events['OwnershipTransferred']['previous_owner'] == ZERO_ADDRESS
assert rewards_manager.tx.events['OwnershipTransferred']['new_owner'] == ape
def test_rewards_contract_address_is_not_zero(ape, rewards_initializer):
with reverts("rewards contract: zero address"):
RewardsManager.deploy(ZERO_ADDRESS, rewards_initializer, {"from": ape})
def test_rewards_rewards_initializer_is_not_zero(ape, farming_rewards):
with reverts("rewards initializer: zero address"):
RewardsManager.deploy(farming_rewards, ZERO_ADDRESS, {"from": ape})
def test_stranger_cannot_transfer_ownership(rewards_manager, stranger):
with reverts("not permitted"):
rewards_manager.transfer_ownership(stranger, {"from": stranger})
def test_ownership_can_be_transferred(rewards_manager, ape, stranger):
tx = rewards_manager.transfer_ownership(stranger, {"from": ape})
assert rewards_manager.owner() == stranger
assert len(tx.events) == 1
assert tx.events['OwnershipTransferred']['previous_owner'] == ape
assert tx.events['OwnershipTransferred']['new_owner'] == stranger
def test_ownership_can_be_transferred_to_zero_address(rewards_manager, ape):
rewards_manager.transfer_ownership(ZERO_ADDRESS, {"from": ape})
assert rewards_manager.owner() == ZERO_ADDRESS
def test_stranger_can_check_is_rewards_period_finished(rewards_manager, stranger):
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == True
def test_period_finish(rewards_manager, farming_rewards):
assert farming_rewards.tokenRewards(gift_index)[4] == rewards_manager.period_finish()
def test_rewards_initializer_cannot_start_next_rewards_period_with_zero_amount(rewards_manager, rewards_initializer):
with reverts("manager: rewards disabled"):
rewards_manager.start_next_rewards_period({"from": rewards_initializer})
def test_stranger_cannot_start_first_rewards_period(rewards_manager, stranger):
with reverts("manager: not initialized"):
rewards_manager.start_next_rewards_period({"from": stranger})
def test_rewards_initializer_can_start_next_rewards_period(rewards_manager, rewards_initializer, ldo_token, dao_agent):
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
assert ldo_token.balanceOf(rewards_manager) > 0
rewards_manager.start_next_rewards_period({"from": rewards_initializer})
def test_stranger_starts_next_rewards_period(rewards_manager, ldo_token, dao_agent, stranger, rewards_initializer):
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
assert ldo_token.balanceOf(rewards_manager) > 0
rewards_manager.start_next_rewards_period({"from": rewards_initializer})
chain.sleep(initial_rewards_duration_sec)
chain.mine()
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
assert ldo_token.balanceOf(rewards_manager) > 0
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == True
rewards_manager.start_next_rewards_period({"from": stranger})
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == False
def test_stranger_cannot_start_next_rewards_period_while_current_is_active(rewards_manager, ldo_token, dao_agent, stranger, rewards_initializer):
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == True
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
rewards_manager.start_next_rewards_period({"from": rewards_initializer})
chain.sleep(1)
chain.mine()
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == False
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
with reverts("manager: rewards period not finished"):
rewards_manager.start_next_rewards_period({"from": stranger})
def test_stranger_can_start_next_rewards_period_after_current_is_finished(rewards_manager, ldo_token, dao_agent, stranger, rewards_initializer):
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == True
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
rewards_manager.start_next_rewards_period({"from": rewards_initializer})
chain.sleep(initial_rewards_duration_sec * 2)
chain.mine()
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == True
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
rewards_manager.start_next_rewards_period({"from": stranger})
assert rewards_manager.is_rewards_period_finished({"from": stranger}) == False
def test_stranger_cannot_recover_erc20(rewards_manager, ldo_token, stranger):
with reverts("not permitted"):
rewards_manager.recover_erc20(ldo_token, 0, {"from": stranger})
def test_owner_recovers_erc20_to_own_address(rewards_manager, ldo_token, dao_agent, ape):
assert ldo_token.balanceOf(rewards_manager) == 0
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
assert ldo_token.balanceOf(rewards_manager) == rewards_amount
tx = rewards_manager.recover_erc20(ldo_token, rewards_amount, ape, {"from": ape})
assert len(tx.events) == 0
assert ldo_token.balanceOf(ape) == 0
assert ldo_token.balanceOf(rewards_manager) == rewards_amount
def test_owner_recovers_erc20_zero_amount(rewards_manager, ldo_token, dao_agent, ape):
assert ldo_token.balanceOf(rewards_manager) == 0
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
assert ldo_token.balanceOf(rewards_manager) == rewards_amount
tx = rewards_manager.recover_erc20(ldo_token, 0, ape, {"from": ape})
assert len(tx.events) == 1
assert tx.events['ERC20TokenRecovered']['token'] == ldo_token
assert tx.events['ERC20TokenRecovered']['amount'] == rewards_amount
assert tx.events['ERC20TokenRecovered']['recipient'] == ape
assert ldo_token.balanceOf(ape) == rewards_amount
def test_owner_recovers_erc20_to_stranger_address(rewards_manager, ldo_token, dao_agent, ape, stranger):
assert ldo_token.balanceOf(rewards_manager) == 0
ldo_token.transfer(rewards_manager, rewards_amount, {"from": dao_agent})
assert ldo_token.balanceOf(rewards_manager) == rewards_amount
tx = rewards_manager.recover_erc20(ldo_token, rewards_amount, stranger, {"from": ape})
assert len(tx.events) == 1
assert tx.events['ERC20TokenRecovered']['token'] == ldo_token
assert tx.events['ERC20TokenRecovered']['amount'] == rewards_amount
assert tx.events['ERC20TokenRecovered']['recipient'] == stranger
assert ldo_token.balanceOf(stranger) == rewards_amount
def test_update_rewards_period_duration(rewards_manager, ape, farming_rewards, stranger):
with reverts('manager: not permitted'):
rewards_manager.set_rewards_period_duration(1000, {"from": stranger})
assert farming_rewards.tokenRewards(gift_index)[2] == initial_rewards_duration_sec
rewards_manager.set_rewards_period_duration(1000, {"from": ape})
assert farming_rewards.tokenRewards(gift_index)[2] == 1000
|
python
| 11 | 0.728885 | 145 | 39.71123 | 187 |
starcoderdata
|
public ResponseEntity<String> sendEmailToModer(EmailToModeratorRequest request) throws MessagingException {
String name = request.getName();
String subject = request.getSubject();
String messageText = request.getMessage();
String emailRec = request.getEmailAdres();
int id = 0;
if (isEmailValidRegEx(emailRec)) {
//find user by ID
User user = userRepository.findUserByEmail(emailRec);
if (user != null) {
id = user.getId();
}
MimeMessage message = emailSender.createMimeMessage();
boolean multipart = true;
MimeMessageHelper helper = new MimeMessageHelper(message, multipart, "utf-8");
//String htmlMsg = "<h3>" + messageText + "</h3>";
String htmlMsg="";
if (id != 0) {
// String htmlMsg = "<h3 style=\"color: green\">" + messageText + "</color> </h3>";
htmlMsg = "<h3>" + messageText + "<br><br>" + "from user with name " + name + " and Id " + id + "</h3>";
} else {
htmlMsg = "<h3>" + messageText + "<br><br>" + "from unauthorized with name " + name+ "</h3>";
}
message.setContent(htmlMsg, "text/html");
helper.setTo(systemEmailsRepository.findEmailById(request.getEmailAdrId()));
helper.setSubject(subject);
this.emailSender.send(message);
return new ResponseEntity<String>("Email Sent!", HttpStatus.OK);
} else {
return new ResponseEntity<String>("Email not valid", HttpStatus.CONFLICT);
}
}
|
java
| 17 | 0.558646 | 120 | 38.404762 | 42 |
inline
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"text/tabwriter"
// "github.com/pkg/errors"
)
type BeneficiaryList struct {
Beneficiaries []struct {
ReferenceID string `json:"beneficiary_reference_id"`
Name string `json:"name"`
Birth string `json:"birth_year"`
Gender string `json:"gender"`
Mobile string `json:"mobile_number"`
PhotoIdType string `json:"photo_id_type"`
PhotoIdNumber string `json:"photo_id_number"`
ComorbidityInd string `json:"comorbidity_ind"`
VaccinationStat string `json:"vaccination_status"`
Vaccine string `json:"vaccine"`
Dose1Date string `json:"dose1_date"`
Dose2Date string `json:"dose2_date"`
Appointments []struct {
AppointmentID string `json:"appointment_id"`
CenterID int `json:"center_id"`
Name string `json:"name"`
StateName string `json:"state_name"`
DistrictName string `json:"district_name"`
BlockName string `json:"block_name"`
From string `json:"from"`
To string `json:"to"`
Dose int `json:"dose"`
SessionID string `json:"session_id"`
Date string `json:"date"`
Slot string `json:"slot"`
} `json:"appointments"`
} `json:"beneficiaries"`
}
type AppointmentList struct {
DoseAppointments []struct {
} `json:"appointments"`
}
func getBeneficiaries() (*BeneficiaryList, error) {
response, err := queryServer(beneficiariesURLFormat, "GET", nil)
beneficiaryList := BeneficiaryList{}
err = json.Unmarshal(response, &beneficiaryList)
if err != nil {
log.Printf("Error parsing response: %v",err.Error())
return &beneficiaryList, err
}
var buf bytes.Buffer
w := tabwriter.NewWriter(&buf, 1, 8, 1, '\t', 0)
for _, beneficiary := range beneficiaryList.Beneficiaries {
fmt.Fprintln(w, fmt.Sprintf("\nBeneficiaryID\t %s", beneficiary.ReferenceID))
fmt.Fprintln(w, fmt.Sprintf("Name\t %s", beneficiary.Name))
fmt.Fprintln(w, fmt.Sprintf("PhotoIdType\t %s", beneficiary.PhotoIdType))
fmt.Fprintln(w, fmt.Sprintf("PhotoIdNumber\t %s", beneficiary.PhotoIdNumber))
fmt.Fprintln(w, fmt.Sprintf("Status\t %s", beneficiary.VaccinationStat))
fmt.Fprintln(w, fmt.Sprintf("Dose1Date\t %s", beneficiary.Dose1Date))
fmt.Fprintln(w, fmt.Sprintf("Dose2Date\t %s", beneficiary.Dose2Date))
for _, appt := range beneficiary.Appointments {
fmt.Fprintln(w, fmt.Sprintf("AppointmentID\t %s", appt.AppointmentID))
fmt.Fprintln(w, fmt.Sprintf("SessionID\t %s", appt.SessionID))
fmt.Fprintln(w, fmt.Sprintf("Dose\t %d", appt.Dose))
fmt.Fprintln(w, fmt.Sprintf("Date\t %s", appt.Date))
fmt.Fprintln(w, fmt.Sprintf("Slot\t %s\n", appt.Slot))
}
}
if err := w.Flush(); err != nil {
log.Printf("Error writing to buffer: %v",err.Error())
return &beneficiaryList, err
}
if buf.Len() == 0 {
sendwhatsapptext("No beneficiaries registered\n")
return &beneficiaryList, nil
}
// sendwhatsapptext("Beneficiaries registered:\n" + buf.String())
return &beneficiaryList, err
}
|
go
| 14 | 0.677944 | 80 | 33.261364 | 88 |
starcoderdata
|
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.15.0 -emit-pch -o %t %s
// RUN: %clang_analyze_cc1 -triple x86_64-apple-macosx10.15.0 -include-pch %t \
// RUN: -analyzer-checker=core,apiModeling -verify %s
//
// RUN: %clang_cc1 -emit-pch -o %t %s
// RUN: %clang_analyze_cc1 -include-pch %t \
// RUN: -analyzer-checker=core,apiModeling -verify %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
// Pre-compiled header
int foo();
// Literal data for this macro value will be null
#define EOF -1
#else
// Source file
int test() {
// we need a function call here to initiate erroneous routine
return foo(); // no-crash
}
#endif
|
c++
| 8 | 0.679507 | 79 | 22.178571 | 28 |
research_code
|
<?php
namespace App\Traits;
use AfricasTalking\SDK\AfricasTalking;
use App\Sms;
trait Messaging {
public function sendSMS($student,$message)
{
$username = 'hotlunch'; // use 'sandbox' for development in the test environment
$apiKey = 'f00081c7d5230a82b19fded9e16cd5c3ae73df8196ede611cd3694fc6141d4d6'; // use your sandbox app API key for development in the test environment
$AT = new AfricasTalking($username, $apiKey);
$sms = $AT->sms();
$result = $sms->send([
'to' => $student->parent_phone,
'from' =>'HOTLUNCH',
'message' => $message
]);
$smsD=array();
$smsD['student_id']=$student->id;
$smsD['date']=date('Y-m-d');
$smsD['time']=date('H:i:s');
$smsD['sms']=$message;
Sms::create($smsD);
}
}
?>
|
php
| 14 | 0.633766 | 152 | 23.09375 | 32 |
starcoderdata
|
from conans import AutoToolsBuildEnvironment, ConanFile, tools
import os
import shutil
class TestPackage(ConanFile):
settings = "os", "arch", "compiler", "build_type"
def build(self):
for f in ("header.h", "main.c", "source.c", "Jamfile"):
shutil.copy(os.path.join(self.source_folder, f),
os.path.join(self.build_folder, f))
if not tools.cross_building(self.settings):
assert os.path.isfile(os.environ["JAM"])
vars = AutoToolsBuildEnvironment(self).vars
vars["CCFLAGS"] = vars["CFLAGS"]
vars["C++FLAGS"] = vars["CXXFLAGS"]
vars["LINKFLAGS"] = vars["LDFLAGS"]
vars["LINKLIBS"] = vars["LIBS"]
with tools.environment_append(vars):
self.run("{} -d7".format(os.environ["JAM"]), run_environment=True)
def test(self):
if not tools.cross_building(self.settings):
bin_path = os.path.join(".", "test_package")
self.run(bin_path, run_environment=True)
|
python
| 16 | 0.583493 | 82 | 37.592593 | 27 |
starcoderdata
|
package com.huotu.huotao.sayhi.bean;
import java.io.Serializable;
/**
* Created by Administrator on 2017/2/25.
*/
public class LocationBean implements Serializable {
private int locationid;
private int taskid;
private String longitude;
private String latitude;
private String address;
private int status;
private String remark;
public int getLocationid() {
return locationid;
}
public void setLocationid(int locationid) {
this.locationid = locationid;
}
public int getTaskid() {
return taskid;
}
public void setTaskid(int taskid) {
this.taskid = taskid;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
|
java
| 14 | 0.635046 | 116 | 19.794521 | 73 |
starcoderdata
|
export default theme => ({
root: {
...theme.mixins.gutters(),
paddingTop: theme.spacing.unit * 2,
paddingBottom: theme.spacing.unit * 2
}
});
|
javascript
| 11 | 0.598765 | 45 | 22.142857 | 7 |
starcoderdata
|
absl::StatusOr<CValue> Translator::GenerateIR_MemberExpr(
const clang::MemberExpr* expr, const xls::SourceLocation& loc) {
XLS_ASSIGN_OR_RETURN(CValue leftval, GenerateIR_Expr(expr->getBase(), loc));
XLS_ASSIGN_OR_RETURN(auto itype, ResolveTypeInstance(leftval.type()));
auto sitype = std::dynamic_pointer_cast<CStructType>(itype);
if (sitype == nullptr) {
return absl::UnimplementedError(
absl::StrFormat("Unimplemented member access on type %s at %s",
string(*itype), LocString(loc)));
}
// Get the value referred to
clang::ValueDecl* member = expr->getMemberDecl();
// VarDecl for static values
if (member->getKind() == clang::ValueDecl::Kind::Var) {
XLS_ASSIGN_OR_RETURN(
CValue val,
TranslateVarDecl(clang_down_cast<const clang::VarDecl*>(member), loc));
return val;
} else if (member->getKind() != clang::ValueDecl::Kind::Field) {
// Otherwise only FieldDecl is supported. This is the non-static "foo.bar"
// form.
return absl::UnimplementedError(
absl::StrFormat("Unimplemented member expression %s at %s",
member->getDeclKindName(), LocString(loc)));
}
auto field = clang_down_cast<clang::FieldDecl*>(member);
const auto& fields_by_name = sitype->fields_by_name();
auto found_field =
// Upcast to NamedDecl because we track unique identifiers
// with NamedDecl pointers
fields_by_name.find(absl::implicit_cast<const clang::NamedDecl*>(field));
if (found_field == fields_by_name.end()) {
return absl::NotFoundError(absl::StrFormat(
"Member access on unknown field %s in type %s at %s",
field->getNameAsString(), string(*itype), LocString(loc)));
}
const CField& cfield = *found_field->second;
// Upcast to NamedDecl because we track unique identifiers
// with NamedDecl pointers
XLS_CHECK_EQ(cfield.name(),
absl::implicit_cast<const clang::NamedDecl*>(field));
xls::BValue bval =
GetStructFieldXLS(leftval.value(), cfield.index(), *sitype, loc);
return CValue(bval, cfield.type());
}
|
c++
| 16 | 0.664611 | 79 | 41.18 | 50 |
inline
|
// RUN: %clangxx -fsycl -DFAKE_PLUGIN -shared %s -o %t_fake_plugin.so
// RUN: %clangxx -fsycl %s -o %t.out
// RUN: env SYCL_OVERRIDE_PI_OPENCL=%t_fake_plugin.so env SYCL_OVERRIDE_PI_LEVEL_ZERO=%t_fake_plugin.so env SYCL_OVERRIDE_PI_CUDA=%t_fake_plugin.so env SYCL_OVERRIDE_PI_HIP=%t_fake_plugin.so env SYCL_PI_TRACE=-1 %t.out > %t.log 2>&1
// RUN: FileCheck %s --input-file %t.log
// REQUIRES: linux
#ifdef FAKE_PLUGIN
#include
pi_result piPlatformsGet(pi_uint32 NumEntries, pi_platform *Platforms,
pi_uint32 *NumPlatforms) {
return PI_INVALID_OPERATION;
}
pi_result piTearDown(void *) { return PI_SUCCESS; }
pi_result piPluginInit(pi_plugin *PluginInit) {
PluginInit->PiFunctionTable.piPlatformsGet = piPlatformsGet;
PluginInit->PiFunctionTable.piTearDown = piTearDown;
return PI_SUCCESS;
}
#else
#include
int main() {
try {
sycl::platform P{sycl::default_selector{}};
} catch (...) {
// NOP
}
return 0;
}
#endif
// CHECK: SYCL_PI_TRACE[basic]: Plugin found and successfully loaded: {{[0-9a-zA-Z_\/\.-]+}}_fake_plugin.so
// CHECK: SYCL_PI_TRACE[basic]: Plugin found and successfully loaded: {{[0-9a-zA-Z_\/\.-]+}}_fake_plugin.so
// CHECK: SYCL_PI_TRACE[basic]: Plugin found and successfully loaded: {{[0-9a-zA-Z_\/\.-]+}}_fake_plugin.so
// CHECK: SYCL_PI_TRACE[basic]: Plugin found and successfully loaded: {{[0-9a-zA-Z_\/\.-]+}}_fake_plugin.so
|
c++
| 12 | 0.673823 | 232 | 32.581395 | 43 |
starcoderdata
|
<?php
include 'chatfs.php';//connect database;
$query='SELECT * from chat ORDER BY date DESC';//select the data
$run=$conn->query($query) or die("Last error: {$conn->error}\n") ;
while($row = $run->fetch_array()):
?>
<div class="chat-data">
<span style="color:darkgreen"><?php echo $row['name'];?>
<span style="color:darkred"><?php echo $row['msg'];?>
<span style="float:right"><?php echo formatData( $row['date']);?>
<?php endwhile ?>
|
php
| 9 | 0.600402 | 72 | 24.210526 | 19 |
starcoderdata
|
func (r *Reconciler) FinalizeKind(ctx context.Context, t *eventingv1.Trigger) pkgreconciler.Event {
broker, err := r.brokerLister.Brokers(t.Namespace).Get(t.Spec.Broker)
if err != nil {
if apierrs.IsNotFound(err) {
// Ok to return nil here. There's nothing for us to do.
return nil
}
return fmt.Errorf("retrieving broker: %v", err)
}
// If it's not my brokerclass, ignore
// However, if for some reason it has my finalizer, remove it.
// This is a bug in genreconciler because it slaps the finalizer in before we
// know whether it is actually ours.
if broker.Annotations[eventing.BrokerClassKey] != r.brokerClass {
logging.FromContext(ctx).Infof("Ignoring trigger %s/%s", t.Namespace, t.Name)
finalizers := sets.NewString(t.Finalizers...)
if finalizers.Has(finalizerName) {
finalizers.Delete(finalizerName)
t.Finalizers = finalizers.List()
}
return nil
}
if isUsingOperator(broker) {
// Everything gets cleaned up by garbage collection in this case.
return nil
}
_, rabbitmqURL, err := r.rabbitmqURL(ctx, t)
// If there's no secret, we can't delete the queue. Deleting an object should not require creation
// of a secret, and for example if the namespace is being deleted, there's nothing we can do.
// For now, return nil rather than leave the Trigger around.
if err != nil {
logging.FromContext(ctx).Errorf("Failed to fetch rabbitmq secret while finalizing, leaking a queue %s/%s", t.Namespace, t.Name)
return nil
}
err = resources.DeleteQueue(r.dialerFunc, &resources.QueueArgs{
QueueName: naming.CreateTriggerQueueName(t),
RabbitmqURL: rabbitmqURL,
})
if err != nil {
return fmt.Errorf("trigger finalize failed: %v", err)
}
return nil
}
|
go
| 14 | 0.720794 | 129 | 35.446809 | 47 |
inline
|
'use strict'
const mixinSetters = require('./mixin-setters')
const setValues = require('./set-values')
class Field {
constructor (values) {
if (typeof values === 'string') {
values = { title: values }
}
this._attachment = null
this.data = {}
setValues(this, values)
// Adds scope of `this` to each setter fn for chaining `.get()`
this.addSetterScopes()
}
attachment (attachment) {
this._attachment = attachment
return this
}
end () {
return this._attachment
}
json () {
return Object.assign({}, this.data)
}
toJSON () {
return this.json()
}
}
// props for Slack API - true gets a generic setter fn
const PROPS = {
title: true,
value: true,
short: true
}
mixinSetters(Field.prototype, PROPS)
// export a factory fn
module.exports = (values) => {
return new Field(values)
}
|
javascript
| 11 | 0.618938 | 67 | 15.980392 | 51 |
starcoderdata
|
<?php
namespace EgeaTech\LaravelModels\Models\Concerns;
use Illuminate\Database\Eloquent\Model;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\AllowedInclude;
use Spatie\QueryBuilder\AllowedSort;
use Spatie\QueryBuilder\Filters\FiltersPartial;
trait Queryable
{
public static function getDefaultSortingField(): string
{
return static::fetchDisposableModelInstance()->getKeyName();
}
/**
* @return AllowedFilter[]
*/
public static function getAllowedFilters(): array
{
return collect(static::fetchDisposableModelInstance()->getFillable())
->map(fn (string $fillableField) => new AllowedFilter($fillableField, new FiltersPartial($fillableField)))
->toArray();
}
/**
* @return string[]|AllowedInclude[]
*/
public static function getAllowedIncludes(): array
{
return [];
}
/**
* @return AllowedSort[]
*/
public static function getAllowedSorting(): array
{
$modelInstance = static::fetchDisposableModelInstance();
return $modelInstance->timestamps
? [AllowedSort::field($modelInstance->getUpdatedAtColumn())]
: [AllowedSort::field($modelInstance->getKeyName())];
}
/**
* @return string[]
*/
public static function getAllowedAppendAttributes(): array
{
return [];
}
private static function fetchDisposableModelInstance(): Model
{
return new static();
}
}
|
php
| 18 | 0.655484 | 118 | 24.409836 | 61 |
starcoderdata
|
using RuneForge.Data.Components;
using RuneForge.Game.Components.Attributes;
using RuneForge.Game.Components.Implementations;
namespace RuneForge.Game.Components.Factories
{
[ComponentDto(typeof(TextureAtlasComponentDto))]
public class TextureAtlasComponentFactory : ComponentFactory<TextureAtlasComponent, TextureAtlasComponentPrototype, TextureAtlasComponentDto>
{
public override TextureAtlasComponent CreateComponentFromPrototype(TextureAtlasComponentPrototype componentPrototype, TextureAtlasComponentPrototype componentPrototypeOverride)
{
return new TextureAtlasComponent(componentPrototype.TextureAtlasAssetName, componentPrototype.HasPlayerColor);
}
public override TextureAtlasComponent CreateComponentFromDto(TextureAtlasComponentDto componentDto)
{
return new TextureAtlasComponent(componentDto.TextureAtlasAssetName, componentDto.HasPlayerColor);
}
}
}
|
c#
| 12 | 0.804954 | 184 | 45.142857 | 21 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Enterprise.Invoicing.ViewModel
{
[Serializable]
public class NeedPayModel
{
public int supplierId { get; set; }
public string supplierName { get; set; }
public double amount { get; set; }
public double cost { get; set; }
public System.DateTime dateStart { get; set; }
public System.DateTime dateEnd { get; set; }
}
[Serializable]
public class NeedPayDetailModel
{
public string purchaseNo { get; set; }
public string stockInNo { get; set; }
public double amount { get; set; }
public double cost { get; set; }
public double allcost { get; set; }
public DateTime inDate { get; set; }
//public System.DateTime inDate { get; set; }
public string remark { get; set; }
}
[Serializable]
public class V_StockInPurchase
{
public string stockInNo { get; set; }
public int supplierId { get; set; }
public DateTime createDate { get; set; }
public string materialNo { get; set; }
public string purchaseNo { get; set; }
public int purchaseDetailSn { get; set; }
public string supplierName { get; set; }
public string category { get; set; }
public string materialModel { get; set; }
public string materialName { get; set; }
public string tunumber { get; set; }
public string unit { get; set; }
public string pinyin { get; set; }
public string fastcode { get; set; }
public string person { get; set; }
public double poPrice { get; set; }
public double poAmount { get; set; }
public double inAmount { get; set; }
public double returnAmount { get; set; }
public double poCost { get; set; }
public double inCost { get; set; }
public double returnCost { get; set; }
}
///
/// 前台查询模型
///
public class SearchModel
{
///
/// 查询单号
///
public string QueryNo { get; set; }
///
/// 供应商
///
public string Supplier { get; set; }
///
/// 开始时间
///
public DateTime? DateStart { get; set; }
///
/// 结束时间
///
public DateTime? DateEnd { get; set; }
///
/// 状态
///
public int? Status { get; set; }
///
/// 页索引
///
public int PageIndex { get; set; }
///
/// 页大小
///
public int? PageSize { get; set; }
///
/// 记录总数
///
public int TotalCount { get; set; }
///
/// 页总数
///
public int PageCount { get; set; }
}
}
|
c#
| 8 | 0.533399 | 54 | 26.9 | 110 |
starcoderdata
|
import React from 'react';
import $ from 'jquery';
class EditForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
if (this.state.value.length < 1)
{
window.alert ('Enter a todo')
}
let todo = {
"id" : this.props.todo.id,
"nexttext" : this.state.value
}
$.ajax({
url: 'http://127.0.0.1:5000/edit',
type: 'POST',
data: todo,
dataType: 'json',
success: this.reload
})
}
render() {
return (
<form onSubmit={this.handleSubmit} class="flex flex-row space-x-2 w-full">
<input type='text'
class="autofocus bg-black border border-green-300 focus:outline-none focus:bg-gray-800 focus:border-green-400 w-4/5 mr-2 p-1"
value={this.state.value}
placeholder={this.props.todo.todotext}
onChange={this.handleChange} />
<div class='inline-block'><input
class="bg-black border px-2 py-1 cursor-pointer border-green-300 w-auto"
id='submittodo' type="submit" value="add" />
)
}
}
export default EditForm;
|
javascript
| 12 | 0.502706 | 145 | 27.689655 | 58 |
starcoderdata
|
package com.zhuinden.movierandomizerclient.utils;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import com.zhuinden.movierandomizerclient.application.CustomApplication;
/**
* Created by Zhuinden on 2017.12.28..
*/
public class Toaster {
private Toaster() {
}
private static final Handler handler = new Handler(Looper.getMainLooper());
public static void showToast(String text) {
if(Looper.getMainLooper() == Looper.myLooper()) {
showText(text);
} else {
handler.post(() -> showText(text));
}
}
private static void showText(String text) {
Toast.makeText(CustomApplication.get(), text, Toast.LENGTH_LONG).show();
}
}
|
java
| 13 | 0.667989 | 80 | 23.387097 | 31 |
starcoderdata
|
// Copyright 2021 All rights reserved.
// Use of this source code is governed by MIT license
// Package function implements some functions for control the function execution and some is for functional programming.
package function
import (
"reflect"
"time"
)
// After creates a function that invokes func once it's called n or more times
func After(n int, fn any) func(args ...any) []reflect.Value {
// Catch programming error while constructing the closure
mustBeFunction(fn)
return func(args ...any) []reflect.Value {
n--
if n < 1 {
return unsafeInvokeFunc(fn, args...)
}
return nil
}
}
// Before creates a function that invokes func once it's called less than n times
func Before(n int, fn any) func(args ...any) []reflect.Value {
// Catch programming error while constructing the closure
mustBeFunction(fn)
var res []reflect.Value
return func(args ...any) []reflect.Value {
if n > 0 {
res = unsafeInvokeFunc(fn, args...)
}
if n <= 0 {
fn = nil
}
n--
return res
}
}
// Fn is for curry function which is func(...any) any
type Fn func(...any) any
// Curry make a curry function
func (f Fn) Curry(i any) func(...any) any {
return func(values ...any) any {
v := append([]any{i}, values...)
return f(v...)
}
}
// Compose compose the functions from right to left
func Compose(fnList ...func(...any) any) func(...any) any {
return func(s ...any) any {
f := fnList[0]
restFn := fnList[1:]
if len(fnList) == 1 {
return f(s...)
}
return f(Compose(restFn...)(s...))
}
}
// Delay make the function execution after delayed time
func Delay(delay time.Duration, fn any, args ...any) {
// Catch programming error while constructing the closure
mustBeFunction(fn)
time.Sleep(delay)
invokeFunc(fn, args...)
}
// Debounced creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.
func Debounced(fn func(), duration time.Duration) func() {
// Catch programming error while constructing the closure
mustBeFunction(fn)
timer := time.NewTimer(duration)
timer.Stop()
go func() {
for {
select {
case <-timer.C:
go fn()
}
}
}()
return func() { timer.Reset(duration) }
}
// Schedule invoke function every duration time, util close the returned bool chan
func Schedule(d time.Duration, fn any, args ...any) chan bool {
// Catch programming error while constructing the closure
mustBeFunction(fn)
quit := make(chan bool)
go func() {
for {
unsafeInvokeFunc(fn, args...)
select {
case <-time.After(d):
case <-quit:
return
}
}
}()
return quit
}
|
go
| 15 | 0.675462 | 160 | 22.069565 | 115 |
starcoderdata
|
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int N,c1[128],c2[128],Ans,Ret;
char s[105];
inline void check(int L,int R,int c[]){
for (char ch='a';ch<='z';++ch) c[ch]=0;
for (int i=L;i<=R;++i) ++c[s[i]];
}
inline int count(){
Ret=0;
for (char ch='a';ch<='z';++ch)
if (c1[ch]&&c2[ch]) ++Ret;
return Ret;
}
int main(){
scanf("%d%s",&N,s+1);
for (int i=1;i<N;++i)
Ans=max(Ans,(check(1,i,c1),check(i+1,N,c2),count()));
printf("%d",Ans);
return 0;
}
|
c++
| 14 | 0.573469 | 55 | 20.347826 | 23 |
codenet
|
public static async Task PreHandle(HttpListenerContext listenerContext)
{
//Attempt to establish the WebSocket
WebSocketContext webSocketContext = null;
try
{
webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null);
}
catch (Exception e)
{
//Send an error on failure
listenerContext.Response.StatusCode = 500;
listenerContext.Response.Close();
Console.WriteLine("Exception: {0}", e);
return;
}
//Begin handling a specific websocket instance
await WebSocketInstance(webSocketContext.WebSocket, listenerContext);
}
|
c#
| 13 | 0.567532 | 97 | 37.55 | 20 |
inline
|
import React, { useState, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import AppContext from '../../context/AppContext';
import TabBar from '../../shared/TabBar';
import OutreachTab from './Outreach';
import FollowupTab from './Followup';
import ProfileTab from './Profile';
import ActionsTab from './Actions';
import AboutTab from './About';
const LeftSidebar = () => {
const { t } = useTranslation('rightSidebar');
const context = useContext(AppContext);
const { state, dispatch } = context;
const { data, theme } = state;
const tabs = [
{ key: 'profile', name: data.profile.heading },
{ key: 'outreach', name: data.outreach.heading },
{ key: 'followup', name: data.followup.heading },
{ key: 'actions', name: t('actions.title') },
{ key: 'about', name: t('about.title') },
];
const [currentTab, setCurrentTab] = useState(tabs[0].key);
const onChange = (key, value) => {
dispatch({
type: 'on_input',
payload: {
key,
value,
},
});
dispatch({ type: 'save_data' });
};
const renderTabs = () => {
switch (currentTab) {
case tabs[0].key:
return <ProfileTab data={data} onChange={onChange} />;
case tabs[1].key:
return <OutreachTab data={data} onChange={onChange} />;
case tabs[2].key:
return <FollowupTab data={data} onChange={onChange} />;
case tabs[3].key:
return <ActionsTab data={data} theme={theme} dispatch={dispatch} />;
case tabs[4].key:
return <AboutTab />;
default:
return null;
}
};
return (
<div
id="leftSidebar"
className="z-10 py-6 md:h-screen bg-white col-span-1 shadow-2xl overflow-y-scroll"
>
<TabBar tabs={tabs} currentTab={currentTab} setCurrentTab={setCurrentTab} />
<div className="px-6">{renderTabs()}
);
};
export default LeftSidebar;
|
javascript
| 16 | 0.607477 | 88 | 28.181818 | 66 |
starcoderdata
|
import { observable, action } from 'mobx';
import GroupApi from '../api/groups';
import { authStore } from '../stores/AuthStore';
import handleError from '../helpers/handleError';
export class GroupStore {
@observable groupList = [];
@observable closeModal = false;
@action
async getAll() {
try {
this.groupList = await GroupApi.getAll(authStore.token);
} catch (error) {
handleError(error);
} finally {
}
}
@action
async create(data) {
try {
const result = await GroupApi.create({
token: authStore.token,
...data
});
this.closeModal = true;
this.groupList.push(result.group_info);
} catch (error) {
handleError(error);
} finally {
this.closeModal = false;
}
}
@action
async update(groupId, data) {
try {
const result = await GroupApi.updateById(authStore.token, groupId, data);
this.closeModal = true;
this.groupList = this.groupList.map(el => el._id === groupId ? result : el);
} catch (error) {
handleError(error);
} finally {
this.closeModal = false;
}
}
@action
async delete(id) {
try {
await GroupApi.delete(authStore.token, id);
this.groupList = this.groupList.filter(e => e._id !== id);
} catch (error) {
handleError(error);
}
}
@action
setListToInitState() {
this.groupList = [];
}
}
export const groupStore = new GroupStore();
|
javascript
| 15 | 0.606 | 82 | 19.283784 | 74 |
starcoderdata
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class user extends CI_Controller {
public function __construct()
{
parent::__construct(); //memanggil method contructor pd controller
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('kepegawaian_model');
$this->load->model('cetak_model_pegawai');
}
public function index()
{
$data = array(
"title" => 'Data Pegawai',
"kepegawaian" => $this->kepegawaian_model->datatabels()
);
$this->load->view('admin/template/header_datatabels_pegawai',$data);
$this->load->view('admin/kepegawaian/user',$data);
$this->load->view('admin/template/footer_datatabels_pegawai');
}
public function laporan_pdf($Id){
$this->load->library('pdf_pegawai');
$data['kepegawaian'] = $this->cetak_model_pegawai->getdatabyID($Id);
$this->pdf_pegawai->setPaper('A4', 'portrait');
$this->pdf_pegawai->filename = "laporan.pdf";
$this->pdf_pegawai->load_view('admin/kepegawaian/laporan', $data);
}
}
/* End of file Controllername.php */
|
php
| 12 | 0.58804 | 76 | 28.365854 | 41 |
starcoderdata
|
void WipeWindowList ()
{
WindowList& List = GetWindowList();
WindowList::iterator it = List.begin();
while (it != List.end())
{
// if the window isn't valid, erase it
if (!::IsWindow (*it))
{
WindowList::iterator itErase = it++;
List.erase(itErase);
}
// this one's OK, check the next one
else
++it;
}
}
|
c++
| 11 | 0.452703 | 51 | 21.473684 | 19 |
inline
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:08:31 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/PrivateFrameworks/ProVideo.framework/ProVideo
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Updated by
*/
#import
#import
@class PVVideoCompositingContext, PVVideoCompositing, AVAsynchronousVideoCompositionRequest, PVVideoCompositionInstruction, PVTaskToken, NSString;
@interface PVAVFRenderJobDelegate : NSObject {
PVVideoCompositing* m_compositor;
AVAsynchronousVideoCompositionRequest* m_request;
PVVideoCompositionInstruction* m_instruction;
SCD_Struct_PV21 m_compositionTime;
BOOL m_thumbnailCompositing;
CVBufferRef m_destinationPixelBuffer;
unsigned m_minimumRequestCompletionTimeMS;
PerfTimer m_timer;
unsigned m_childCode;
HGCVGLTextureFactory* m_hgCVGLTextureFactory;
HGRef m_renderManager;
HGRef m_instructionGraphContext;
unsigned m_parentCode;
PVTaskToken* _token;
}
@property (readonly) SCD_Struct_PV21 compositionTime;
@property (readonly) PVVideoCompositionInstruction * compositionInstruction;
@property (readonly) AVAsynchronousVideoCompositionRequest * compositionRequest;
@property (assign) unsigned minimumRequestCompletionTimeMS;
@property (assign) unsigned parentCode;
@property (assign) unsigned childCode;
@property (retain) PVTaskToken * token; //@synthesize token=_token - In the implementation block
@property (readonly) unsigned jobTypeTag;
@property (readonly) PVVideoCompositingContext * videoCompositingContext;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(unsigned)jobTypeTag;
-(PVTaskToken *)token;
-(void)setToken:(PVTaskToken *)arg1 ;
-(SCD_Struct_PV21)compositionTime;
-(PVVideoCompositingContext *)videoCompositingContext;
-(void)finishCancelledJob;
-(int)jobPriority;
-(int)renderContextPriority;
-(unsigned)jobTypeTag;
-(void)buildGraph:(vector std::__1::allocator renderContext:(const HGRenderContext*)arg2 frameStats:(FrameStats*)arg3 ;
-(int)renderThreadPriority;
-(void)setupDestinationBuffers:(vector std::__1::allocator renderContext:(const HGRenderContext*)arg2 frameStats:(FrameStats*)arg3 ;
-(void)finishCompletedJob;
-(void)renderJobFinished:(HGRef ;
-(unsigned long long)packedFamilyCode;
-(void)_setupGLTextureFactory:(const HGRenderContext*)arg1 ;
-(void)_setupInputs:(PVInputHGNodeMap<PVInstructionGraphSourceNode *>*)arg1 renderContext:(const HGRenderContext*)arg2 frameStats:(FrameStats*)arg3 ;
-(void)_buildGraph:(PVInputHGNodeMap<PVInstructionGraphSourceNode *>*)arg1 renderContext:(const HGRenderContext*)arg2 frameStats:(FrameStats*)arg3 outputNodes:(vector std::__1::allocator ;
-(unsigned)parentCode;
-(id)initWithCompositor:(id)arg1 request:(id)arg2 compositionTime:(SCD_Struct_PV21)arg3 thumbnailCompositing:(BOOL)arg4 ;
-(PVVideoCompositionInstruction *)compositionInstruction;
-(AVAsynchronousVideoCompositionRequest *)compositionRequest;
-(unsigned)minimumRequestCompletionTimeMS;
-(void)setMinimumRequestCompletionTimeMS:(unsigned)arg1 ;
-(void)setParentCode:(unsigned)arg1 ;
-(unsigned)childCode;
-(void)setChildCode:(unsigned)arg1 ;
@end
|
c
| 9 | 0.768184 | 225 | 49.96 | 75 |
starcoderdata
|
const mongoose = require("mongoose");
const { User, GuildAchievements, Achievement, Account } = require("./models/index");
module.exports = Root => {
Root.createUser = async user => {
const merged = Object.assign({ _id: mongoose.Types.ObjectId() }, user);
const createUser = new User(merged);
createUser.save().then(u => console.log(`nouvel utilisateur -> ${u.username}`));
};
Root.getUser = async user => {
const data = await User.findOne({userID: user.id });
if (data) return data;
else return;
};
Root.updateUser = async (user, settings) => {
let data = await Root.getUser(user);
if (typeof data != "object") data = {};
for (const key in settings) {
if (data[key] !== settings[key]) data[key] = settings[key];
}
return data.updateOne(settings);
}
Root.removeUser = async user => {
await User.findOneAndDelete({ userID: user.id});
await Achievement.findOneAndDelete({ userID: user.id });
const allUserAccount = await Root.getUserAccounts(user.id);
if (!allUserAccount) return;
else Account.findOneAndDelete({ userID: user.id });
}
Root.updateXp = async (Root, member, xp) => {
const UpdateUser = await Root.getUser(member);
const XpAdd = UpdateUser.experience + xp;
await Root.updateUser(member, { experience: XpAdd });
}
Root.updatePosition = async (Root, member) => {
const updateUser = await Root.getUser(member);
const positionUp = updateUser.pos + 1;
await Root.updateUser(member, { pos: positionUp });
}
Root.emoji = (id) => {
return Root.emojis.cache.get(id).toString();
}
Root.createGuildAchievement = () => {
const merged = Object.assign({ _id: mongoose.Types.ObjectId() });
const createUser = new GuildAchievement(merged);
createUser.save().then(u => console.log(`Achievements du serveur créé`));
}
Root.getGuildAchievement = () => {
const data = GuildAchievements.findOne();
if (data) return data;
else return;
}
Root.getAllGuildAchievements = () => {
const data = GuildAchievements.find();
if (data) return data;
else return;
}
Root.getUserAchievement = user => {
const data = Achievement.find( { userID: user.id } );
if (data) return data;
else return;
}
Root.createUserAchievement = user => {
const merged = Object.assign({ _id: mongoose.Types.ObjectId() }, user);
const createUser = new Achievement(merged);
createUser.save().then(u => console.log(`Achievements de l'utilisateur: ${u.username} créé`));
}
Root.createAccount = (user) => {
const merged = Object.assign({ _id: mongoose.Types.ObjectId() }, user);
const createBankAccount = new Account(merged);
createBankAccount.save().then(u => console.log(`Compte de l'utilisateur ${u.username} créé`)).catch(console.error);
}
Root.getUserAccount = user => {
const data = Account.findOne({ userID: user.id });
if (data) return data;
else return;
}
Root.getUserAccounts = user => {
const data = Account.find({ userID: user.id });
if (data) return data;
else return;
}
Root.getUserAccountByName = (user, accountName) => {
const data = Account.findOne({ userID: user.id, name: accountName});
if (data) return data;
else return;
}
Root.updateBankAccount = async (user, accountName, settings) => {
let data = await Root.getUserAccountByName(user, accountName);
if (typeof data != "object") data = {};
for (const key in settings) {
if (data[key] !== settings[key]) data[key] = settings[key];
}
return data.updateOne(settings);
}
Root.updateMoney = async (user, accountName, streak, moneyToAdd) => {
const data = await Root.getUserAccountByName(user, accountName);
const updateStreak = streak + 1;
const newTime = new Date().getHours();
const newAmount = data.money + moneyToAdd
Root.updateBankAccount(user, accountName, {money: newAmount, time: newTime, streak: updateStreak});
}
}
|
javascript
| 20 | 0.587065 | 123 | 35.159664 | 119 |
starcoderdata
|
package login
import (
"context"
"github.com/grafana/grafana/pkg/models"
)
type AuthInfoService interface {
LookupAndUpdate(ctx context.Context, query *models.GetUserByAuthInfoQuery) (*models.User, error)
GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error
SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error
UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error
}
|
go
| 9 | 0.806897 | 97 | 30.071429 | 14 |
starcoderdata
|
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Database Key Column
|--------------------------------------------------------------------------
|
| this should be the name of the primary key column
|
| Default: 'id'
|
*/
$config['crud_db_key'] = 'id';
/*
|--------------------------------------------------------------------------
| Database Created Column
|--------------------------------------------------------------------------
|
| this should be the name of the record "created on" column
|
| Default: 'id'
|
*/
$config['crud_db_created'] = 'created_on';
/*
|--------------------------------------------------------------------------
| Database Created Column
|--------------------------------------------------------------------------
|
| this should be the name of the record "last modified" column, if you are
| using MySQL, this field should be set to type TIMESTAMP
|
| Default: 'id'
|
*/
$config['crud_db_modified'] = 'mod_on';
/*
|--------------------------------------------------------------------------
| Encrypt Data
|--------------------------------------------------------------------------
|
| Should the data be encrypted before inseration into the database,
| and decrypted before output?
|
| IMPORTANT: You must set this value BEFORE any data is in the tables
|
| Default: false
|
*/
$config['crud_db_encrypted'] = false;
/* End of file crud.php */
/* Location: ./application/config/crud.php */
|
php
| 7 | 0.406924 | 75 | 29.039216 | 51 |
starcoderdata
|
package io.vertx.tp.ke.refine;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.tp.plugin.database.DataPool;
import io.vertx.up.commune.config.Database;
import io.vertx.up.eon.KName;
import io.vertx.up.eon.Strings;
import io.vertx.up.uca.yaml.Node;
import io.vertx.up.uca.yaml.ZeroUniform;
import io.vertx.up.unity.Ux;
import io.vertx.up.util.Ut;
import org.jooq.Configuration;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Supplier;
class KeTool {
private static final Node VISITOR = Ut.singleton(ZeroUniform.class);
private static String DATABASE;
static String getCatalog() {
if (Ut.isNil(DATABASE)) {
final JsonObject config = VISITOR.read();
DATABASE = Ut.visitString(config, "jooq", "provider", "catalog");
}
return DATABASE;
}
static Configuration getConfiguration() {
final Database database = Database.getCurrent();
final DataPool pool = DataPool.create(database);
return pool.getExecutor().configuration();
}
static Future map(final JsonObject data, final String field,
final ConcurrentMap<String, JsonObject> attachmentMap,
final BiFunction<JsonObject, JsonArray, Future fileFn) {
/*
* Here call add only
*/
final String key = data.getString(field);
Objects.requireNonNull(key);
final ConcurrentMap<String, Future futures = new ConcurrentHashMap<>();
attachmentMap.forEach((fieldF, condition) -> {
/*
* Put `key` of data into `modelKey`
*/
final JsonObject criteria = condition.copy();
if (Ut.notNil(criteria)) {
criteria.put(Strings.EMPTY, Boolean.TRUE);
criteria.put(KName.MODEL_KEY, key);
/*
* JsonArray normalize
*/
final JsonArray dataArray = Ut.valueJArray(data, fieldF);
Ut.itJArray(dataArray).forEach(json -> json.put(KName.MODEL_KEY, key));
futures.put(fieldF, fileFn.apply(criteria, dataArray));
} else {
/*
* Log
*/
KeLog.warnChannel(KeTool.class, "Criteria must be not empty");
}
});
return Ux.thenCombine(futures).compose(mapData -> {
mapData.forEach(data::put);
return Ux.future(data);
});
}
static void consume(final Supplier supplier, final Consumer consumer) {
final T input = supplier.get();
if (Objects.nonNull(input)) {
if (input instanceof String) {
if (Ut.notNil((String) input)) {
consumer.accept(input);
}
} else {
consumer.accept(input);
}
}
}
static void banner(final String module) {
System.out.println("-------------------------------------------------------------");
System.out.println("| |");
System.out.println("| Zero Extension: " + module);
System.out.println("| |");
System.out.println("-------------------------------------------------------------");
}
}
|
java
| 19 | 0.5552 | 102 | 36.878788 | 99 |
starcoderdata
|
<?php
/**
* 商品详描
* @author auto create
*/
class DetailSource
{
/**
* 详描locale
**/
public $locale;
/**
* 移动端详描内容,具体格式请参考:https://developers.aliexpress.com/doc.htm?docId=109513&docType=1
**/
public $mobile_detail;
/**
* PC 端详描内容,具体格式请参考:https://developers.aliexpress.com/doc.htm?docId=109513&docType=1
**/
public $web_detail;
}
?>
|
php
| 6 | 0.630556 | 85 | 13.44 | 25 |
starcoderdata
|
private void mutationMethodsInListDataView() {
// The initial data
ArrayList<String> items = new ArrayList<>(Arrays.asList("foo", "bar"));
// Get the data view when binding it to a component
Select<String> select = new Select<>();
SelectListDataView<String> dataView = select.setItems(items);
TextField newItemField = new TextField("Add new item");
Button addNewItem = new Button("Add", e -> {
// Adding through the data view API mutates the data source
dataView.addItem(newItemField.getValue());
});
Button remove = new Button("Remove selected", e-> {
// Same for removal
dataView.removeItem(select.getValue());
});
// Hook to item count change event
dataView.addItemCountChangeListener(e ->
Notification.show(" " + e.getItemCount() + " items available"));
// Request the item count directly
Span itemCountSpan = new Span("Total Item Count: " + dataView.getItemCount());
}
|
java
| 14 | 0.611164 | 86 | 41.32 | 25 |
inline
|
using System;
using vts.Shared.Services;
namespace vts.Core.Shared.Entities.Master
{
public enum EntityStatus { New = 0, Active = 1, Inactive = 2, Deleted = 3 }
public abstract class MasterDataRef
{
public Guid Id { get; set; }
public abstract MasterDataCollection MasterDataType { get; }
public abstract Tuple<bool, string> IsValid();
protected static T CreateEmpty where T : MasterDataRef, new()
{
T o = new T();
o.CreatEmptyImpl();
return o;
}
protected abstract void CreatEmptyImpl();
}
public abstract class MasterEntity where T : MasterDataRef
{
protected MasterEntity(Guid id)
{
Id = id;
}
protected MasterEntity(Guid id, DateTime dateCreated, DateTime dateLastUpdated, EntityStatus status)
: this(id)
{
DateCreated = dateCreated;
DateLastUpdated = dateLastUpdated;
Status = status;
}
public Guid Id { get; set; }
public DateTime DateCreated { get; set; }
internal void _SetDateCreated(DateTime dateCreated)
{
DateCreated = dateCreated;
}
public DateTime DateLastUpdated { get; set; }
internal void _SetDateLastUpdated(DateTime dateLastUpdated)
{
DateLastUpdated = dateLastUpdated;
}
public EntityStatus Status { get; set; }
internal void _SetStatus(EntityStatus status)
{
Status = status;
}
public abstract T GetMasterDataRef();
public abstract ValidationResultInfo Validate();
}
}
|
c#
| 13 | 0.586918 | 108 | 24.727273 | 66 |
starcoderdata
|
package com.acierto.java11;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
class A {
public List getValues(Set input) {
return null;
}
}
class B extends A {
public List getValues(Set input) {
return null;
}
public List getValues(TreeSet input) {
return null;
}
}
public class Overriding {
}
|
java
| 8 | 0.661215 | 60 | 16.833333 | 24 |
starcoderdata
|
protected override void OnUpdate()
{
NativeSummedFloat3 avgPosition = new NativeSummedFloat3(Allocator.TempJob);
NativeSummedFloat3.ParallelWriter avgPositionParallelWriter = avgPosition.AsParallelWriter();
// Sum together all positions of entities with a LocalToWorld component.
JobHandle jobHandle = Entities.WithName("AvgPositionJob")
.WithStoreEntityQueryInField(ref localToWorldQuery)
.ForEach((in LocalToWorld localToWorld) =>
{
avgPositionParallelWriter.AddValue(localToWorld.Position);
}).ScheduleParallel(default);
jobHandle.Complete();
// We store the query so we can calculate how many entities have the LocalToWorld component.
int entityCount = localToWorldQuery.CalculateEntityCount();
UnityEngine.Debug.Log(avgPosition.Value / entityCount);
avgPosition.Dispose();
}
|
c#
| 20 | 0.791209 | 95 | 38.047619 | 21 |
inline
|
import { types } from "mobx-state-tree";
import lodash from "../../utils/lodash";
import { guidGenerator, restoreNewsnapshot } from "../../core/Helpers";
const ControlBase = types
.model({})
.views(self => ({
get serializableValue() {
const obj = {};
obj[self.type] = self.selectedValues();
return obj;
},
}))
.actions(self => ({}));
export default ControlBase;
|
javascript
| 9 | 0.633333 | 71 | 24 | 18 |
starcoderdata
|
namespace CityWeatherOperator.Crd
{
public class CityWeatherResourceSpec
{
public string City { get; set; }
public int? Replicas { get; set; }
}
}
|
c#
| 8 | 0.628571 | 42 | 21 | 8 |
starcoderdata
|
func CreateGitHubWebhook(accessToken string, webhookUrl string, webhookSecret string, GitOrgProject string, GitRepository string) error {
sslVrf := "0"
if strings.ToLower(sslVerification) == "false" {
sslVrf = "1"
}
ctx := InitGitHubClient(accessToken)
hook := &github.Hook{
Events: []string{"push", "pull_request", "delete"},
Active: github.Bool(true),
Config: map[string]interface{}{
"url": webhookUrl,
"content_type": "json",
"secret": webhookSecret,
"insecure_ssl": sslVrf,
},
}
if _, _, err := githubClient.Repositories.CreateHook(ctx, GitOrgProject, GitRepository, hook); err != nil {
// Ignore exists error if the list doesn't return all installed hooks
if strings.Contains(err.Error(), "Hook already exists on this repository") {
return nil
}
return err
}
return nil
}
|
go
| 15 | 0.682198 | 137 | 27.896552 | 29 |
inline
|
<?php
namespace Hank\UI\Symfony\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SignInController extends Controller
{
public function index(Request $request, AuthenticationUtils $authenticationUtils): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('authorization/sign-in.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
}
|
php
| 12 | 0.728155 | 95 | 27.88 | 25 |
starcoderdata
|
package com.stylefeng.guns.rest.modular.order.responser;
import com.stylefeng.guns.rest.core.SimpleResponser;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @Description //TODO
* @Author 罗华
* @Date 2018/11/30 8:18
* @Version 1.0
*/
@ApiModel(value = "OrderPostResponser", description = "订单提交返回")
public class OrderPostResponser extends SimpleResponser {
@ApiModelProperty(name = "data", value = "提交返回")
private OrderData data;
public OrderData getData() {
return data;
}
public void setData(OrderData data) {
this.data = data;
}
public static OrderPostResponser me(String orderNo, String paySequence) {
OrderPostResponser response = new OrderPostResponser();
response.setCode(SUCCEED);
response.setMessage("处理成功");
OrderData data = new OrderData();
data.setOrderNo(orderNo);
data.setPaySequence(paySequence);
response.setData(data);
return response;
}
@ApiModel
static class OrderData {
@ApiModelProperty(value = "订单号", example = "OD181130202020022")
private String orderNo;
@ApiModelProperty(value = "支付流水", example = "wx201410272009395522657a690389285100")
private String paySequence;
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getPaySequence() {
return paySequence;
}
public void setPaySequence(String paySequence) {
this.paySequence = paySequence;
}
}
}
|
java
| 11 | 0.651995 | 91 | 26.047619 | 63 |
starcoderdata
|
package nl.uva.larissa.json.model.validate;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.i18n.iri.IRIHelper;
public class MailtoIRIValidator implements ConstraintValidator<MailToIRI, IRI> {
@Override
public void initialize(MailToIRI constraintAnnotation) {
}
@Override
public boolean isValid(IRI iri, ConstraintValidatorContext context) {
return iri == null || IRIHelper.isMailtoUri(iri);
}
}
|
java
| 9 | 0.801115 | 80 | 24.619048 | 21 |
starcoderdata
|
<?php
/**
* Copyright (c) NMS PRIME GmbH ("NMS PRIME Community Version")
* and others – powered by CableLabs. 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.
*/
namespace App\Http\Controllers\Auth;
use App;
use App\BaseModel;
use Carbon\Carbon;
use App\GlobalConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Nwidart\Modules\Facades\Module;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Silber\Bouncer\BouncerFacade as Bouncer;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
private $prefix = 'admin';
/**
* Return a instance of the used guard
*/
protected function guard()
{
return Auth::guard('admin');
}
/**
* Change Login Check Field to login_name
* Laravel Standard: email
*/
public function username()
{
return 'login_name';
}
/**
* Show Login Page
*
* @return view
*/
public function showLoginForm()
{
$intended = null;
$prefix = $this->prefix;
$globalConfig = GlobalConfig::first();
$head1 = $globalConfig->headline1;
$head2 = $globalConfig->headline2;
$image = 'main-pic-1.jpg';
$loginPage = 'admin';
$logo = asset('images/nmsprime-logo-white.png');
if (session()->has('url.intended') && $pos = strpos($url = session('url.intended'), 'admin')) {
$intended = substr($url, $pos + 6); // pos + admin/
}
return \View::make('auth.login', compact('head1', 'head2', 'prefix', 'image', 'loginPage', 'logo', 'intended'));
}
/**
* Attempt to log the user into the application.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function attemptLogin(Request $request)
{
if (! $this->guard()->attempt($this->credentials($request), $request->filled('remember'))) {
return false;
}
$user = Auth::user();
if (! $user->active) {
Log::info("User {$user->login_name} denied: User is inactive");
return false;
}
if (! count($user->roles)) {
Log::info("User {$user->login_name} denied: User has no roles assigned");
return false;
}
return true;
}
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param App\User $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
// Set (cached) session key with model namespaces for authorization functionaity
BaseModel::get_models();
$request->session()->put('GlobalNotification', []);
App::setLocale(\App\Http\Controllers\BaseViewController::get_user_lang());
if ($user->isPasswordExpired() || $user->isFirstLogin()) {
$request->session()->flash('GlobalNotification', [
'shouldChangePassword' => [
'message' => 'shouldChangePassword',
'level' => 'danger',
'reason' => $user->isPasswordExpired() ? 'PasswordExpired' : 'newUser',
],
]);
}
self::setDashboardNotifications();
// do not try to update user on ha slave machines
if (\Module::collections()->has('ProvHA')) {
if ('master' != config('provha.hostinfo.ownState')) {
return;
}
}
$user->update(['last_login_at' => Carbon::now()]);
}
/**
* Set global notification messages in session on login
*/
private static function setDashboardNotifications()
{
$alerts = [];
$conf = GlobalConfig::first();
if ($conf->alert1) {
$alerts['alert1'] = [
'message' => $conf->alert1,
'level' => 'info',
'reason'=>'', ];
}
if ($conf->alert2) {
$alerts['alert2'] = [
'message' => $conf->alert2,
'level' => 'warning',
'reason' => '', ];
}
if ($conf->alert3) {
$alerts['alert3'] = [
'message' => $conf->alert3,
'level' => 'danger',
'reason' => '', ];
}
\Session::flash('DashboardNotification', $alerts);
}
/**
* Show Default Page after successful login
*
* @return type Redirect
*/
public function redirectTo()
{
$user = Auth::user();
$activeModules = Module::collections();
Log::debug($user->login_name.' logged in successfully!');
if ($activeModules->has('Ticketsystem') && $this->isMobileDevice()) {
return route('TicketReceiver.index');
}
if ($user->initial_dashboard) {
return route($user->initial_dashboard);
}
if ($activeModules->has('Dashboard')) {
return route('Dashboard.index');
}
if ($activeModules->has('ProvBase') && Bouncer::can('view', \Modules\ProvBase\Entities\Contract::class)) {
return route('Contract.index');
}
if (Bouncer::can('view', \Modules\HfcReq\Entities\NetElement::class)) {
return route('NetElement.index');
}
return route('GlobalConfig.index');
}
/**
* Detect Mobile Device with regular expression from http://detectmobilebrowsers.com/
*
* @return bool
*/
protected function isMobileDevice(): bool
{
$useragent = $_SERVER['HTTP_USER_AGENT'];
return preg_match(isMobileRegEx(1), $useragent) || preg_match(isMobileRegEx(2), substr($useragent, 0, 4));
}
/**
* This function will be called if user has no access to a certain area
* or has no valid login at all.
*/
public function denied($message)
{
return \View::make('auth.denied')->with('message', $message);
}
}
|
php
| 18 | 0.554812 | 120 | 27.90535 | 243 |
starcoderdata
|
<?php declare(strict_types=1);
namespace Wisembly\AmqpBundle\Processor;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Output\OutputInterface;
class ProcessFactoryTest extends TestCase
{
public function test_it_is_instantiable()
{
$this->assertInstanceOf(ProcessFactory::class, new ProcessFactory('foo'));
}
public function test_it_prepares_a_process()
{
$process = new Process(
[
PHP_BINARY,
'foo',
'bar',
]
);
$commandLine = $process->getCommandLine();
$factory = new ProcessFactory('foo');
$process = $factory->create('bar', []);
$this->assertSame($commandLine, $process->getCommandLine());
}
/** @dataProvider verbosityProvider */
public function test_the_verbosity_is_added(int $level, string $argument)
{
$process = new Process(
array_filter([
PHP_BINARY,
'foo',
'bar',
$argument
])
);
$commandLine = $process->getCommandLine();
$factory = new ProcessFactory('foo');
$process = $factory->create('bar', [], null, $level);
$this->assertSame($commandLine, $process->getCommandLine());
}
public function verbosityProvider(): iterable
{
return [
'debug' => [OutputInterface::VERBOSITY_DEBUG, '-vvv'],
'very verbose' => [OutputInterface::VERBOSITY_VERY_VERBOSE, '-vv'],
'verbose' => [OutputInterface::VERBOSITY_VERBOSE, '--verbose'],
'quiet' => [OutputInterface::VERBOSITY_QUIET, '--quiet'],
'normal' => [OutputInterface::VERBOSITY_NORMAL, ''],
];
}
public function test_it_passes_the_stdin_if_given()
{
$factory = new ProcessFactory('foo');
$process = $factory->create('bar', [], 'baz');
$this->assertSame('baz', $process->getInput());
}
}
|
php
| 16 | 0.56161 | 82 | 27.291667 | 72 |
starcoderdata
|
package org.examples.j2se.j2se;
/**
* Description : TODO(双重校验锁方式创建,适应多线程的单例模式 example)
* Description : TODO(有的设计模式说,用枚举的方式实现更好,没有测试)
* User: h819
* Date: 14-4-25
* Time: 下午12:24
* To change this template use File | Settings | File Templates.
*/
public class SingletonExample {
private static volatile SingletonExample INSTANCE = null;
// Private constructor suppresses
// default public constructor
private SingletonExample() {
}
//thread safe and performance promote
public static SingletonExample getInstance() {
if (INSTANCE == null) {
synchronized (SingletonExample.class) {
//when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again.
if (INSTANCE == null) {
INSTANCE = new SingletonExample();
}
}
}
return INSTANCE;
}
/**
* 单例模式中的方法,写法如下
*/
public void method() {
}
/**
* 调用方法
*/
private void example() {
SingletonExample.getInstance().method();
}
}
|
java
| 15 | 0.601196 | 154 | 21.519231 | 52 |
starcoderdata
|
//
// MPBannerAdManager+Testing.h
//
// Copyright 2018-2020 Twitter, Inc.
// Licensed under the MoPub SDK License Agreement
// http://www.mopub.com/legal/sdk-license-agreement/
//
#import "MPBannerAdManager.h"
@interface MPBannerAdManager (Testing)
@property (nonatomic, strong) MPAdServerCommunicator *communicator;
@property (nonatomic, strong) MPInlineAdAdapter *onscreenAdapter;
@property (nonatomic, strong) MPInlineAdAdapter *requestingAdapter;
@end
|
c
| 5 | 0.776371 | 67 | 28.625 | 16 |
starcoderdata
|
package io.github.jokoframework.misc;
import io.github.jokoframework.model.UserAccessResponse;
public interface ProcessError {
void afterProcessError(UserAccessResponse response);
void afterProcessError(String message);
void afterProcessErrorNoConnection();
}
|
java
| 6 | 0.810909 | 56 | 26.5 | 10 |
starcoderdata
|
# -*- encoding: utf-8 -*-
import dsl
from shapely.wkt import loads as wkt_loads
from . import FixtureTest
class DisusedRailwayStations(FixtureTest):
def test_old_south_ferry(self):
# Old South Ferry (1) (disused=yes)
self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 40.701283821753)'), {
u'name': u'Old South Ferry (1)', u'wheelchair': u'no', u'source': u'openstreetmap.org', u'railway': u'station', u'disused': u'yes', u'network': u'New York City Subway'}))
self.assert_no_matching_feature(
16, 19294, 24643, 'pois',
{'kind': 'station', 'id': 2086974744})
def test_valle_az(self):
# Valle, AZ (disused=station)
self.generate_fixtures(dsl.way(366220389, wkt_loads('POINT (-112.200039193448 35.65261688375637)'), {
u'name': u'Valle', u'gnis:reviewed': u'no', u'addr:state': u'AZ', u'ele': u'1794', u'source': u'openstreetmap.org', u'gnis:feature_id': u'21103', u'disused': u'station', u'gnis:county_name': u'Coconino'}))
self.assert_no_matching_feature(
16, 12342, 25813, 'pois',
{'id': 366220389})
|
python
| 13 | 0.603161 | 236 | 45.230769 | 26 |
starcoderdata
|
#!/usr/bin/env python3
"""
Solution to the challenge #16 of the "Advent of Code 2017" series.
MIT License
Copyright (c) 2017 (
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
#START = "abcde"
#input_file = "sample_input_16"
START = "abcdefghijklmnop"
input_file = "input_16"
order = list(START)
# Dance figures:
def spin(size):
global order
divider = len(order) - size
order = order[divider:] + order[:divider]
def exchange(pos1, pos2):
global order
order[pos1], order[pos2] = order[pos2], order[pos1]
def partner(name1, name2):
global order
pos1 = order.index(name1)
pos2 = order.index(name2)
order[pos1], order[pos2] = order[pos2], order[pos1]
input_data = [line.strip() for line in open(input_file, "r")]
moves = input_data[0].split(",")
# Challenge A:
for move in moves:
category = move[0]
data = move[1:]
if category == "s":
spin(int(data))
elif category == "x":
indices = data.split("/")
exchange(int(indices[0]), int(indices[1]))
elif category == "p":
partners = data.split("/")
partner(partners[0], partners[1])
print("[Challenge A] Final order: ", end="")
print("".join(order))
# Challenge B: Check whether there is a cycle (position repeated after N iters):
START = "abcdefghijklmnop"
TOTAL_ITERATIONS = 1000 * 1000 * 1000
order = list(START)
previous_orders = set()
consecutive_iterations = []
cycle_length = None
for i in range(TOTAL_ITERATIONS):
for move in moves:
category = move[0]
data = move[1:]
if category == "s":
spin(int(data))
elif category == "x":
indices = data.split("/")
exchange(int(indices[0]), int(indices[1]))
elif category == "p":
partners = data.split("/")
partner(partners[0], partners[1])
strorder = "".join(order) # a list is unhashable, but a string is.
if strorder in previous_orders:
print("Repetition found after {} iterations.".format(i))
cycle_length = i
break
else:
previous_orders.add(strorder)
consecutive_iterations.append(strorder)
rem = TOTAL_ITERATIONS % i
print("[Challenge B] Final order: ", end="")
# Iterations go from 1 to 1B, but python's arrays are 0-indexed:
print(consecutive_iterations[rem-1])
|
python
| 14 | 0.677236 | 80 | 30.537736 | 106 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Xml;
namespace LectorFacturasXML.Clases
{
///
/// Nodo opcional para expresar las partes o componentes que integran la totalidad del concepto expresado en el
/// comprobante fiscal digital a través de Internet.
///
internal class Parte
{
public Parte()
{
infoAduanera = new List
infoAduanera = null;
}
private List infoAduanera { get; set; }
//Atributo requerido para expresar la clave del producto o del servicio amparado por la presente parte. Es requerido y deben utilizar las claves del catálogo de productos y servicios, cuando los conceptos que registren por sus actividades correspondan con dichos conceptos.
private string ClaveProdServ { set; get; }
//Atributo opcional para expresar el número de serie, número de parte del bien o identificador del producto o del servicio amparado por la presente parte. Opcionalmente se puede utilizar claves del estándar GTIN.
private string NoIdentificacion { set; get; }
//Atributo requerido para precisar la cantidad de bienes o servicios del tipo particular definido por la presente parte.
private float Cantidad { set; get; }
//Atributo opcional para precisar la unidad de medida propia de la operación del emisor, aplicable para la cantidad expresada en la parte. La unidad debe corresponder con la descripción de la parte.
private string Unidad { set; get; }
//Atributo requerido para precisar la descripción del bien o servicio cubierto por la presente parte.
private string Descripcion { set; get; }
//Atributo opcional para precisar el valor o precio unitario del bien o servicio cubierto por la presente parte. No se permiten valores negativos.
private float ValorUnitario { set; get; }
//Atributo opcional para precisar el importe total de los bienes o servicios de la presente parte. Debe ser equivalente al resultado de multiplicar la cantidad por el valor unitario expresado en la parte. No se permiten valores negativos.
private float Importe { set; get; }
internal void Cargar(XmlAttributeCollection attributes)
{
foreach (XmlAttribute at in attributes)
{
switch (at.Name.ToUpper())
{
case "CLAVEPRODSERV":
ClaveProdServ = at.Value;
break;
case "NOIDENTIFICACION":
NoIdentificacion = at.Value;
break;
case "CANTIDAD":
Cantidad = float.Parse(at.Value);
break;
case "UNIDAD":
Unidad = at.Value;
break;
case "DESCRIPCION":
Descripcion = at.Value;
break;
case "VALORUNITARIO":
ValorUnitario = float.Parse(at.Value);
break;
case "IMPORTE":
Importe = float.Parse(at.Value);
break;
default:
break;
}
}
}
internal void CargarNodos(XmlNode nParte)
{
//throw new NotImplementedException();
foreach (XmlNode n in nParte)
{
if (n.Name.ToUpper().Contains("INFORMACIONADUANERA"))
{
var nuevoInfoAduanera = new InformacionAduanera();
nuevoInfoAduanera.Cargar(n.Attributes);
nuevoInfoAduanera.CargarNodos(n);
infoAduanera.Add(nuevoInfoAduanera);
}
}
}
//Atributo opcional para precisar el importe total de los bienes o servicios de la presente parte. Debe ser equivalente al resultado de multiplicar la cantidad por el valor unitario expresado en la parte.
}
}
|
c#
| 18 | 0.591462 | 281 | 46.659091 | 88 |
starcoderdata
|
import React, { useEffect } from 'react';
import { useQuill } from 'react-quilljs';
import { updateActivityDay } from '../graphql/mutations';
import { API, graphqlOperation } from 'aws-amplify';
import 'quill/dist/quill.snow.css';
import { Button, Divider } from 'antd';
const MyEditor = ({ journalData, onJournalDataUpdate }) => {
const { quill, quillRef } = useQuill({
placeholder: "How did the day go? What could've gone better?",
modules: {
toolbar: [
['bold', 'italic', 'underline', 'strike'],
[{ align: [] }],
[{ list: 'ordered' }, { list: 'bullet' }],
[{ indent: '-1' }, { indent: '+1' }],
[{ size: ['small', false, 'large', 'huge'] }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
['clean'],
],
clipboard: {
matchVisual: false,
},
},
});
useEffect(() => {
quill && quill.setContents(JSON.parse(journalData));
}, [journalData, quill]);
return (
<main
style={{
height: '50vh',
}}
>
<div ref={quillRef} />
<Button
type="primary"
onClick={() => {
onJournalDataUpdate(JSON.stringify(quill.getContents()));
}}
>
Save
);
};
function Journal({ location }) {
const { currentDayID, displayDate, journalData = '{}' } = location.state;
console.log({ journalData });
const handleJournalDataUpdate = newJournalData => {
API.graphql(
graphqlOperation(updateActivityDay, {
input: { id: currentDayID, journalEntry: newJournalData },
})
);
};
return (
<h2 style={{ textAlign: 'center' }}>{displayDate}
<MyEditor
journalData={journalData}
onJournalDataUpdate={handleJournalDataUpdate}
/>
);
}
export default Journal;
|
javascript
| 21 | 0.538035 | 75 | 23.8125 | 80 |
starcoderdata
|
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Contact;
class ContactController extends Controller
{
public function index(){
$data['contact'] = Contact::all();
return view('admin.pages.contact')->with($data);
}
public function update(Request $request){
$request->validate([
'description' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'email' => 'required|email'
]);
$contact = Contact::find(1);
$contact->description = request('description');
$contact->address = request('address');
$contact->phone = request('phone');
$contact->email = request('email');
$contact->save();
$request->session()->flash('edit-success', 'Sent successfully');
return redirect(route('admin.contact'));
}
}
|
php
| 13 | 0.590437 | 72 | 25 | 37 |
starcoderdata
|
public void writeToStream(OutputStream os) throws IOException {
byte[] data = new byte[9];
copySF(data, Type.DATA, Category.IM_IMAGE);
// The size of the structured field
byte[] len = BinaryUtils.convert(rasterData.length + 8, 2);
data[1] = len[0];
data[2] = len[1];
os.write(data);
os.write(rasterData);
}
|
java
| 9 | 0.584 | 67 | 33.181818 | 11 |
inline
|
func TestAllowedGetGitArchive(t *testing.T) {
skipUnlessRealGitaly(t)
// Create the repository in the Gitaly server
apiResponse := realGitalyOkBody(t)
require.NoError(t, ensureGitalyRepository(t, apiResponse))
archivePath := path.Join(scratchDir, "my/path")
archivePrefix := "repo-1"
msg := serializedProtoMessage("GetArchiveRequest", &gitalypb.GetArchiveRequest{
Repository: &apiResponse.Repository,
CommitId: "HEAD",
Prefix: archivePrefix,
Format: gitalypb.GetArchiveRequest_TAR,
Path: []byte("files"),
})
jsonParams := buildGitalyRPCParams(gitalyAddress, rpcArg{"ArchivePath", archivePath}, msg)
resp, body, err := doSendDataRequest("/archive.tar", "git-archive", jsonParams)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode, "GET %q: status code", resp.Request.URL)
assertNginxResponseBuffering(t, "no", resp, "GET %q: nginx response buffering", resp.Request.URL)
// Ensure the tar file is readable
foundEntry := false
tr := tar.NewReader(bytes.NewReader(body))
for {
hdr, err := tr.Next()
if err != nil {
break
}
if hdr.Name == archivePrefix+"/" {
foundEntry = true
break
}
}
assert.True(t, foundEntry, "Couldn't find %v directory entry", archivePrefix)
}
|
go
| 14 | 0.711183 | 98 | 29.341463 | 41 |
inline
|
package secrets
import "context"
// KV is a basic key value store.
type KV interface {
Put(ctx context.Context, key string, data Values, options ...RequestOption) error
Get(ctx context.Context, key string, options ...RequestOption) (Values, error)
Delete(ctx context.Context, key string, options ...RequestOption) error
List(ctx context.Context, path string, options ...RequestOption) ([]string, error)
}
// KVClient is a basic key value store client.
type KVClient = KV
|
go
| 8 | 0.746862 | 83 | 33.142857 | 14 |
starcoderdata
|
fn load_links_in_attrs(&mut self, attrs: &[ast::Attribute], span: Span) {
use crate::html::markdown::markdown_links;
use crate::passes::collect_intra_doc_links::preprocess_link;
// FIXME: this probably needs to consider inlining
let attrs = crate::clean::Attributes::from_ast(attrs, None);
for (parent_module, doc) in attrs.collapsed_doc_value_by_module_level() {
debug!(?doc);
for link in markdown_links(doc.as_str()) {
debug!(?link.link);
let path_str = if let Some(Ok(x)) = preprocess_link(&link) {
x.path_str
} else {
continue;
};
self.resolver.borrow_mut().access(|resolver| {
let _ = resolver.resolve_str_path_error(
span,
&path_str,
TypeNS,
parent_module.unwrap_or_else(|| self.current_mod.to_def_id()),
);
});
}
}
}
|
rust
| 23 | 0.468635 | 86 | 40.730769 | 26 |
inline
|
<?php
namespace oframe\basics\backend\modules\sys\models;
use Yii;
/**
* 查询 Model
*/
class Search extends \yii\base\Model
{
/**
* 登录名
* @var string
*/
public $username;
/**
* 手机号
* @var string
*/
public $mobile_phone;
/**
* 邮箱
* @var string
*/
public $email;
/**
* 角色 ID
* @var int
*/
public $role_id;
public function rules()
{
return [
[['username', 'mobile_phone', 'email', 'role_id'], 'safe']
];
}
}
|
php
| 13 | 0.457565 | 70 | 12.243902 | 41 |
starcoderdata
|
void ReOrder(){
//exists so that the max values can be moved to the end easily
Node* Tail = this->Start;
while(Tail->Next != NULL){
Tail = Tail->Next;
}
bool done = false;
//runs until there are no nodes sorted on any given pass
while(done == false){
done = true;
//list traversal pointers
Node* temp = this->Start;
Node* prev = this->Start;
//keeping track of max and min words
string minWord = Start->word;
string maxWord = Tail->word;
//pass loop
while(temp->Next != NULL){
//these two statements are probably unneccessary,
//but in a long list they can make the runtime a
//bit faster by putting max and min values at the
//beginning and end of list, saving us more
//traversals //////
if(temp->word < minWord){ //
minWord = temp->word; //
prev->Next = temp->Next; //
temp->Next = this->Start; //
this->Start = temp; //
done = false; //
temp = prev; //
}else if(temp->word > maxWord){ //
maxWord = temp->word; //
prev->Next = temp->Next; //
temp->Next = NULL; //
Tail->Next = temp; //
Tail = temp; //
done = false; //
temp = prev; //////
//this basically just swaps two values if they
//aren't in order on that pass
}else if(temp->Next->word < temp->word){
prev->Next = temp->Next;
temp->Next = temp->Next->Next;
prev->Next->Next = temp;
done = false;
}
prev = temp;
temp = temp->Next;
}
}
}
|
c++
| 17 | 0.403492 | 66 | 39.769231 | 52 |
inline
|
package library.neetoffice.com.genericadapter.base;
import android.widget.AbsListView;
/**
* Created by Deo-chainmeans on 2016/10/15.
*/
class GenericScrollListener implements AbsListView.OnScrollListener {
private int firstVisibleItem;
private int visibleItemCount;
private int totalItemCount;
private final OnScrollCallBack callBack;
GenericScrollListener(OnScrollCallBack callBack) {
this.callBack = callBack;
}
public void onScroll(AbsListView view, int f, int v, int t) {
firstVisibleItem = f;
visibleItemCount = v;
totalItemCount = t;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == GenericScrollListener.SCROLL_STATE_IDLE & (firstVisibleItem + visibleItemCount + 1 >= totalItemCount)) {
callBack.onScrollEnd();
}
}
}
|
java
| 12 | 0.702055 | 131 | 27.258065 | 31 |
starcoderdata
|
from Cubes import *
from Generator import *
print "\n\n---This programm is created to solve the ***Block World Problem***! So the user is called to give an input\n", \
" of the test state and the goal state the states must be given in programm from the screen or from a file \n", \
" that is created -user choice.The codec of the states are being referred in the theoretical part of the exercise \n", \
" but in a summary each case is represented as tuple of tuples with the second one to be the stacks of \n ", \
" cubes starting from the top to the bottom. An important thing to notice is for the stacks that have only one cube\n", \
" the documented form is somthing like ('B',) with a comma as tuples with one element are represented in python documentation---\n\n"
ask = input("Give me 1 if you want to run a random test or 2 for a user settled problem\n")
if ask == 1 :
number = input("Give the magnitude of the Problem - Number of Cubes!\n")
r = Generator(number)
test_state = r.generate()
goal_state = r.generate()
print "The test state created from random generator is:\n",test_state,"\nThe goal_state created from random generator is:\n",goal_state
elif ask == 2:
test_state = input("Give me the state you want to test in tuples of tuples:\n")
goal_state = input("Give me the goal state you want to reach:\n")
else:
print >> sys.stderr, "Unknown behaviour for initializing Problem!\n"
sys.exit(1)
p = Cubes(test_state,goal_state)
heuristic = input("Select the number (1-3) of the Heuristic that you want to use as these are represented in theoretical section or in Main File\n")
if heuristic == 1:
s = astar_search(p,p.h1) # return 1 Approach
elif heuristic == 2:
s = astar_search(p,p.h2) # Wrong Place base on the Cube under
elif heuristic == 3:
s = astar_search(p,p.h3) # Height and Column Difference
else:
print >> sys.stderr, "Heuristic Function couldn't be found!"
sys.exit(1)
print "\n"
sol = s.solution() # The sequence of actions to go from the root to this node
path = s.path() # The nodes that form the path from the root to this node
print "Solution: \n+{0}+\n|Action\t|\t\t State \t\t\t|Path Cost |\n+{0}+".format('-'*42)
for i in range(len(path)) :
state = path[i].state
cost = path[i].path_cost
action = " "
if i > 0 : # The initial state has not an action that results to it
action = sol[i-1]
print "|{0}\t|{1} \t|{2} \t |".format(action, state, cost)
print "+{0}+".format('-'*42)
|
python
| 10 | 0.686236 | 148 | 48.431373 | 51 |
starcoderdata
|
<?php
namespace Spqr\Eventlist\Controller;
use Pagekit\Application as App;
use Spqr\Eventlist\Model\Event;
/**
* @Access(admin=true)
* @return string
*/
class EventController
{
/**
* @Access("eventlist: manage events")
* @Request({"filter": "array", "page":"int"})
* @param null $filter
* @param int $page
*
* @return array
*/
public function eventAction($filter = null, $page = 0)
{
return [
'$view' => [
'title' => 'Events',
'name' => 'spqr/eventlist:views/admin/event-index.php',
],
'$data' => [
'statuses' => Event::getStatuses(),
'config' => [
'filter' => (object)$filter,
'page' => $page,
],
],
];
}
/**
* @Route("/event/edit", name="event/edit")
* @Access("eventlist: manage events")
* @Request({"id": "int"})
* @param int $id
*
* @return array
*/
public function editAction($id = 0)
{
try {
$module = App::module('spqr/eventlist');
if (!$event = Event::where(compact('id'))->first()) {
if ($id) {
App::abort(404, __('Invalid event id.'));
}
$event = Event::create([
'status' => Event::STATUS_DRAFT,
'date' => new \DateTime(),
]);
$event->set('markdown', true);
}
return [
'$view' => [
'title' => $id ? __('Edit Event') : __('Add Event'),
'name' => 'spqr/eventlist:views/admin/event-edit.php',
],
'$data' => [
'event' => $event,
'statuses' => Event::getStatuses(),
'categories' => Event::getCategories(),
'config' => $module->config(),
],
];
} catch (\Exception $e) {
App::message()->error($e->getMessage());
return App::redirect('@eventlist/eventlist');
}
}
}
|
php
| 19 | 0.404027 | 75 | 26.470588 | 85 |
starcoderdata
|
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useHistory } from "react-router-dom";
import CustomAlertControl from "../AlertMessage";
import { userImpersonateSchoolSide } from "./MySchoolAction";
import {
getUserData,
} from "src/utility/utils";
const MySchool = () => {
const dispatch = useDispatch();
const history = useHistory();
useEffect(async () => {
if (getUserData().linked_email !== null) {
if (localStorage.getItem('impersonateStatusSchool') === "false") {
await dispatch(userImpersonateSchoolSide('impersonate'));
}
history.push("/home")
window.location.reload()
}
}, []);
return (
<>
<CustomAlertControl />
{getUserData().linked_email === null ?
<div className="myschoolData">
Join a School To View...
:
""
}
)
}
export default MySchool
|
javascript
| 21 | 0.648709 | 69 | 21.275 | 40 |
starcoderdata
|
// Copyright 2017-2018. See LICENSE file.
import Link from 'app/cater/link';
import React from 'react';
import Title from 'app/cater/title';
import '../assets/all.scss'; // Import a global stylesheet
// Import a number of different image types
import gif from '../assets/cat.gif';
import png from '../assets/cat.png';
import pngForceData from '../assets/cat.png.datauri';
import jpg from '../assets/cat.jpg';
import jpgTiny from '../assets/cat-tiny.jpg';
import svg from '../assets/cat.svg';
const title = 'Cats on Cats on Cats - Cater Asset Test';
// Bring back Geocities! Renders assets from the asset pipeline
export default () => (
<Link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" />
<Link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet" />
<img alt="Cute Cat GIF" src={gif} width="100" height="66" />
<img alt="Cute Cat PNG" src={png} width="100" height="66" />
<img alt="Cute Cat JPG" src={jpg} width="100" height="66" />
<img alt="Cute Cat SVG" src={svg} width="100" height="100" />
<a href=".">...
<hr />
Loaded as data URIs
<img alt="Tiny Cat JPG" src={jpgTiny} width="100" height="66" />
<img
alt="Cat PNG that's forced to be a data URI"
src={pngForceData}
width="100"
height="66"
/>
);
|
javascript
| 8 | 0.60705 | 89 | 28.461538 | 52 |
starcoderdata
|
<?php
namespace App\Http\Controllers\Export\Hotline;
use App\Contracts\Dealer\DealerInterface;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Product;
use App\Support\Product\ProductProfit;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;
class HotlineProductController extends Controller
{
/**
* @var Product
*/
private $product;
/**
* @var ProductProfit
*/
private $productProfit;
/**
* @var Category
*/
private $category;
/**
* HotlineCategoryController constructor.
* @param Category $category
* @param Product $product
* @param ProductProfit $productProfit
*/
public function __construct(Category $category, Product $product, ProductProfit $productProfit)
{
$this->product = $product;
$this->productProfit = $productProfit;
$this->category = $category;
}
/**
* @param int $categoryId
* @return View
*/
public function index(int $categoryId)
{
if (Gate::denies('vendor-catalog', auth('web')->user())) {
abort(401);
}
$category = $this->category->newQuery()->findOrFail($categoryId);
$query = $this->product->newQuery()
->where('is_archive', '=', 0)
->whereHas('categoryProducts', function ($query) use ($categoryId) {
$query->where('categories_id', $categoryId);
})
->with(['dealerProduct' => function ($query) {
$query->where('dealers_id', DealerInterface::HOTLINE);
}])
->with('primaryImage', 'vendorProducts');
if (request()->has('sortBy')) {
$query = $this->addSortByConstraint($query);
}
$products = $query->paginate(config('admin.show_items_per_page'))->appends(request()->query());
$this->setProductParameters($products);
return view('content.admin.export.hotline.products.list.index')->with(compact('category', 'products'));
}
/**
* @param int $categoryId
* @return View
*/
public function search(int $categoryId)
{
if (Gate::denies('vendor-catalog', auth('web')->user())) {
abort(401);
}
$searchText = request()->get('search_for');
$category = $this->category->newQuery()->findOrFail($categoryId);
$products = $this->product->newQuery()
->where('is_archive', '=', 0)
->whereHas('categoryProducts', function ($query) use ($categoryId) {
$query->where('categories_id', $categoryId);
})
->where('name_ru', 'LIKE', '%' . $searchText . '%')
->with(['dealerProduct' => function ($query) {
$query->where('dealers_id', DealerInterface::HOTLINE);
}])
->with('primaryImage', 'vendorProducts')
->get();
$this->setProductParameters($products);
return view('content.admin.export.hotline.products.search.index')->with(compact('category', 'products', 'searchText'));
}
/**
* Set product published.
*
* @return bool|RedirectResponse
*/
public function publish()
{
if (Gate::denies('vendor-catalog', auth('web')->user())) {
abort(401);
}
$productId = (int)request()->get('product_id');
$product = $this->product->newQuery()->findOrFail($productId);
$product->dealers()->syncWithoutDetaching([
DealerInterface::HOTLINE => [
'published' => 1,
]
]);
if (request()->ajax()) {
return 'true';
} else {
return back();
}
}
/**
* Set product un published.
*
* @return bool|RedirectResponse
*/
public function unPublish()
{
if (Gate::denies('vendor-catalog', auth('web')->user())) {
abort(401);
}
$productId = (int)request()->get('product_id');
$product = $this->product->newQuery()->findOrFail($productId);
$product->dealers()->syncWithoutDetaching([
DealerInterface::HOTLINE => [
'published' => 0,
]
]);
if (request()->ajax()) {
return 'true';
} else {
return back();
}
}
/**
* Add sort by condition.
*
* @param Request $request
* @param Builder $query
* @return Builder
*/
private function addSortByConstraint(Builder $query): Builder
{
switch (request()->get('sortBy')) {
case 'createdAt' :
if (request()->get('sortMethod') === 'asc') {
$query->orderBy('created_at');
} else if (request()->get('sortMethod') === 'desc') {
$query->orderByDesc('created_at');
}
break;
case 'published' :
if (request()->get('sortMethod') === 'asc') {
$query->orderByDesc('published');
} else if (request()->get('sortMethod') === 'desc') {
$query->orderBy('published');
}
break;
case 'name':
$locale = app()->getLocale();
if (request()->get('sortMethod') === 'asc') {
$query->orderBy('name_' . $locale);
} else if (request()->get('sortMethod') === 'desc') {
$query->orderByDesc('name_' . $locale);
}
break;
}
return $query;
}
/**
* @param $products
*/
private function setProductParameters($products)
{
foreach ($products as $product) {
$profitSum = $this->productProfit->getProfit($product);
if ($profitSum) {
$profitPercents = $profitSum / $product->price1 * 100;
} else {
$profitPercents = null;
}
$product->profitSum = number_format($profitSum, 2);
$product->profitPercents = number_format($profitPercents, 2);
}
}
}
|
php
| 21 | 0.517373 | 127 | 27.391892 | 222 |
starcoderdata
|
const socketio = require("socket.io-client");
/**Singleton representing the socket object connected to the socket web server.
*/
class Socket {
constructor(endpoint) {
this.socket = socketio(endpoint, { transports: ["websocket", "polling", "flashsocket"] });
}
get socketInstance() {
return this.socket;
}
}
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = new Socket(process.env.TRACKING_SOCKET_SERVER_ENDPOINT);
}
}
getInstance() {
if (Singleton.instance) {
return Singleton.instance.socketInstance;
}
return Singleton.instance;
}
}
module.exports = Singleton;
|
javascript
| 13 | 0.712 | 92 | 23.038462 | 26 |
starcoderdata
|
#include "DrawHooks.h"
#include "Renderer.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_win32.h"
#include "imgui/imgui_impl_opengl3.h"
#include "imgui/imgui_impl_dx9.h"
#include "imgui/imgui_impl_dx11.h"
#include "InputHandler.h"
#include "MidfunctionHook.h"
#include
namespace imogui
{
std::function DrawHooks::renderCallback = nullptr;
Direct3DDevice9_Present DrawHooks::originalDirect3DDevice9Present = nullptr;
DirectX11_IDXGISwapChain_Present DrawHooks::oDirectX11SwapchainPresent = nullptr;
namespace
{
ID3D11Device* pDevice = nullptr;
ID3D11RenderTargetView* RenderTargetView = NULL;
ID3D11DeviceContext* pContext = nullptr;
//viewport
UINT vps = 1;
D3D11_VIEWPORT viewport;
HRESULT hr;
}
int64_t __stdcall hkD3D9Present(IDirect3DDevice9* device, const RECT* src, const RECT* dest, HWND wnd_override, const RGNDATA* dirty_region)
{
static bool firstTime = true;
if (firstTime)
{
firstTime = false;
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags = ImGuiConfigFlags_NoMouseCursorChange;
D3DDEVICE_CREATION_PARAMETERS creationParameters;
device->GetCreationParameters(&creationParameters);
RECT rect;
GetWindowRect(creationParameters.hFocusWindow, &rect);
Renderer::Get().SetWidth(rect.right);
Renderer::Get().SetHeight(rect.bottom);
InputHandler::HookWndProc(creationParameters.hFocusWindow);
ImGui_ImplWin32_Init(creationParameters.hFocusWindow);
ImGui_ImplDX9_Init(device);
}
ImGui_ImplDX9_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
Renderer::Get().BeginScene();
DrawHooks::renderCallback(Renderer::Get());
Renderer::Get().EndScene();
ImGui::EndFrame();
ImGui::Render();
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
return DrawHooks::originalDirect3DDevice9Present(device, src, dest, wnd_override, dirty_region);
}
HRESULT __stdcall hookD3D11Present(IDXGISwapChain* pSwapChain, UINT SyncInterval, UINT Flags)
{
static bool firstTime = true;
if (firstTime)
{
firstTime = false;
if (SUCCEEDED(pSwapChain->GetDevice(__uuidof(ID3D11Device), (void**)&pDevice)))
{
pSwapChain->GetDevice(__uuidof(pDevice), (void**)&pDevice);
pDevice->GetImmediateContext(&pContext);
}
//imgui
DXGI_SWAP_CHAIN_DESC sd;
pSwapChain->GetDesc(&sd);
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::GetIO().WantCaptureMouse || ImGui::GetIO().WantTextInput || ImGui::GetIO().WantCaptureKeyboard; //control menu with mouse
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
RECT rect;
GetWindowRect(sd.OutputWindow, &rect);
Renderer::Get().SetWidth(rect.right);
Renderer::Get().SetHeight(rect.bottom);
InputHandler::HookWndProc(sd.OutputWindow);
ImGui_ImplWin32_Init(sd.OutputWindow);
ImGui_ImplDX11_Init(pDevice, pContext);
ImGui::GetIO().ImeWindowHandle = sd.OutputWindow;
}
if (RenderTargetView == nullptr)
{
pContext->RSGetViewports(&vps, &viewport);
ID3D11Texture2D* backbuffer = nullptr;
hr = pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backbuffer);
if (FAILED(hr))
{
return hr;
}
hr = pDevice->CreateRenderTargetView(backbuffer, nullptr, &RenderTargetView);
backbuffer->Release();
if (FAILED(hr))
{
return hr;
}
}
else
{
pContext->OMSetRenderTargets(1, &RenderTargetView, nullptr);
}
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
Renderer::Get().BeginScene();
DrawHooks::renderCallback(Renderer::Get());
Renderer::Get().EndScene();
ImGui::EndFrame();
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
return DrawHooks::oDirectX11SwapchainPresent(pSwapChain, SyncInterval, Flags);
}
void DrawHooks::OpenGLSwapbuffersMidfunction(HDC hDc)
{
static bool firstTime = true;
if (firstTime)
{
firstTime = false;
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags = ImGuiConfigFlags_NoMouseCursorChange;
HWND hWnd = WindowFromDC(hDc);
RECT rect;
GetClientRect(hWnd, &rect);
Renderer::Get().SetWidth(rect.right);
Renderer::Get().SetHeight(rect.bottom);
InputHandler::HookWndProc(hWnd);
ImGui_ImplWin32_Init(hWnd);
ImGui_ImplOpenGL3_Init();
}
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
Renderer::Get().BeginScene();
DrawHooks::renderCallback(Renderer::Get());
Renderer::Get().EndScene();
ImGui::EndFrame();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
int8_t* DrawHooks::GetPointerToHookedDirect3DDevice9Present()
{
return (int8_t*)hkD3D9Present;
}
int8_t* DrawHooks::GetPointerToHookedDirectX11SwapchainPresent()
{
return (int8_t*)hookD3D11Present;
}
}
|
c++
| 17 | 0.714081 | 141 | 22.921569 | 204 |
starcoderdata
|
/*
* Copyright 2014-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package org.springframework.restdocs.snippet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.springframework.restdocs.RestDocumentationContext;
import org.springframework.restdocs.templates.TemplateFormat;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
/**
* Standard implementation of {@link WriterResolver}.
*
* @author
*/
public final class StandardWriterResolver implements WriterResolver {
private final PlaceholderResolverFactory placeholderResolverFactory;
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(
"{", "}");
private String encoding = "UTF-8";
private TemplateFormat templateFormat;
/**
* Creates a new {@code StandardWriterResolver} that will use a
* {@link PlaceholderResolver} created from the given
* {@code placeholderResolverFactory} to resolve any placeholders in the
* {@code operationName}. Writers will use the given {@code encoding} and, when
* writing to a file, will use a filename appropriate for content generated from
* templates in the given {@code templateFormat}.
* @param placeholderResolverFactory the placeholder resolver factory
* @param encoding the encoding
* @param templateFormat the snippet format
*/
public StandardWriterResolver(PlaceholderResolverFactory placeholderResolverFactory,
String encoding, TemplateFormat templateFormat) {
this.placeholderResolverFactory = placeholderResolverFactory;
this.encoding = encoding;
this.templateFormat = templateFormat;
}
@Override
public Writer resolve(String operationName, String snippetName,
RestDocumentationContext context) throws IOException {
PlaceholderResolver placeholderResolver = this.placeholderResolverFactory
.create(context);
String outputDirectory = replacePlaceholders(placeholderResolver, operationName);
String fileName = replacePlaceholders(placeholderResolver, snippetName) + "."
+ this.templateFormat.getFileExtension();
File outputFile = resolveFile(outputDirectory, fileName, context);
if (outputFile != null) {
createDirectoriesIfNecessary(outputFile);
return new OutputStreamWriter(new FileOutputStream(outputFile),
this.encoding);
}
else {
return new OutputStreamWriter(System.out, this.encoding);
}
}
private String replacePlaceholders(PlaceholderResolver resolver, String input) {
return this.propertyPlaceholderHelper.replacePlaceholders(input, resolver);
}
File resolveFile(String outputDirectory, String fileName,
RestDocumentationContext context) {
File outputFile = new File(outputDirectory, fileName);
if (!outputFile.isAbsolute()) {
outputFile = makeRelativeToConfiguredOutputDir(outputFile, context);
}
return outputFile;
}
private File makeRelativeToConfiguredOutputDir(File outputFile,
RestDocumentationContext context) {
File configuredOutputDir = context.getOutputDirectory();
if (configuredOutputDir != null) {
return new File(configuredOutputDir, outputFile.getPath());
}
return null;
}
private void createDirectoriesIfNecessary(File outputFile) {
File parent = outputFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IllegalStateException(
"Failed to create directory '" + parent + "'");
}
}
}
|
java
| 13 | 0.779383 | 99 | 35.141593 | 113 |
starcoderdata
|
TEST_F(StunPortTest, TestStunPortGetStunKeepaliveLifetime) {
// Lifetime for the default (unknown) network type is |kInfiniteLifetime|.
CreateStunPort(kStunAddr1);
EXPECT_EQ(kInfiniteLifetime, port()->stun_keepalive_lifetime());
// Lifetime for the cellular network is |kHighCostPortKeepaliveLifetimeMs|
SetNetworkType(rtc::ADAPTER_TYPE_CELLULAR);
EXPECT_EQ(kHighCostPortKeepaliveLifetimeMs,
port()->stun_keepalive_lifetime());
// Lifetime for the wifi network is |kInfiniteLifetime|.
SetNetworkType(rtc::ADAPTER_TYPE_WIFI);
CreateStunPort(kStunAddr2);
EXPECT_EQ(kInfiniteLifetime, port()->stun_keepalive_lifetime());
}
|
c++
| 10 | 0.765337 | 76 | 45.642857 | 14 |
inline
|
import React, { useState, useEffect } from "react"
import TextCenter from "../TextCenter/TextCenter"
import {
FaMobileAlt,
FaLaptop,
FaGamepad
} from "react-icons/fa"
import Home1stCard from "./Home1stCard"
const Home1st = ({ data, language }) => {
const dataUse = data.frontmatter[`home_1st_${language}`] || {}
const dataArr = Object.values(dataUse).map(item => item) || []
const dataBox = dataArr.filter((item, index) => index > 1)
const [scrollY, setScrollY] = useState(0)
const icon = [FaLaptop, FaMobileAlt, FaGamepad]
const logit = () => {
if (window) setScrollY(window.pageYOffset)
}
useEffect(() => {
function watchScroll() {
window.addEventListener("scroll", logit)
}
watchScroll()
return () => {
window.removeEventListener("scroll", logit)
}
}, [])
return (
<section
className="main-container "
style={{ marginTop: 0, backgroundColor: "#f1f1f1" }}
>
<div className="main">
<div className="container">
<div className="row">
<div className="col-md-12">
<TextCenter head={dataArr[1]} description={dataArr[0]} />
<div className="row list-card">
{dataBox.map((item, index) => (
<Home1stCard
scrollY={scrollY}
key={index}
id={index+1}
icon={icon[index]}
language={language}
title={item[`home_box_title_${language}_${index + 1}`]}
lead={item[`home_box_desc_${language}_${index + 1}`]}
/>
))}
)
}
export default Home1st
|
javascript
| 25 | 0.527528 | 75 | 29.169492 | 59 |
starcoderdata
|
void ResizeBR_MouseMove(object sender, MouseEventArgs e) {
if (this.drag && e.Location != this.lastPoint) {
this.lastPoint = e.Location;
Point p1 = new Point(e.X, e.Y);
Point p2 = this.PointToScreen(p1);
this.Size = new Size(this.startSize.Width + (p2.X - this.startScreenPoint.X),
this.startSize.Height + (p2.Y - this.startScreenPoint.Y));
ResetTitle();
//ResetResizers(newSize); this causes bad oscillations, so instead we make the resizers invisible during dragging
KGui.gui.GuiChartUpdate(); // prevent flicker on dragging by forcing redraw
KGui.gui.GuiScoreUpdate(); // prevent flicker by forcing redraw
KGui.gui.GuiDeviceUpdate(); // prevent flicker by forcing redraw
}
}
|
c#
| 17 | 0.575281 | 129 | 62.642857 | 14 |
inline
|
from collections import defaultdict
batches = open("input").read().strip().split("\n\n")
print("--- Day06 ---")
def p1():
ans = 0
for b in batches:
bb = set(b.replace('\n', ''))
ans += len(bb)
print(ans)
def p2():
ans = 0
for b in batches:
counter = defaultdict(int)
lines = b.splitlines()
for line in lines:
for c in line:
counter[c] += 1
for k, v in counter.items():
if v == len(lines):
ans += 1
print(ans)
print("Part1", end="=> ")
p1()
print("Part2", end="=> ")
p2()
print("---- EOD ----")
|
python
| 13 | 0.470032 | 52 | 15.684211 | 38 |
starcoderdata
|
@Override
public void encode(XMLEncoder encoder) throws ContentEncodingException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write((byte)_lgBits);
baos.write((byte)_nHash);
baos.write('A'); // "method" - must be 'A' for now
baos.write(0); // "reserved" - must be 0 for now
for (int i = 0; i < _seed.length; i++)
baos.write((byte)_seed[i]);
int size = usedBits();
for (int i = 0; i < size; i++)
baos.write(_bloom[i]);
encoder.writeElement(getElementLabel(), baos.toByteArray());
}
|
java
| 9 | 0.660342 | 73 | 36.714286 | 14 |
inline
|
#include
using namespace std;
const int MAX = 5000;
int main() {
int T;
cin >> T;
while (T--) {
char a[MAX + 1], b[MAX + 1];
int n, m;
cin >> n >> m >> a >> b;
int TA[MAX + 1][MAX + 1], TB[MAX + 1][MAX + 1];
// TA[i][j] : answer for merging the i-length prefix of A and j-length prefix of B with the last character coming from A
// TB[i][j] : answer for merging the i-length prefix of A and j-length prefix of B with the last character coming from B
// Initialize:
for (int i = 0; i <= n; i++) {
fill(TA[i], TA[i] + m + 1, 3 * MAX);
fill(TB[i], TB[i] + m + 1, 3 * MAX);
}
TB[0][1] = TA[1][0] = 1;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++) {
if (i < n) {
if (i > 0) // did the second-last character come from A?
TA[i + 1][j] = min(TA[i + 1][j], ***);
if (j > 0) // did the second-last character come from B?
TA[i + 1][j] = min(TA[i + 1][j], ***);
}
if (j < m) {
if (i > 0) // did the second-last character come from A?
TB[i][j + 1] = min(TB[i][j + 1], ***);
if (j > 0) // did the second-last character come from B?
TB[i][j + 1] = min(TB[i][j + 1], ***);
}
}
// watch out for indices while filling out the above.
// a[i] is the last character of the i+1 length-prefix of a
// b[i] is the last character of the i+1 length-prefix of b
printf("%d\n", min(TA[n][m], TB[n][m]));
}
return 0;
}
|
c++
| 19 | 0.464396 | 128 | 26.844828 | 58 |
starcoderdata
|
bool mcan_send_message(uint32_t id_value, uint8_t *data, uint32_t data_length)
{
uint32_t status = mcan_tx_get_fifo_queue_status(&mcan_instance);
//check if fifo is full
if(status & MCAN_TXFQS_TFQF) {
return false;
}
//Prevent sending more data than buffer size
if(data_length > CONF_MCAN_ELEMENT_DATA_SIZE)
data_length = CONF_MCAN_ELEMENT_DATA_SIZE;
//get the put index where we put the next packet
uint32_t put_index = (status & MCAN_TXFQS_TFQPI_Msk) >> MCAN_TXFQS_TFQPI_Pos;
struct mcan_tx_element tx_element;
mcan_get_tx_buffer_element_defaults(&tx_element);
if(id_value >= 0x800)
tx_element.T0.reg |= MCAN_TX_ELEMENT_T0_EXTENDED_ID(id_value) | MCAN_TX_ELEMENT_T0_XTD;
else
tx_element.T0.reg |= MCAN_TX_ELEMENT_T0_STANDARD_ID(id_value);
tx_element.T1.bit.DLC = data_length;
for (uint32_t i = 0; i < data_length; i++) {
tx_element.data[i] = data[i];
}
mcan_set_tx_buffer_element(&mcan_instance, &tx_element, put_index);
mcan_tx_transfer_request(&mcan_instance, (1 << put_index));
return true;
}
|
c++
| 9 | 0.696239 | 89 | 28.657143 | 35 |
inline
|
package api
// ITransform represents the transform properties of an INode
type ITransform interface {
CalcFilteredTransform(
excludeTranslation bool,
excludeRotation bool,
excludeScale bool,
aft IAffineTransform)
// AffineTransform returns this node's transform
AffineTransform() IAffineTransform
InverseTransform() IAffineTransform
SetPosition(x, y float64)
Position() IPoint
SetRotation(radian float64)
Rotation() float64
SetScale(scale float64)
Scale() float64
// Not really useful in this engine.
// SetNonUniformScale(sx, sy float64)
// NonUniformScale() float64
}
|
go
| 7 | 0.778689 | 61 | 20.034483 | 29 |
starcoderdata
|
#include <bits/stdc++.h>
using namespace std;
int n,Z,W,arr[2002];
int dp[2002][2],vis[2002][2];
inline int _abs(int a) {
return a<0 ? -a : a;
}
int DP(int idx,int f) {
int &ret=dp[idx][f];
if(vis[idx][f]) return ret;
vis[idx][f]=1;
ret = _abs(arr[idx]-arr[0]);
for(int i=1;i<idx;i++) {
if(!f) ret = max(ret, DP(i,f^1));
else ret = min(ret, DP(i,f^1));
}
return ret;
}
int main() {
scanf("%d%d%d",&n,&Z,&W);
for(int i=0;i<n;i++) scanf("%d",arr+i);
reverse(arr,arr+n);
arr[n]=W;
printf("%d\n",DP(n,0));
return 0;
}
|
c++
| 14 | 0.492437 | 43 | 18.193548 | 31 |
codenet
|
package burlap.behavior.stochasticgames.madynamicprogramming;
import burlap.oomdp.core.states.State;
import burlap.oomdp.stochasticgames.JointAction;
/**
* Class for storing Q-value informartion for a joint action. It is effectively a triple consisting of a state, joint action, and a double for the corresponding q-value.
* @author
*
*/
public class JAQValue {
public State s;
public JointAction ja;
public double q;
public JAQValue(State s, JointAction ja, double q){
this.s = s;
this.ja = ja;
this.q = q;
}
}
|
java
| 8 | 0.728938 | 169 | 22.73913 | 23 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.