code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
<?php
include_once 'funciones/funciones.php';
include_once 'funciones/sesion.php';
include_once 'templates/header.php'; ?>
<body class="hold-transition skin-blue fixed sidebar-mini">
<!-- Site wrapper -->
<div class="wrapper">
<?php include_once 'templates/barra.php'; ?>
<?php include_once 'templates/navegacion.php'; ?>
<!-- =============================================== -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
Panel de Administración
tu sitio desde este panel o en el menú de la izquierda
<!-- /.content-wrapper -->
<?php
include_once 'templates/footer.php';
include_once 'templates/footer-scripts.php';
?> | php | 4 | 0.605634 | 88 | 23.342857 | 35 | starcoderdata |
import hashlib
from luigi import Task, ListParameter, Parameter
from luigi.util import inherits
class Dctool2TaskBase(Task):
output_folder = Parameter()
@inherits(Dctool2TaskBase)
class Dctool2Task(Task):
categories = ListParameter()
documents_file = Parameter()
def create_classifier_id(max_df, min_df, percentile):
parameter_string = "{max_df}-{min_df}-{percentile}".format(
max_df=max_df,
min_df=min_df,
percentile=percentile
)
return hashlib.md5(parameter_string.encode()).hexdigest() | python | 10 | 0.7 | 63 | 21.4 | 25 | starcoderdata |
namespace TryAtSoftware.Randomizer.Core.Interfaces
{
public interface IInstanceBuilder<out TEntity>
{
TEntity PrepareNewInstance();
}
} | c# | 7 | 0.717949 | 51 | 21.428571 | 7 | starcoderdata |
/////////////////////////////////////////////////////////////
// //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing //
// http://earth.uq.edu.au/centre-geoscience-computing //
// //
// Primary Business: Brisbane, Queensland, Australia //
// Licensed under the Open Software License version 3.0 //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
/////////////////////////////////////////////////////////////
#ifndef __PARTICLE_H
#define __PARTICLE_H
// -- project includes --
#include "Foundation/Quaternion.h"
#include "Foundation/vec3.h"
#include "Foundation/Matrix3.h"
#include "Model/BasicParticle.h"
#include "Parallel/CheckPointable.h"
//--- STL includes ---
#include
#include
#include
#include
#include
using std::map;
using std::vector;
using std::pair;
using std::string;
template <class T> class ParallelParticleArray;
class AMPISGBufferRoot;
class AMPIBuffer;
namespace esys
{
namespace lsm
{
class SimpleParticleData;
}
}
/*!
\brief Class for a basic particle
*/
class CParticle : public CBasicParticle, public esys::lsm::CheckPointable
{
public: // types
class exchangeType
{
public:
exchangeType()
: m_pos(),
m_initPos(),
m_oldPos(),
m_vel()
{
m_is_dynamic=true;
}
exchangeType(const Vec3 &pos, const Vec3 &initPos, const Vec3 &oldPos, const Vec3 &vel,bool is_dyn)
: m_pos(pos),
m_initPos(initPos),
m_oldPos(oldPos),
m_vel(vel)
{
m_is_dynamic=is_dyn;
}
Vec3 m_pos;
Vec3 m_initPos;
Vec3 m_oldPos;
Vec3 m_vel;
bool m_is_dynamic;
};
typedef double (CParticle::* ScalarFieldFunction)() const;
typedef Vec3 (CParticle::* VectorFieldFunction)() const;
protected:
//! stress tensor. \warning Warning: this is unscaled, i.e. without the 1/V term
Matrix3 m_sigma;
Vec3 m_vel,m_force;
Vec3 m_oldpos; //!< position at the time of last neighbor search
Vec3 m_initpos; //!< position at time of construction
Vec3 m_circular_shift; //!< shift vector if particle is circular image
double m_mass,m_div_mass;
double m_div_vol; //!< inverse of the particle volume, used in stress calculations
bool flag;
bool m_is_dynamic;
void setForce(const Vec3 &force) {m_force = force;}
public:
CParticle();
CParticle(double,double,const Vec3&,const Vec3&,const Vec3&,int,bool);
CParticle(double,double,const Vec3&,const Vec3&,const Vec3&,const Vec3&,const Vec3&,int,bool); // including oldpos
CParticle(const esys::lsm::SimpleParticleData &particleData);
virtual ~CParticle(){};
static ScalarFieldFunction getScalarFieldFunction(const string&);
static VectorFieldFunction getVectorFieldFunction(const string&);
inline const Vec3 &getInitPos() const {return m_initpos;}
inline void setInitPos(const Vec3 &initPos) {m_initpos = initPos;}
inline Vec3 getDisplacement() const {return (m_pos-m_oldpos);} ;
inline Vec3 getTotalDisplacement() const {return (m_pos-m_initpos);} ;
inline const Vec3 &getOldPos() const {return m_oldpos;};
inline Vec3 getVel() const {return m_vel;};
inline double getAbsVel() const {return m_vel.norm();};
inline void setVel(const Vec3 &V){m_vel=V;};
inline void setMass(double mass) {m_mass = mass; m_div_mass = 1.0/m_mass;}
inline double getMass() const {return m_mass;};
inline double getInvMass() const {return m_div_mass;};
inline Vec3 getForce() const {return m_force;};
virtual void setDensity(double); // needs to be virtual , different for rot. particle (mom. inert)
void resetDisplacement(){m_oldpos=m_pos;};
double getIDField() const {return double(m_global_id);};
double getTagField() const {return double(getTag());};
void applyForce(const Vec3&,const Vec3&);
virtual void integrate(double);
virtual void integrateTherm(double){}
virtual void zeroForce();
virtual void zeroHeat() {}
virtual void thermExpansion() {}
inline void moveToRel(const Vec3 &v){m_pos=m_initpos+v;}; //!< move relative to initial position
inline double getKineticEnergy() const {return 0.5*m_mass*m_vel*m_vel;};
// switching on/off dynamic behaviour
virtual void setNonDynamic() {m_is_dynamic=false;};
virtual void setNonDynamicLinear() {m_is_dynamic=false;};
virtual void setNonDynamicRot(){}; // do nothing
virtual void resetRotation(){}; // do nothing
inline void changeRadiusBy(double deltaR){m_rad += deltaR;}
void setFlag(bool b=true){flag=b;};
bool isFlagged() const {return flag;};
void writeAsDXLine(ostream&,int slid=0);
friend ostream& operator<<(ostream&, const CParticle&);
void print(){cout << *this << endl << flush;};
void rescale() {};
exchangeType getExchangeValues();
void setExchangeValues(const exchangeType&);
// circular
void setCircular(const Vec3&);
// stress
double sigma_xx_2D() const {return m_sigma(0,0)/(M_PI*m_rad*m_rad);};
double sigma_xy_2D() const {return m_sigma(0,1)/(M_PI*m_rad*m_rad);};
double sigma_yy_2D() const {return m_sigma(1,1)/(M_PI*m_rad*m_rad);};
double sigma_d() const;
double sigma_vonMises() const;
Matrix3 sigma() const;
friend class TML_PackedMessageInterface;
virtual void saveCheckPointData(std::ostream& oStream);
virtual void saveSnapShotData(std::ostream& oStream);
//virtual Quaternion getQuat(){return Quaternion(1.0,Vec3(0.0,0.0,0.0));};
virtual void applyMoment(const Vec3&){};
static void get_type() {cout <<" CParticle" ;};
virtual void loadCheckPointData(std::istream &iStream);
template <typename TmplVisitor>
void visit(TmplVisitor &visitor)
{
visitor.visitParticle(*this);
}
public:
// Ensure that particles only move in the x-y plane 2D computations
inline static void setDo2dCalculations(bool do2dCalculations) {s_do2Calculations = do2dCalculations;}
inline static bool getDo2dCalculations() {return s_do2Calculations;}
private:
static bool s_do2Calculations;
};
/* CParticle extractCParticleFrom(AMPIBuffer*); */
/* CParticle extractCParticleFrom(AMPISGBufferRoot*,int); */
#endif //__PARTICLE_H | c | 18 | 0.658948 | 116 | 31.060606 | 198 | starcoderdata |
#include
using namespace std;
struct Money {
int g, s, k;
inline int safe_mod(int x, int y) {
int t = x % y;
if (t < 0)return t + y;
else return t;
}
inline int hash() {
return g * 17 * 29 + s * 29 + k;
}
void rationalize() {
int sc = hash();
k = sc;
sc = k / 29;
k %= 29;
s = sc;
sc = s / 17;
s %= 17;
g = sc;
}
Money(int g = 0, int s = 0, int k = 0) : g(g), s(s), k(k) { rationalize(); }
Money operator-(const Money &that) {
return Money(g - that.g, s - that.s, k - that.k);
}
friend ostream &operator<<(ostream &os, const Money &m) {
os << m.g << "." << m.s << "." << m.k;
return os;
}
friend istream &operator>>(istream &is, Money &m) {
string str;
is >> str;
transform(str.begin(), str.end(), str.begin(), [](char c) -> char { return c == '.' ? ' ' : c; });
istringstream iss(str);
iss >> m.g >> m.s >> m.k;
return is;
}
};
int main() {
Money p, a;
cin >> p >> a;
if (p.hash() <= a.hash())
cout << Money(0, 0, a.hash() - p.hash()) << endl;
else cout << "-" << Money(0, 0, p.hash() - a.hash()) << endl;
return 0;
} | c++ | 15 | 0.428351 | 106 | 20.65 | 60 | starcoderdata |
package com.github.phantauth.resource.producer;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
public class ExternalCache {
private final LoadingCache cache;
private final Function<InputStream, T> reader;
public ExternalCache(final int size, final long ttl, final Function<InputStream, T> reader) {
this.reader = reader;
cache = CacheBuilder.newBuilder()
.maximumSize(size)
.expireAfterWrite(ttl, TimeUnit.MILLISECONDS)
.build(new Loader());
}
public T get(final String key) throws ExecutionException {
return cache.get(key);
}
private class Loader extends CacheLoader<String, T> {
final CloseableHttpClient client;
private Loader() {
this.client = newClient();
}
private CloseableHttpClient newClient() {
if ( client != null ) {
return client;
}
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(3000)
.setSocketTimeout(2000)
.build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setRedirectStrategy(new LaxRedirectStrategy())
.setUserAgent("PhantAuth")
.build();
}
@Override
public T load(final String uri) throws Exception {
try (CloseableHttpResponse response = client.execute(new HttpGet(uri))) {
// on not supported entity type (ie: fleet, or team), in this case next generator will get chance ????
if ( response.getStatusLine().getStatusCode() == 404 ) {
return null;
}
return reader.apply(response.getEntity().getContent());
}
}
}
} | java | 13 | 0.634946 | 118 | 33.736111 | 72 | starcoderdata |
import logging
from ctypes import byref, c_char_p, c_uint8, CFUNCTYPE
from .lmbinc import LCMInfo, LCMKeyMsg, PSP
logger = logging.getLogger(__name__)
class LCM:
"""
Liquid Crystal Display Module.
sdk/src_utils/sdk_lcm/sdk_lcm.c
:param lmb_io_path: path of liblmbio.so
:param lmb_api_path: path of liblmbapi.so
"""
DEFAULT_LCM_PORT = "/dev/ttyS1"
DEFAULT_BAUD_RATE = 19200
def __init__(self,
lmb_io_path: str = "/opt/lanner/psp/bin/amd64/lib/liblmbio.so",
lmb_api_path: str = "/opt/lanner/psp/bin/amd64/lib/liblmbapi.so") -> None:
self._lmb_io_path = lmb_io_path
self._lmb_api_path = lmb_api_path
self._ub_keys = c_uint8(0)
self._lcm_info = LCMInfo()
self._str_lcm_port = c_char_p(self.DEFAULT_LCM_PORT.encode())
self._dw_speed = self.DEFAULT_BAUD_RATE
def get_module_type(self) -> str:
"""Get LCM module type."""
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_DeviceInfo(byref(self._lcm_info))
if i_ret == PSP.ERR_Success:
module_type = "UART"
else:
module_type = "LPT"
logger.debug(f"LCM module type is {module_type}")
psp.lib.LMB_LCM_DeviceClose()
return module_type
def get_keys_status(self) -> int:
"""Get LCM keys status.
bit 0 means Key 1, bit 1 means Key2, bit 2 means Key 3, bit 3 means Key4
1: pressed , 0: released
0 (0000): key1 -> off, key2 -> off, key3 -> off, key4 -> off
1 (0001): key1 -> on, key2 -> off, key3 -> off, key4 -> off
2 (0010): key1 -> off, key2 -> on, key3 -> off, key4 -> off
4 (0100): key1 -> off, key2 -> off, key3 -> on, key4 -> off
8 (1000): key1 -> off, key2 -> off, key3 -> off, key4 -> on
"""
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_KeysStatus(byref(self._ub_keys))
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_KeysStatus", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
logger.debug(f"LCM keys status is {self._ub_keys.value:02x}")
psp.lib.LMB_LCM_DeviceClose()
return self._ub_keys.value
def set_backlight(self, enable: bool) -> None:
"""Set LCM backlight."""
# Check type.
if not isinstance(enable, bool):
raise TypeError("'enable' type must be bool")
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_LightCtrl(c_uint8(enable & 0xFF).value)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_LightCtrl", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
logger.debug(f"set LCM backlight to {enable}")
psp.lib.LMB_LCM_DeviceClose()
def set_cursor(self, row: int, column: int = 1) -> None:
"""Set LCM cursor."""
# Check type.
if not isinstance(row, int):
raise TypeError("'row' type must be int")
if not isinstance(column, int):
raise TypeError("'column' type must be int")
# Check value has been done by the PSP.
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_SetCursor(column, row)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_SetCursor", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
logger.debug(f"set LCM cursor to row {row} column {column}")
psp.lib.LMB_LCM_DeviceClose()
def write(self, msg: str) -> None:
"""Write string on LCM."""
# Check type.
if not isinstance(msg, str):
raise TypeError("'msg' type must be str")
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_WriteString(c_char_p(msg.encode()))
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_WriteString", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
logger.debug(f"write '{msg}' on LCM")
psp.lib.LMB_LCM_DeviceClose()
def clear(self) -> None:
"""Clear string on LCM."""
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_DisplayClear()
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_DisplayClear", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
logger.debug(f"clear string on LCM")
psp.lib.LMB_LCM_DeviceClose()
@classmethod
def _callback(cls, stu_lcm_msg: LCMKeyMsg) -> None:
"""Callback function for exec_callback()."""
print(f" LCM Item = 0x{stu_lcm_msg.ub_keys:02X}, "
f"Status = 0x{stu_lcm_msg.ub_status:02X}, "
f"time is {stu_lcm_msg.stu_time.uw_year:04d}/"
f"{stu_lcm_msg.stu_time.ub_month:02d}/"
f"{stu_lcm_msg.stu_time.ub_day:02d} "
f"{stu_lcm_msg.stu_time.ub_hour:02d}:"
f"{stu_lcm_msg.stu_time.ub_minute:02d}:"
f"{stu_lcm_msg.stu_time.ub_second:02d}")
def exec_callback(self) -> None:
"""Use callback function to detect LCM Keys status."""
c_callback = CFUNCTYPE(None, LCMKeyMsg)
p_callback = c_callback(self._callback)
with PSP(self._lmb_io_path, self._lmb_api_path) as psp:
i_ret = psp.lib.LMB_LCM_OpenPort(self._str_lcm_port, self._dw_speed)
if i_ret != PSP.ERR_Success:
error_message = PSP.get_error_message("LMB_LCM_OpenPort", i_ret)
logger.error(error_message)
raise PSP.PSPError(error_message)
i_ret = psp.lib.LMB_LCM_KeysCallback(p_callback, 150)
if i_ret != PSP.ERR_Success:
print("-----> hook LCM Keys callback failure <-------")
return
print("----> hook LCM Keys Callback OK <----")
print("===> pause !!! hit to end <===")
input()
i_ret = psp.lib.LMB_LCM_KeysCallback(None, 150)
if i_ret == PSP.ERR_Success:
print("----> hook LCM Keys Callback Disable OK <----")
psp.lib.LMB_LCM_DeviceClose() | python | 15 | 0.554756 | 91 | 45.054348 | 184 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace nsExceptions
{
///
/// Handles exception inside tasks.
///
public static class TaskExceptionHandler
{
public static void Handle(Task task)
{
AggregateException exception = task.Exception;
if (exception != null)
Console.WriteLine(exception);
MessageBox.Show(
String.Format("Unexpected error has occured.{0}{0}{1}", Environment.NewLine, exception.Message),
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
} | c# | 15 | 0.605195 | 112 | 24.666667 | 30 | starcoderdata |
void plo_init(void)
{
u16 t;
int i, act;
const char digits[] = "0123456789abcdef";
low_init();
timer_init();
serial_init(BPS_115200);
phfs_init();
//plostd_printf(ATTR_LOADER, "\n");
plostd_printf(ATTR_LOADER, "%s\n", WELCOME);
/* Execute loader command */
for (t = _plo_timeout; t; t--) {
plostd_printf(ATTR_INIT, "\r%d seconds to automatic boot ", t);
if (timer_wait(1000, TIMER_KEYB, NULL, 0))
break;
}
if (t == 0) {
plostd_printf(ATTR_INIT, "\n%s%s", PROMPT, _plo_command);
cmd_parse(_plo_command);
}
plostd_printf(ATTR_INIT, "\n");
/* Enter to interactive mode */
plo_cmdloop();
low_done();
return;
} | c | 10 | 0.611111 | 70 | 17.542857 | 35 | inline |
void space_resize(int h, int w, int maxhw, int times, int *nh, int *nw) {
int m;
float scale;
// Make sure nh and nw <= maxhw,
m = MAX(h, w);
if (maxhw > 0 && m > maxhw) {
scale = 1.0 * maxhw / m;
h = (int)(scale * h);
w = (int)(scale * w);
}
h = (h + times - 1) / times;
w = (w + times - 1) / times;
*nh = h * times;
*nw = w * times;
} | c | 10 | 0.481081 | 73 | 20.823529 | 17 | inline |
const http = require("http")
const fs = require("fs")
const toObject = require("object-deep-from-entries")
const {parse} = require("then-busboy")
const server = () => http.createServer((req, res) => {
async function transform(body) {
const files = await Promise.all(body.files.entries().map(
([path, file]) => fs.promises.readFile(file.path).then(content => [
path, String(content)
])
))
return toObject([
...body.fields.entries().map(([path, {value}]) => [path, value]),
...files
])
}
function onFulfilled(data) {
res.statusCode = 200
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify(data))
}
function onRejected(err) {
console.log(err)
res.statusCode = err.status || 500
res.end(String(err))
}
parse(req).then(transform).then(onFulfilled)
.catch(onRejected)
})
module.exports = server | javascript | 20 | 0.631799 | 73 | 23.512821 | 39 | starcoderdata |
package org.consumersunion.stories.common.shared.dto;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.collect.Lists;
@JsonTypeName("organization_links")
public class OrganizationResourceLinks extends ResourceLinks {
private final List profiles;
private final List questionnaires;
private final List collections;
private final List permissions;
private final List themes;
private final List notes;
private final List attachments;
@JsonProperty("default_permission")
private ResourceLink defaultPermission;
@JsonProperty("default_theme")
private ResourceLink defaultTheme;
public OrganizationResourceLinks() {
profiles = Lists.newArrayList();
questionnaires = Lists.newArrayList();
collections = Lists.newArrayList();
permissions = Lists.newArrayList();
themes = Lists.newArrayList();
notes = Lists.newArrayList();
attachments = Lists.newArrayList();
}
public List getProfiles() {
return profiles;
}
public void setProfiles(List profiles) {
this.profiles.clear();
this.profiles.addAll(profiles);
}
public List getQuestionnaires() {
return questionnaires;
}
public void setQuestionnaires(List questionnaires) {
this.questionnaires.clear();
this.questionnaires.addAll(questionnaires);
}
public List getCollections() {
return collections;
}
public void setCollections(List collections) {
this.collections.clear();
this.collections.addAll(collections);
}
public List getPermissions() {
return permissions;
}
public void setPermissions(List permissions) {
this.permissions.clear();
this.permissions.addAll(permissions);
}
public ResourceLink getDefaultPermission() {
return defaultPermission;
}
public void setDefaultPermission(ResourceLink defaultPermission) {
this.defaultPermission = defaultPermission;
}
public List getThemes() {
return themes;
}
public void setThemes(List themes) {
this.themes.clear();
this.themes.addAll(themes);
}
public ResourceLink getDefaultTheme() {
return defaultTheme;
}
public void setDefaultTheme(ResourceLink defaultTheme) {
this.defaultTheme = defaultTheme;
}
public List getNotes() {
return notes;
}
public void setNotes(List notes) {
this.notes.clear();
this.notes.addAll(notes);
}
public List getAttachments() {
return attachments;
}
public void setAttachments(List attachments) {
this.attachments.clear();
this.attachments.addAll(attachments);
}
} | java | 7 | 0.695215 | 123 | 28.035398 | 113 | starcoderdata |
#include
#include "utils.hpp"
int main(int argc, char* argv[]) {
std::string mission_type = "passthrough.yaml";
std::string mpc_main_yaml_path = MULTICOPTER_MPC_OCP_DIR "/mpc-main.yaml";
multicopter_mpc::MpcMain mpc_main(multicopter_mpc::MultiCopterTypes::Iris, mission_type, mpc_main_yaml_path);
Simulator simulator(mpc_main.getMpcController()->getTimeStep());
Eigen::VectorXd state = mpc_main.getMpcController()->getStateMultibody()->zero();
Eigen::VectorXd control = Eigen::VectorXd::Zero(mpc_main.getMpcController()->getMcParams()->n_rotors_);
for (std::size_t i = 0; i < mpc_main.getMpcController()->getTrajectoryGenerator()->getKnots(); ++i) {
// applyRandomNoise(state);
mpc_main.setCurrentState(state);
mpc_main.runMpcStep();
control = mpc_main.getMotorsThrust();
state = simulator.simulateStep(state, control);
if (i % 20 == 0) {
std::cout << "Step number: " << i << std::endl;
}
}
} | c++ | 12 | 0.680962 | 111 | 37.28 | 25 | starcoderdata |
package com.baeldung.tutorial.hexagonal.adapter;
import com.baeldung.tutorial.hexagonal.port.in.UserRegistration;
/**
* User Registration data is populated in this class from REST API
* Example, No Implementation
*/
public class RestUserRegistrationImpl implements UserRegistration {
public boolean subscriptionPaid() {
return false;
}
public String getUserName() {
return null;
}
public String getUserEmail() {
return null;
}
public String getUserAddress() {
return null;
}
} | java | 8 | 0.684397 | 67 | 18.448276 | 29 | starcoderdata |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.monitor.query.codesnippets;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.monitor.query.MetricsQueryAsyncClient;
import com.azure.monitor.query.MetricsQueryClient;
import com.azure.monitor.query.MetricsQueryClientBuilder;
import com.azure.monitor.query.models.MetricResult;
import com.azure.monitor.query.models.MetricsQueryResult;
import reactor.core.publisher.Mono;
import java.util.Arrays;
/**
* Class containing JavaDoc codesnippets for metrics query client.
*/
public class MetricsQueryClientJavaDocCodeSnippets {
/**
* Code snippet for creating a metrics query client.
*/
public void instantiation() {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
// BEGIN: com.azure.monitor.query.MetricsQueryClient.instantiation
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
.credential(tokenCredential)
.buildClient();
// END: com.azure.monitor.query.MetricsQueryClient.instantiation
// BEGIN: com.azure.monitor.query.MetricsQueryAsyncClient.instantiation
MetricsQueryAsyncClient metricsQueryAsyncClient = new MetricsQueryClientBuilder()
.credential(tokenCredential)
.buildAsyncClient();
// END: com.azure.monitor.query.MetricsQueryAsyncClient.instantiation
}
public void queryMetricsAsync() {
MetricsQueryAsyncClient metricsQueryAsyncClient = new MetricsQueryClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
// BEGIN: com.azure.monitor.query.MetricsQueryAsyncClient.query#String-List
Mono<MetricsQueryResult> response = metricsQueryAsyncClient
.queryResource("{resource-id}", Arrays.asList("{metric-1}", "{metric-2}"));
response.subscribe(result -> {
for (MetricResult metricResult : result.getMetrics()) {
System.out.println("Metric name " + metricResult.getMetricName());
metricResult.getTimeSeries().stream()
.flatMap(timeSeriesElement -> timeSeriesElement.getValues().stream())
.forEach(metricValue ->
System.out.println("Time stamp: " + metricValue.getTimeStamp() + "; Total: "
+ metricValue.getTotal()));
}
});
// END: com.azure.monitor.query.MetricsQueryAsyncClient.query#String-List
}
public void queryMetrics() {
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
// BEGIN: com.azure.monitor.query.MetricsQueryClient.query#String-List
MetricsQueryResult response = metricsQueryClient.queryResource("{resource-id}",
Arrays.asList("{metric-1}", "{metric-2}"));
for (MetricResult metricResult : response.getMetrics()) {
System.out.println("Metric name " + metricResult.getMetricName());
metricResult.getTimeSeries().stream()
.flatMap(timeSeriesElement -> timeSeriesElement.getValues().stream())
.forEach(metricValue ->
System.out.println("Time stamp: " + metricValue.getTimeStamp() + "; Total: "
+ metricValue.getTotal()));
}
// END: com.azure.monitor.query.MetricsQueryClient.query#String-List
}
}
| java | 23 | 0.660016 | 109 | 45.407407 | 81 | research_code |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include
#define ORGANIZATION_NAME "@EVGENY@"
#define ORGANIZATION_DOMAIN "localhost"
#define APPLICATION_NAME "FindOptimalK program"
#define SETTINGS_FILE_PWD "config.ini" //Full path to the ini file
//Settings group names
#define SETTINGS_MAINWINDOW "Mainwindow parametrs"
//Settings section names
#define SETTINGS_INITIAL_SECTION "Initial parametrs"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
Ui::MainWindow *ui;
QAction* m_saveSettingsAction;
QAction* m_loadSettingsAction;
QAction* m_dbConnectionAction;
QMap<QString, QVariant> rocketMapFromDB;
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void save_settings();
void load_settings();
void call_dbConnection();
void start_modeling(QMap<QString, QVariant>* parametrs);
};
#endif // MAINWINDOW_H | c | 11 | 0.739634 | 66 | 19.74 | 50 | starcoderdata |
func initClient(proxyAddr string, insecure bool, pool *x509.CertPool) (*webClient, *url.URL, error) {
var opts []roundtrip.ClientParam
u, err := url.ParseRequestURI(proxyAddr)
if err != nil {
return nil, nil, trace.Wrap(err).AddField("proxy_addr", proxyAddr)
}
if pool != nil {
// use custom set of trusted CAs
opts = append(opts, roundtrip.HTTPClient(newClientWithPool(pool)))
} else if insecure {
// skip https cert verification, oh no!
fmt.Println(color.YellowString("WARNING: You are using insecure connection to Gravity Hub %v", proxyAddr))
opts = append(opts, roundtrip.HTTPClient(newInsecureClient()))
}
clt, err := newWebClient(proxyAddr, opts...)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return clt, u, nil
} | go | 14 | 0.707285 | 108 | 31.869565 | 23 | inline |
package software.amazon.qldb.example.dagger.modules;
import com.amazonaws.services.qldb.AmazonQLDB;
import dagger.internal.Factory;
import dagger.internal.Preconditions;
import javax.annotation.Generated;
import javax.inject.Provider;
import software.amazon.qldb.example.actions.ledgermanagement.ListLedgers;
@Generated(
value = "dagger.internal.codegen.ComponentProcessor",
comments = "https://google.github.io/dagger"
)
public final class SetupModule_ProvidesListLedgersFactory implements Factory {
private final SetupModule module;
private final Provider clientProvider;
public SetupModule_ProvidesListLedgersFactory(
SetupModule module, Provider clientProvider) {
assert module != null;
this.module = module;
assert clientProvider != null;
this.clientProvider = clientProvider;
}
@Override
public ListLedgers get() {
return Preconditions.checkNotNull(
module.providesListLedgers(clientProvider.get()),
"Cannot return null from a non-@Nullable @Provides method");
}
public static Factory create(
SetupModule module, Provider clientProvider) {
return new SetupModule_ProvidesListLedgersFactory(module, clientProvider);
}
} | java | 12 | 0.775848 | 91 | 32.342105 | 38 | starcoderdata |
#ifndef _WCHAR_H
#define _WCHAR_H
// This mechanism provides __gnu_va_list which is equivalent to va_list
// We have to do this because wchar.h is not supposed to define va_list
#define __need___va_list
#include
#include
#include
#include
#include
#include
#define WEOF 0xffffffffU
// TODO: The following declaration should be independent of gcc.
#define WCHAR_MIN __WCHAR_MIN__
#define WCHAR_MAX __WCHAR_MAX__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct __mlibc_file_base FILE;
typedef struct __mlibc_mbstate mbstate_t;
// MISSING: struct tm
// [7.28.2] Wide formatted I/O functions
int fwprintf(FILE *__restrict, const wchar_t *__restrict, ...);
int fwscanf(FILE *__restrict, const wchar_t *__restrict, ...);
int vfwprintf(FILE *__restrict, const wchar_t *__restrict, __gnuc_va_list);
int vfwscanf(FILE *__restrict, const wchar_t *__restrict, __gnuc_va_list);
int swprintf(wchar_t *__restrict, size_t, const wchar_t *__restrict, ...);
int swscanf(wchar_t *__restrict, size_t, const wchar_t *__restrict, ...);
int vswprintf(wchar_t *__restrict, size_t, const wchar_t *__restrict, __gnuc_va_list);
int vswscanf(wchar_t *__restrict, size_t, const wchar_t *__restrict, __gnuc_va_list);
int wprintf(const wchar_t *__restrict, ...);
int wscanf(const wchar_t *__restrict, ...);
int vwprintf(const wchar_t *__restrict, __gnuc_va_list);
int vwscanf(const wchar_t *__restrict, __gnuc_va_list);
// [7.28.3] Wide character I/O functions
wint_t fgetwc(FILE *);
wchar_t *fgetws(wchar_t *__restrict, int, FILE *__restrict);
wint_t fputwc(wchar_t, FILE *);
int fputws(const wchar_t *__restrict, FILE *__restrict);
int fwide(FILE *, int);
wint_t getwc(FILE *);
wint_t getwchar(void);
wint_t putwc(wchar_t, FILE *);
wint_t putwchar(wchar_t);
wint_t ungetwc(wint_t, FILE *);
// [7.28.4] Wide string functions
double wcstod(const wchar_t *__restrict, wchar_t **__restrict);
float wcstof(const wchar_t *__restrict, wchar_t **__restrict);
long double wcstold(const wchar_t *__restrict, wchar_t **__restrict);
long wcstol(const wchar_t *__restrict, wchar_t **__restrict, int);
long long wcstoll(const wchar_t *__restrict, wchar_t **__restrict, int);
unsigned long wcstoul(const wchar_t *__restrict, wchar_t **__restrict, int);
unsigned long long wcstoull(const wchar_t *__restrict, wchar_t **__restrict, int);
wchar_t *wcscpy(wchar_t *__restrict, const wchar_t *__restrict);
wchar_t *wcsncpy(wchar_t *__restrict, const wchar_t *__restrict, size_t);
wchar_t *wmemcpy(wchar_t *__restrict, const wchar_t *__restrict, size_t);
wchar_t *wmemmove(wchar_t *, const wchar_t *, size_t);
wchar_t *wcscat(wchar_t *__restrict, const wchar_t *__restrict);
wchar_t *wcsncat(wchar_t *__restrict, const wchar_t *__restrict, size_t);
int wcscmp(const wchar_t *, const wchar_t *);
int wcscoll(const wchar_t *, const wchar_t *);
int wcsncmp(const wchar_t *, const wchar_t *, size_t);
int wcsxfrm(wchar_t *__restrict, const wchar_t *__restrict, size_t);
int wmemcmp(const wchar_t *, const wchar_t *, size_t);
wchar_t *wcschr(const wchar_t *, wchar_t);
size_t wcscspn(const wchar_t *, const wchar_t *);
wchar_t *wcspbrk(const wchar_t *, const wchar_t *);
wchar_t *wcsrchr(const wchar_t *, wchar_t);
size_t wcsspn(const wchar_t *, const wchar_t *);
wchar_t *wcsstr(const wchar_t *, const wchar_t *);
wchar_t *wcstok(wchar_t *__restrict, const wchar_t *__restrict, wchar_t **__restrict);
wchar_t *wmemchr(const wchar_t *, wchar_t, size_t);
size_t wcslen(const wchar_t *);
wchar_t *wmemset(wchar_t *, wchar_t, size_t);
// [7.28.5] Wide date/time functions
size_t wcsftime(wchar_t *__restrict, size_t, const wchar_t *__restrict,
const struct tm *__restrict);
// [7.28.6] Wide conversion functions
wint_t btowc(int c);
int wctob(wint_t);
int mbsinit(const mbstate_t *);
size_t mbrlen(const char *__restrict, size_t, mbstate_t *__restrict);
size_t mbrtowc(wchar_t *__restrict, const char *__restrict, size_t, mbstate_t *__restrict);
size_t wcrtomb(char *__restrict, wchar_t, mbstate_t *__restrict);
size_t mbsrtowcs(wchar_t *__restrict, const char **__restrict, size_t, mbstate_t *__restrict);
size_t mbsnrtowcs(wchar_t *__restrict, const char **__restrict, size_t, size_t, mbstate_t *__restrict);
size_t wcsrtombs(char *__restrict, const wchar_t **__restrict, size_t, mbstate_t *__restrict);
size_t wcsnrtombs(char *__restrict, const wchar_t **__restrict, size_t, size_t, mbstate_t *__restrict);
// POSIX extensions
int wcwidth(wchar_t wc);
int wcswidth(const wchar_t *, size_t);
#ifdef __cplusplus
}
#endif
#endif // _WCHAR_H | c | 12 | 0.686687 | 103 | 36.193548 | 124 | starcoderdata |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using Xenko.UI.Tests.Events;
using Xenko.UI.Tests.Layering;
namespace Xenko.UI.Tests
{
public class Program
{
public static void Main()
{
var uiElementTest = new UIElementLayeringTests();
uiElementTest.TestAll();
var panelTest = new PanelTests();
panelTest.TestAll();
var controlTest = new ControlTests();
controlTest.TestAll();
var stackPanelTest = new StackPanelTests();
stackPanelTest.TestAll();
var canvasTest = new CanvasTests();
canvasTest.TestAll();
var contentControlTest = new ContentControlTest();
contentControlTest.TestAll();
var eventManagerTest = new EventManagerTests();
eventManagerTest.TestAll();
var routedEventArgTest = new RoutedEventArgsTest();
routedEventArgTest.TestAll();
var uiElementEventTest = new UIElementEventTests();
uiElementEventTest.TestAll();
var gridTest = new GridTests();
gridTest.TestAll();
}
}
} | c# | 13 | 0.623116 | 114 | 29.955556 | 45 | starcoderdata |
package com.github.huihuangui.ovalseekbar.app;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.azoft.carousellayoutmanager.CarouselLayoutManager;
import com.azoft.carousellayoutmanager.CarouselZoomPostLayoutListener;
import com.azoft.carousellayoutmanager.CenterScrollListener;
import com.github.huihuangui.ovalseekbar.OvalSeekBar;
import com.github.huihuangui.ovalseekbar.app.widget.RecyclerViewOvalSeekBar;
/**
* @author
* @email:
*/
public class WithRecyclerViewActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private OvalSeekBar mOvalSeekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_recycler_view);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mOvalSeekBar = (RecyclerViewOvalSeekBar) findViewById(R.id.oval_seek_bar);
mRecyclerView.addOnScrollListener((
(RecyclerViewOvalSeekBar) mOvalSeekBar).getRecyclerViewListener());
CarouselLayoutManager clm = new CarouselLayoutManager(CarouselLayoutManager.HORIZONTAL, true);
clm.setPostLayoutListener(new CarouselZoomPostLayoutListener());
mRecyclerView.addOnScrollListener(new CenterScrollListener());
mRecyclerView.setLayoutManager(clm);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(new MyAdapter());
}
class MyAdapter extends RecyclerView.Adapter {
@NonNull
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
ImageView tv = new ImageView(WithRecyclerViewActivity.this);
return new MyViewHolder(tv);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {
viewHolder.tv.setImageResource(Images.DEMO_IMAGES[i]);
}
@Override
public int getItemCount() {
return Images.DEMO_IMAGES.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView tv;
public MyViewHolder(ImageView v) {
super(v);
tv = v;
}
}
}
} | java | 10 | 0.723299 | 127 | 35.541667 | 72 | starcoderdata |
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
pixelfont.h - v0.1 -
Do this:
#define PIXELFONT_IMPLEMENTATION
before you include this file in *one* C/C++ file to create the implementation.
*/
#ifndef pixelfont_h
#define pixelfont_h
#ifndef PIXELFONT_I8
#define PIXELFONT_I8 signed char
#endif
#ifndef PIXELFONT_U8
#define PIXELFONT_U8 unsigned char
#endif
#ifndef PIXELFONT_U16
#define PIXELFONT_U16 unsigned short
#endif
#ifndef PIXELFONT_U32
#define PIXELFONT_U32 unsigned int
#endif
typedef struct pixelfont_t
{
PIXELFONT_U32 size_in_bytes;
PIXELFONT_U8 height;
PIXELFONT_U8 line_spacing;
PIXELFONT_U8 baseline;
PIXELFONT_U16 offsets[ 256 ];
PIXELFONT_U8 glyphs[ 1 ]; // "open" array - ok to access out of bounds (use size_in_bytes to determine the end)
} pixelfont_t;
typedef enum pixelfont_align_t
{
PIXELFONT_ALIGN_LEFT,
PIXELFONT_ALIGN_RIGHT,
PIXELFONT_ALIGN_CENTER,
} pixelfont_align_t;
typedef enum pixelfont_bold_t
{
PIXELFONT_BOLD_OFF,
PIXELFONT_BOLD_ON,
} pixelfont_bold_t;
typedef enum pixelfont_italic_t
{
PIXELFONT_ITALIC_OFF,
PIXELFONT_ITALIC_ON,
} pixelfont_italic_t;
typedef enum pixelfont_underline_t
{
PIXELFONT_UNDERLINE_OFF,
PIXELFONT_UNDERLINE_ON,
} pixelfont_underline_t;
typedef struct pixelfont_bounds_t
{
int width;
int height;
} pixelfont_bounds_t;
#endif /* pixelfont_h */
#ifndef PIXELFONT_COLOR
#define PIXELFONT_COLOR PIXELFONT_U8
#endif
#ifndef PIXELFONT_FUNC_NAME
#define PIXELFONT_FUNC_NAME pixelfont_blit
#endif
void PIXELFONT_FUNC_NAME( pixelfont_t const* font, int x, int y, char const* text, PIXELFONT_COLOR color,
PIXELFONT_COLOR* target, int width, int height, pixelfont_align_t align, int wrap_width, int hspacing,
int vspacing, int limit, pixelfont_bold_t bold, pixelfont_italic_t italic, pixelfont_underline_t underline,
pixelfont_bounds_t* bounds );
/*
----------------------
IMPLEMENTATION
----------------------
*/
#ifdef PIXELFONT_IMPLEMENTATION
#undef PIXELFONT_IMPLEMENTATION
#ifndef PIXELFONT_PIXEL_FUNC
#define PIXELFONT_PIXEL_FUNC( dst, src ) *(dst) = (src);
#endif
void PIXELFONT_FUNC_NAME( pixelfont_t const* font, int x, int y, char const* text, PIXELFONT_COLOR color,
PIXELFONT_COLOR* target, int width, int height, pixelfont_align_t align, int wrap_width, int hspacing,
int vspacing, int limit, pixelfont_bold_t bold, pixelfont_italic_t italic, pixelfont_underline_t underline,
pixelfont_bounds_t* bounds )
{
int xp = x;
int yp = y;
int max_x = x;
int last_x_on_line = xp;
int count = 0;
char const* str = text;
while( *str )
{
int line_char_count = 0;
int line_width = 0;
int last_space_char_count = 0;
int last_space_width = 0;
char const* tstr = str;
while( *tstr != '\n' && *tstr != '\0' && ( wrap_width <= 0 || line_width <= wrap_width ) )
{
if( *tstr <= ' ' )
{
last_space_char_count = line_char_count;
last_space_width = line_width;
}
PIXELFONT_U8 const* g = font->glyphs + font->offsets[ (int) *tstr ];
line_width += (PIXELFONT_I8) *g++;
int w = *g++;
g += font->height * w;
line_width += (PIXELFONT_I8) *g++;
line_width += hspacing + ( bold ? 1 : 0 );
++tstr;
int kern = *g++;
for( int k = 0; k < kern; ++k )
if( *g++ == *tstr ) { line_width += (PIXELFONT_I8) *g++; break; } else ++g;
++line_char_count;
}
bool skip_space = false;
if( wrap_width > 0 && line_width > wrap_width )
{
line_char_count = last_space_char_count;
line_width = last_space_width;
skip_space = true;
}
if( wrap_width > 0 )
{
if( align == PIXELFONT_ALIGN_RIGHT ) x += wrap_width - line_width;
if( align == PIXELFONT_ALIGN_CENTER ) x += ( wrap_width - line_width ) / 2;
}
else
{
if( align == PIXELFONT_ALIGN_RIGHT ) x -= line_width;
if( align == PIXELFONT_ALIGN_CENTER ) x -= line_width / 2;
}
for( int c = 0; c < line_char_count; ++c )
{
PIXELFONT_U8 const* g = font->glyphs + font->offsets[ (int) *str ];
x += (PIXELFONT_I8) *g++;
int w = *g++;
int h = font->height;
for( int iy = y; iy < y + h; ++iy )
{
int xs = x + ( italic ? ( h - ( iy - y ) ) / 2 - 1 : 0 );
for( int ix = xs; ix < xs + w; ++ix )
{
if( *g++ && target )
if( limit < 0 || count < limit )
if( ix >= 0 && iy >= 0 && ix < width && iy < height )
{
last_x_on_line = ix >= last_x_on_line ? ix + ( bold ? 1 : 0 ) : last_x_on_line;
PIXELFONT_PIXEL_FUNC( ( &target[ ix + iy * width ] ), color );
if( bold && ix + 1 < width )
PIXELFONT_PIXEL_FUNC( ( &target[ ix + 1 + iy * width ] ), color );
}
}
}
x += (PIXELFONT_I8) *g++;
x += hspacing + ( bold ? 1 : 0 );
++str;
++count;
int kern = *g++;
for( int k = 0; k < kern; ++k )
if( *g++ == *str ) { x += (PIXELFONT_I8) *g++; break; } else ++g;
}
if( underline && target && y + font->baseline + 1 >= 0 && y + font->baseline + 1 < height && last_x_on_line > xp )
for( int ix = xp; ix <= last_x_on_line; ++ix )
if( ix >= 0 && ix < width )
PIXELFONT_PIXEL_FUNC( ( &target[ ix + ( y + font->baseline + 1 ) * width ] ), color );
last_x_on_line = xp;
max_x = x > max_x ? x : max_x;
x = xp;
y += font->line_spacing + vspacing;
if( *str == '\n' ) ++str;
if( *str && skip_space && *str <= ' ' ) ++str;
}
if( bounds )
{
bounds->width = wrap_width > 0 ? wrap_width : ( max_x - xp );
bounds->height = y - yp;
}
}
#endif /* PIXELFONT_IMPLEMENTATION */
#undef PIXELFONT_COLOR
#undef PIXELFONT_FUNC_NAME
/*
------------------------------------------------------------------------------
This software is available under 2 licenses - you may choose the one you like.
------------------------------------------------------------------------------
ALTERNATIVE A - 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.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
*/ | c | 25 | 0.617816 | 118 | 29.730216 | 278 | starcoderdata |
<?php
namespace Billplz\Base\Collection;
use Billplz\Request;
use Laravie\Codex\Contracts\Response;
use Billplz\Contracts\Collection\PaymentMethod as Contract;
class PaymentMethod extends Request implements Contract
{
/**
* Get payment method index.
*
* @return \Billplz\Response
*/
public function get(string $collectionId): Response
{
return $this->send('GET', "collections/{$collectionId}/payment_methods", [], []);
}
/**
* Update payment methods.
*
* @param string $id
*
* @return \Billplz\Response
*/
public function update(string $collectionId, array $codes = []): Response
{
$payments = [];
foreach ($codes as $code) {
\array_push($payments, \compact('code'));
}
return $this->send('PUT', "collections/{$collectionId}/payment_methods", [], $payments);
}
} | php | 15 | 0.607415 | 96 | 22.512821 | 39 | starcoderdata |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Draw.src.Model
{
[JsonObject]
public class TriangleShape : Shape
{
#region Constructor
[JsonConstructor]
public TriangleShape(RectangleF rect) : base(rect)
{
}
public TriangleShape(RectangleShape rectangle) : base(rectangle)
{
}
#endregion
///
/// Проверка за принадлежност на точка point към правоъгълника.
/// В случая на правоъгълник този метод може да не бъде пренаписван, защото
/// Реализацията съвпада с тази на абстрактния клас Shape, който проверява
/// дали точката е в обхващащия правоъгълник на елемента (а той съвпада с
/// елемента в този случай).
///
public override bool Contains(PointF point)
{
//if (base.Contains(point))
// // Проверка дали е в обекта само, ако точката е в обхващащия правоъгълник.
// // В случая на правоъгълник - директно връщаме true
// return true;
//else
// // Ако не е в обхващащия правоъгълник, то неможе да е в обекта и => false
// return false;
float x1 = Rectangle.X;
float y1 = Rectangle.Y;
float x2 = Rectangle.X;
float y2 = Rectangle.Y + Width;
float x3 = Rectangle.X + Height;
float y3 = Rectangle.Y;
float p1 = point.X;
float p2 = point.Y;
double A = area(x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
double A1 = area(p1, p2, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
double A2 = area(x1, y1, p1, p2, x3, y3);
/* Calculate area of triangle PAB */
double A3 = area(x1, y1, x2, y2, p1, p2);
/* Check if sum of A1, A2 and A3 is same as A */
if (A == A1 + A2 + A3)
{
return true;
}
else
{
return false;
}
}
///
/// Частта, визуализираща конкретния примитив.
///
///
public override void DrawSelf(Graphics grfx)
{
base.DrawSelf(grfx);
PointF point1 = new PointF(Rectangle.X, Rectangle.Y);
PointF point2 = new PointF(Rectangle.X + Width, Rectangle.Y);
PointF point3 = new PointF(Rectangle.X , Rectangle.Y + Height);
PointF[] points = { point1, point2, point3 };
grfx.FillPolygon(new SolidBrush(FillColor), points);
grfx.DrawPolygon(new Pen(BorderColor, BorderSize), points);
}
static double area(float x1, float y1, float x2,
float y2, float x3, float y3)
{
return Math.Abs((x1 * (y2 - y3) +
x2 * (y3 - y1) +
x3 * (y1 - y2)) / 2.0);
}
}
} | c# | 18 | 0.635557 | 80 | 22.572727 | 110 | starcoderdata |
import React from 'react';
import { connect } from 'react-redux';
import OpenFile from './OpenFile';
import { closeBgSettingsPanel, insert, setBgImage, setBgVideo } from '../actions/actions';
import { getLabels, getInitialSlideBgSettings, getNewSlideBgSettings, getLeftPanelStatus } from '../selectors';
import Label from './Label';
import InputWrapper from './InputWrapper';
import Button from './Button';
import Panel from './Panel';
const mapStateToProps = (state) => ({
labels: getLabels(state),
open: getLeftPanelStatus(state),
initial: getInitialSlideBgSettings(state),
new: getNewSlideBgSettings(state)
});
const mapDispatchToProps = dispatch => ({
closePanel: () => dispatch(closeBgSettingsPanel()),
insert: (stringsToInsert) => dispatch(insert(stringsToInsert)),
});
class BgPanel extends React.Component {
constructor(props) {
super(props);
this.changedSettings = {};
this.state = this.getBlankState();
}
getBlankState() {
return {
'background-color': '#000000',
'background-image': '',
'background-size': 'cover',
'background-position': 'center center',
'background-video': '',
'background-video-loop': false,
'background-video-muted': false,
'background-iframe': ''
};
}
componentWillReceiveProps(nextProps) {
if (!nextProps.open) {
return;
}
if (Object.keys(nextProps.new).length) {
this.recordChange(nextProps.new);
return
}
if (Boolean(nextProps.initial) && Object.keys(nextProps.initial).length) {
var nextState = Object.assign({}, nextProps.initial);
this.setState(nextState);
return;
}
this.setState(this.getBlankState());
}
handleChange(event, key) {
var input = event.target;
var value = input.type === 'checkbox' ? input.checked : input.value;
var obj = {};
obj[key] = value;
this.recordChange(obj);
}
recordChange(newSetting) {
Object.assign(this.changedSettings, newSetting);
this.setState(Object.assign({}, this.state, newSetting));
}
handleSubmit(e) {
var stringsToInsert = Object.keys(this.changedSettings)
.map(key => {
// if (this.changedSettings[key] === '') {
// return null;
// }
var insert = this.changedSettings[key] ? key + '="' + this.changedSettings[key] + '"' : '';
var pattern = key + '="[^"]+"';
return { insert, pattern };
})
//.filter(item => item)
;
this.props.insert(stringsToInsert);
this.exit();
}
updateBgPos(e, axis) {
var currentBgPos = this.state['background-position'].split(' ');
var newBbPosBit = e.target.value;
var newBgPos = currentBgPos;
var updateIndex = (axis === 'x') ? 0 : 1;
newBgPos[updateIndex] = newBbPosBit;
Object.assign(this.changedSettings, { 'background-position': newBgPos.join(' ') });
}
exit() {
this.changedSettings = {};
this.props.closePanel();
}
render() {
return (
<Panel name='leftPanel bgOptionsPanel' closePanel={this.props.closePanel}>
<InputWrapper name='colorWrapper'>
<Label inputId='colorBg' text={this.props.labels['Background color']} />
<input id='colorBg' type='color'
onChange={(e) => this.handleChange(e, 'background-color')}
value={this.state['background-color']} />
<OpenFile
name='imgBgWrapper'
label={this.props.labels['Background image']}
buttonText={this.props.labels['Select image']}
finalAction={(path) => setBgImage(path)}
fileType='img'
handler={
imgPath => {
this.recordChange({ 'background-image': imgPath });
}
}
value={this.state['background-image']}
/>
<InputWrapper name="bgSizeWrapper">
<Label inputId="bgSize" text={this.props.labels['Background size']} />
<input type="text"
id="bgSize"
placeholder="es: cover, contain, 3em, 10%, ecc."
value={this.state['background-size']}
onChange={(e) => this.handleChange(e, 'background-size')}
/>
<InputWrapper name="bgPositionXWrapper">
<Label inputId="bgPositionX" text={this.props.labels['Background position x']} />
<select id="bgPositionX" className="bgPositionPartial"
onChange={(e) => this.updateBgPos(e, 'x')}
>
<InputWrapper name="bgPositionYWrapper">
<Label inputId="bgPositionY" text={this.props.labels['Background position y']} />
<select id="bgPositionY" className="bgPositionPartial"
onChange={(e) => this.updateBgPos(e, 'y')}
>
<InputWrapper name="bgRepeatWrapper">
<Label inputId="bgRepeat" text={this.props.labels['Background repeat']} />
<select id="bgRepeat" onChange={(e) => this.handleChange(e, 'background-repeat')}>
<OpenFile
name='videoBgWrapper'
label={this.props.labels['Background video']}
buttonText={this.props.labels['Select video']}
finalAction={(path) => setBgVideo(path)}
fileType='video'
handler={
filePath => {
this.recordChange({ 'background-video': filePath });
}
}
value={this.state['background-video']}
/>
<InputWrapper name="videoBgLoopWrapper">
<input id="videoBgLoop" type="checkbox"
disabled={!this.changedSettings['background-video']}
value={this.state['background-video-loop']}
onChange={(e) => this.handleChange(e, 'background-video-loop')}
/>
<Label inputId="videoBgLoop" text={this.props.labels['Background video loop']} />
<InputWrapper name="videoBgMutedWrapper">
<input id="videoBgLoop" type="checkbox"
disabled={!this.changedSettings['background-video']}
value={this.state['background-video-muted']}
onChange={(e) => this.handleChange(e, 'background-video-muted')}
/>
<Label inputId="videoBgLoop" text={this.props.labels['Background video muted']} />
<InputWrapper name="iframeBgWrapper">
<Label inputId="iframeBg" text={this.props.labels['Background web page']} />
<input id="iframeBg" type="text" placeholder="http://www.example.com"
onChange={(e) => this.handleChange(e, 'background-iframe')}
value={this.state['background-iframe']}
/>
<Button data-input-id="iframeBg" text={this.props.labels['Reset']}
clickHandler={() => this.recordChange({ 'background-iframe': '' })}
/>
<div className="buttonRow">
<Button clickHandler={() => this.exit()} text={this.props.labels['Cancel']} />
<Button clickHandler={(e) => this.handleSubmit(e)} text={this.props.labels['Save']} />
);
}
};
export default connect(mapStateToProps, mapDispatchToProps)(BgPanel); | javascript | 19 | 0.627862 | 111 | 28.982906 | 234 | starcoderdata |
var Floor = function Floor(game,posx,posy) {
this.game = game;
this.sprite = null;
this.posx = posx;
this.posy = posy;
}
Floor.prototype.create= function() {
this.sprite = this.game.add.sprite(this.posx, this.posy, 'floor');
this.game.physics.arcade.enable(this.sprite);
this.sprite.body.allowGravity = false;
this.sprite.body.immovable = true;
this.sprite.smoothed = false;
this.sprite.scale.set(3,3);
this.sprite.anchor.setTo(0.5, 1);
}
Floor.prototype.update = function() {
}
Floor.prototype.collide= function(collider) {}
module.exports = Floor; | javascript | 17 | 0.680062 | 70 | 24.92 | 25 | starcoderdata |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\post;
use App\comment;
use App\user;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function user()
{
$comments = comment::all();
$posts= post::all();
$count = comment::all()->count();
return view('category',['post'=>$posts],['comments'=>$comments],['count'=>$count]);
}
public function createCmt($id,$c_o)
{
$comments = new comment();
$comments->post_id = $id;
$comments->c_owner = $c_o;
$comments->comment = request('comment');
$comments->save();
return redirect('/category');
}
public function adminHome()
{
$posts= post::all();
$user = User::select('*')->where('is_admin','=', 1)->get();
return view('adminHome',['post'=>$posts],['user'=>$user]);
}
public function createPost()
{
$post = new post();
$post->post_title = request('post_title');
$post->mes_post = request('mes_post');
$post->save();
return redirect('adminHome')->with('mssg', 'your post has been uploaded!!!');
}
public function destroy($id)
{
$posts = post::findOrFail($id);
$comment = comment::where('post_id','=',$id);
$comment->delete();
$posts->delete();
return redirect('adminHome');
}
} | php | 13 | 0.536873 | 91 | 23.565217 | 69 | starcoderdata |
bool StreamCpp::SetPosition(off_type position, PositionType positionType)
{
// Currently we assume there is an istream present.
if(mpStdIstream)
{
switch(positionType)
{
case kPositionTypeBegin:
mpStdIstream->seekg((std::streamoff)position, std::ios::beg);
return !(mpStdOstream->rdstate() & (std::ios::failbit | std::ios::badbit));
case kPositionTypeCurrent:
return SetPosition((off_type)mpStdIstream->tellg() + position, kPositionTypeBegin);
case kPositionTypeEnd:
return SetPosition((off_type)mpStdIstream->tellg() + (off_type)GetSize() + position, kPositionTypeBegin);
}
}
return false;
} | c++ | 16 | 0.61705 | 121 | 34.238095 | 21 | inline |
<?php
namespace frontend\models;
use common\models\Account;
use Yii;
/**
* Signup form
*/
class Work extends Account
{
public $institute_name;
public $degree;
public $time_period;
public $description;
/**
* @inheritdoc
*/
public function rules()
{
return [
['id', 'integer'],
['name', 'filter', 'filter' => 'trim'],
[['name', 'email'], 'required', 'message' => '{attribute} không được rỗng.'],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'validateEmail'],
];
}
public function validateEmail($attribute, $params)
{
if (!$this->hasErrors())
{
$model = User::find()->where(['email' => $this->email])->one();
if (!empty($model))
{
if ($model->id != $this->id)
$this->addError($attribute, $this->email . ' đã tồn tại trong hệ thống.');
}
}
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
];
}
public function profile()
{
if ($this->validate())
{
$user = Account::findOne($this->id);
$user->username = $this->username;
$user->email = $this->email;
$user->firstname = $this->firstname;
$user->lastname = $this->lastname;
if ($user->save())
{
return $user;
}
}
return null;
}
} | php | 17 | 0.445133 | 94 | 20.223684 | 76 | starcoderdata |
import Button from '../../../../plugins/input/button/Button.js';
import EmitChildEvent from './EmitChildEvent.js';
const GetValue = Phaser.Utils.Objects.GetValue;
var ClickChild = function (config) {
var clickConfig = GetValue(config, 'click', undefined);
if (clickConfig === false) {
return;
}
if (clickConfig === undefined) {
clickConfig = {};
}
if (!clickConfig.hasOwnProperty('threshold')) {
clickConfig.threshold = 10;
}
this._click = new Button(this, clickConfig);
this._click.on('click', function (button, gameObject, pointer) {
EmitChildEvent(
this.eventEmitter,
`${this.input.eventNamePrefix}click`,
this.input.targetSizers,
pointer.x, pointer.y,
pointer
);
}, this);
};
export default ClickChild; | javascript | 9 | 0.632632 | 98 | 28.71875 | 32 | starcoderdata |
// Cannot implicitly shard accessed collections because queries on a sharded collection are not
// able to be covered when they aren't on the shard key since the document needs to be fetched in
// order to apply the SHARDING_FILTER stage.
// @tags: [
// assumes_unsharded_collection,
// ]
// Test indexing of decimal numbers
(function() {
'use strict';
// Include helpers for analyzing explain output.
load('jstests/libs/analyze_plan.js');
var t = db.decimal_indexing;
t.drop();
// Create doubles and NumberDecimals. The double 0.1 is actually 0.10000000000000000555
// and the double 0.3 is actually 0.2999999999999999888, so we can check ordering.
assert.commandWorked(t.insert({x: 0.1, y: NumberDecimal('0.3000')}));
assert.commandWorked(t.insert({x: 0.1}));
assert.commandWorked(t.insert({y: 0.3}));
// Create an index on existing numbers.
assert.commandWorked(t.createIndex({x: 1}));
assert.commandWorked(t.createIndex({y: -1}));
// Insert some more items after index creation. Use _id for decimal.
assert.commandWorked(t.insert({x: NumberDecimal('0.10')}));
assert.commandWorked(t.insert({_id: NumberDecimal('0E3')}));
assert.writeError(t.insert({_id: -0.0}));
// Check that we return exactly the right document, use an index to do so, and that the
// result of the covered query has the right number of trailing zeros.
var qres = t.find({x: NumberDecimal('0.1')}, {_id: 0, x: 1}).toArray();
var qplan = t.find({x: NumberDecimal('0.1')}, {_id: 0, x: 1}).explain();
assert.neq(tojson(NumberDecimal('0.1')),
tojson(NumberDecimal('0.10')),
'trailing zeros are significant for exact equality');
assert.eq(
qres, [{x: NumberDecimal('0.10')}], 'query for x equal to decimal 0.10 returns wrong value');
assert(isIndexOnly(db, qplan.queryPlanner.winningPlan),
'query on decimal should be covered: ' + tojson(qplan));
// Check that queries for exact floating point numbers don't return nearby decimals.
assert.eq(t.find({x: 0.1}, {_id: 0}).sort({x: 1, y: 1}).toArray(),
[{x: 0.1}, {x: 0.1, y: NumberDecimal('0.3000')}],
'wrong result for querying {x: 0.1}');
assert.eq(t.find({x: {$lt: 0.1}}, {_id: 0}).toArray(),
[{x: NumberDecimal('0.10')}],
'querying for decimal less than double 0.1 should return decimal 0.10');
assert.eq(t.find({y: {$lt: NumberDecimal('0.3')}}, {y: 1, _id: 0}).toArray(),
[{y: 0.3}],
'querying for double less than decimal 0.3 should return double 0.3');
assert.eq(t.find({_id: 0}, {_id: 1}).toArray(),
[{_id: NumberDecimal('0E3')}],
'querying for zero does not return the correct decimal');
})(); | javascript | 20 | 0.666036 | 97 | 44.534483 | 58 | starcoderdata |
///VectorAdd sample, from the NVidia JumpStart Guide
///http://developer.download.nvidia.com/OpenCL/NVIDIA_OpenCL_JumpStart_Guide.pdf
///Instead of #include we include
///Apart from this include file, all other code should compile and work on OpenCL compliant implementation
#include
#include
#include
#include
void printDevInfo(cl_device_id device)
{
char device_string[1024];
clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_string), &device_string, NULL);
printf( " Device %s:\n", device_string);
// CL_DEVICE_INFO
cl_device_type type;
clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(type), &type, NULL);
if( type & CL_DEVICE_TYPE_CPU )
printf(" CL_DEVICE_TYPE:\t\t%s\n", "CL_DEVICE_TYPE_CPU");
if( type & CL_DEVICE_TYPE_GPU )
printf( " CL_DEVICE_TYPE:\t\t%s\n", "CL_DEVICE_TYPE_GPU");
if( type & CL_DEVICE_TYPE_ACCELERATOR )
printf( " CL_DEVICE_TYPE:\t\t%s\n", "CL_DEVICE_TYPE_ACCELERATOR");
if( type & CL_DEVICE_TYPE_DEFAULT )
printf( " CL_DEVICE_TYPE:\t\t%s\n", "CL_DEVICE_TYPE_DEFAULT");
// CL_DEVICE_MAX_COMPUTE_UNITS
cl_uint compute_units;
clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(compute_units), &compute_units, NULL);
printf( " CL_DEVICE_MAX_COMPUTE_UNITS:\t%d\n", compute_units);
// CL_DEVICE_MAX_WORK_GROUP_SIZE
size_t workitem_size[3];
clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(workitem_size), &workitem_size, NULL);
printf( " CL_DEVICE_MAX_WORK_ITEM_SIZES:\t%d / %d / %d \n", workitem_size[0], workitem_size[1], workitem_size[2]);
}
// Main function
// *********************************************************************
int main(int argc, char **argv)
{
void *srcA, *srcB, *dst; // Host buffers for OpenCL test
cl_context cxGPUContext; // OpenCL context
cl_command_queue cqCommandQue; // OpenCL command que
cl_device_id* cdDevices; // OpenCL device list
cl_program cpProgram; // OpenCL program
cl_kernel ckKernel; // OpenCL kernel
cl_mem cmMemObjs[3]; // OpenCL memory buffer objects: 3 for device
size_t szGlobalWorkSize[1]; // 1D var for Total # of work items
size_t szLocalWorkSize[1]; // 1D var for # of work items in the work group
size_t szParmDataBytes; // Byte size of context information
cl_int ciErr1, ciErr2; // Error code var
int iTestN = 100000 * 8; // Size of Vectors to process
// set Global and Local work size dimensions
szGlobalWorkSize[0] = iTestN >> 3; // do 8 computations per work item
szLocalWorkSize[0]= iTestN>>3;
// Allocate and initialize host arrays
srcA = (void *)malloc (sizeof(cl_float) * iTestN);
srcB = (void *)malloc (sizeof(cl_float) * iTestN);
dst = (void *)malloc (sizeof(cl_float) * iTestN);
int i;
// Initialize arrays with some values
for (i=0;i<iTestN;i++)
{
((cl_float*)srcA)[i] = cl_float(i);
((cl_float*)srcB)[i] = 2;
((cl_float*)dst)[i]=-1;
}
// Create OpenCL context & context
cxGPUContext = clCreateContextFromType(0, CL_DEVICE_TYPE_CPU, NULL, NULL, &ciErr1); //could also be CL_DEVICE_TYPE_GPU
// Query all devices available to the context
ciErr1 |= clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
cdDevices = (cl_device_id*)malloc(szParmDataBytes);
ciErr1 |= clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);
if (cdDevices)
{
printDevInfo(cdDevices[0]);
}
// Create a command queue for first device the context reported
cqCommandQue = clCreateCommandQueue(cxGPUContext, cdDevices[0], 0, &ciErr2);
ciErr1 |= ciErr2;
// Allocate the OpenCL source and result buffer memory objects on the device GMEM
cmMemObjs[0] = clCreateBuffer(cxGPUContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_float8) * szGlobalWorkSize[0], srcA, &ciErr2);
ciErr1 |= ciErr2;
cmMemObjs[1] = clCreateBuffer(cxGPUContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_float8) * szGlobalWorkSize[0], srcB, &ciErr2);
ciErr1 |= ciErr2;
cmMemObjs[2] = clCreateBuffer(cxGPUContext, CL_MEM_WRITE_ONLY, sizeof(cl_float8) * szGlobalWorkSize[0], NULL, &ciErr2);
ciErr1 |= ciErr2;
///create kernels from binary
int numDevices = 1;
cl_int err;
::size_t* lengths = (::size_t*) malloc(numDevices * sizeof(::size_t));
const unsigned char** images = (const unsigned char**) malloc(numDevices * sizeof(const void*));
for (i = 0; i < numDevices; ++i) {
images[i] = 0;
lengths[i] = 0;
}
cpProgram = clCreateProgramWithBinary(cxGPUContext, numDevices,cdDevices,lengths, images, 0, &err);
// Build the executable program from a binary
ciErr1 |= clBuildProgram(cpProgram, 0, NULL, NULL, NULL, NULL);
// Create the kernel
ckKernel = clCreateKernel(cpProgram, "VectorAdd", &ciErr1);
// Set the Argument values
ciErr1 |= clSetKernelArg(ckKernel, 0, sizeof(cl_mem), (void*)&cmMemObjs[0]);
ciErr1 |= clSetKernelArg(ckKernel, 1, sizeof(cl_mem), (void*)&cmMemObjs[1]);
ciErr1 |= clSetKernelArg(ckKernel, 2, sizeof(cl_mem), (void*)&cmMemObjs[2]);
// Copy input data from host to GPU and launch kernel
ciErr1 |= clEnqueueNDRangeKernel(cqCommandQue, ckKernel, 1, NULL, szGlobalWorkSize, szLocalWorkSize, 0, NULL, NULL);
// Read back results and check accumulated errors
ciErr1 |= clEnqueueReadBuffer(cqCommandQue, cmMemObjs[2], CL_TRUE, 0, sizeof(cl_float8) * szGlobalWorkSize[0], dst, 0, NULL, NULL);
// Release kernel, program, and memory objects
// NOTE: Most properly this should be done at any of the exit points above, but it is omitted elsewhere for clarity.
free(cdDevices);
clReleaseKernel(ckKernel);
clReleaseProgram(cpProgram);
clReleaseCommandQueue(cqCommandQue);
clReleaseContext(cxGPUContext);
// print the results
int iErrorCount = 0;
for (i = 0; i < iTestN; i++)
{
if (((float*)dst)[i] != ((float*)srcA)[i]+((float*)srcB)[i])
iErrorCount++;
}
if (iErrorCount)
{
printf("MiniCL validation FAILED\n");
} else
{
printf("MiniCL validation SUCCESSFULL\n");
}
// Free host memory, close log and return success
for (i = 0; i < 3; i++)
{
clReleaseMemObject(cmMemObjs[i]);
}
free(srcA);
free(srcB);
free (dst);
} | c++ | 14 | 0.658947 | 145 | 36.439306 | 173 | starcoderdata |
def save_topology_info(topo_name, node_dict, link_dict):
"""
Save topology info.
'node_dict' and 'link_dict' are saved in folder ."self.name"/"self.name"DB/
respectively in the files nodes.json and links.json.
"""
# Build up database_path
current_dir = os.path.dirname(__file__)
database_folder = topo_name + 'DB'
database_path = os.path.join(current_dir, topo_name, database_folder)
# If it doesn't exists, create it
if not os.path.exists(database_path):
os.mkdir(database_path)
# Save nodes and links data
write_to_json(node_dict, 'nodes', database_path)
write_to_json(link_dict, 'links', database_path) | python | 8 | 0.651026 | 79 | 31.52381 | 21 | inline |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uk.trainwatch.web.signal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import uk.trainwatch.nrod.td.berth.BerthMap;
import uk.trainwatch.util.sql.KeyValue;
import uk.trainwatch.web.rest.Cache;
import uk.trainwatch.web.rest.Rest;
/**
*
* @author peter
*/
@Path("/rail/1/signal")
@RequestScoped
public class SignalRest
{
@Inject
private SignalManager signalManager;
/**
* Returns a JSON Object defining the signal berths within a signalling area that is currently occupied.
*
* @param area
*
* @return
*/
@Path("/occupied/{area}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Cache(maxAge = 10, expires = 10, unit = ChronoUnit.SECONDS)
public Response occupied( @PathParam("area") String area )
{
return Rest.invoke( response -> {
Optional signalArea = Optional.empty();
if( area != null ) {
signalArea = signalManager.getSignalArea( area );
}
if( signalArea.isPresent() ) {
BerthMap map = signalManager.getArea( area );
if( map != null ) {
response.entity( map.stream().
collect( Collectors.toMap( KeyValue::getKey, KeyValue::getValue ) ) ).
lastModified( Instant.ofEpochMilli( map.getLastUpdate() ) );
}
}
} );
}
} | java | 23 | 0.635636 | 108 | 28.820896 | 67 | starcoderdata |
void testInsert_reverseorder(value_T *master_table, size_t item_count, const std::string &myTypeName, size_t iteration_count, bool do_summarize = true ) {
// reverse the master list order
std::reverse( master_table, master_table+item_count );
testInsert_common<value_T>(master_table,item_count,myTypeName,iteration_count, "reverse order");
if (do_summarize)
summarize("Associative Container reverse order insert", item_count, iterations, kDontShowGMeans, kDontShowPenalty );
} | c++ | 8 | 0.741551 | 154 | 49.4 | 10 | inline |
using System;
using System.Windows.Media;
using ATL;
using Gouter.DataModels;
using Gouter.Utils;
namespace Gouter;
///
/// アルバム情報
///
internal class AlbumInfo : NotificationObject, IPlaylistInfo
{
///
/// アルバムの内部ID
///
public int Id { get; }
///
/// アルバム識別キー
///
public string Key { get; }
///
/// アルバム名
///
public string Name { get; private set; }
///
/// アーティスト名
///
public string Artist { get; private set; }
///
/// アートワークID
///
public string ArtworkId { get; private set; }
///
/// アルバム情報登録日時
///
public DateTimeOffset RegisteredAt { get; }
///
/// アルバム情報更新日時
///
public DateTimeOffset UpdatedAt { get; private set; }
///
/// アルバムアートの最大サイズ
///
private const int MaxImageSize = 80;
///
/// トラック情報からアルバム情報を生成する
///
/// <param name="id">アルバムID
/// <param name="key">アルバムキー
/// <param name="track">トラック情報
public AlbumInfo(int id, string key, Track track, string artworkId)
{
this.Id = id;
this.Key = key;
this.Name = track.Album;
this.Artist = track.GetAlbumArtist();
this.IsCompilation = track.GetIsCompiatilnAlbum();
this.ArtworkId = artworkId;
this.RegisteredAt = DateTimeOffset.Now;
this.UpdatedAt = this.RegisteredAt;
this._isArtworkFound = artworkId != null;
this.Playlist = new AlbumPlaylist(this);
}
///
/// DBのモデルデータからアルバム情報を生成する
///
/// <param name="album">アルバム情報
/// <param name="artwork">アートワーク情報
public AlbumInfo(AlbumDataModel album, AlbumArtworksDataModel artwork)
{
this.Key = album.Key;
this.Id = album.Id;
this.Name = album.Name;
this.Artist = album.Artist;
this.ArtworkId = album.ArtworkId;
this.IsCompilation = album.IsCompilation ?? false;
this.RegisteredAt = album.CreatedAt;
this.UpdatedAt = album.UpdatedAt;
this._isArtworkFound = album.ArtworkId != null;
this.Playlist = new AlbumPlaylist(this);
}
private bool _isArtworkFound = false;
private object @_lockObj = new object();
///
/// アートワーク
///
public ImageSource Artwork
{
get
{
if (!this._isArtworkFound)
{
return ImageUtil.GetMissingAlbumImage();
}
else
{
var awkMgr = App.Instance.MediaManager.Artwork;
using var stream = awkMgr.GetStream(this);
return stream == null
? ImageUtil.GetMissingAlbumImage()
: ImageUtil.BitmapSourceFromStream(stream);
}
}
}
///
/// コンピレーションアルバムか否かのフラグ
///
public bool IsCompilation { get; private set; }
///
/// プレイリスト情報
///
public AlbumPlaylist Playlist { get; }
} | c# | 18 | 0.566902 | 74 | 23.816794 | 131 | starcoderdata |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
// Common libraries
#include "Kismet/KismetArrayLibrary.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Kismet/KismetMathLibrary.h"
// Special libraries
#include "Kismet/DataTableFunctionLibrary.h"
FORCEINLINE UClass* DynamicMetaCast(const UClass* DesiredClass, UClass* SourceClass)
{
return ((SourceClass)->IsChildOf(DesiredClass)) ? SourceClass : NULL;
}
struct FCustomThunkTemplates
{
//Replacements for CustomThunk functions from UKismetArrayLibrary
template<typename T>
static int32 Array_Add(TArray TargetArray, const T& NewItem)
{
return TargetArray.Add(NewItem);
}
template<typename T>
static int32 Array_AddUnique(TArray TargetArray, const T& NewItem)
{
return TargetArray.AddUnique(NewItem);
}
template<typename T>
static void Array_Shuffle(TArray TargetArray, const UArrayProperty* ArrayProperty)
{
int32 LastIndex = TargetArray.Num() - 1;
for (int32 i = 0; i < LastIndex; ++i)
{
int32 Index = FMath::RandRange(0, LastIndex);
if (i != Index)
{
TargetArray.Swap(i, Index);
}
}
}
template<typename T>
static void Array_Append(TArray TargetArray, const TArray SourceArray)
{
TargetArray.Append(SourceArray);
}
template<typename T>
static void Array_Insert(TArray TargetArray, const T& NewItem, int32 Index)
{
TargetArray.Insert(NewItem, Index);
}
template<typename T>
static void Array_Remove(TArray TargetArray, int32 IndexToRemove)
{
if (ensure(TargetArray.IsValidIndex(IndexToRemove)))
{
TargetArray.RemoveAt(IndexToRemove);
}
}
template<typename T>
static int32 Array_Find(const TArray TargetArray, const T& ItemToFind)
{
return TargetArray.Find(ItemToFind);
}
template<typename T>
static bool Array_RemoveItem(TArray TargetArray, const T& Item)
{
return TargetArray.Remove(Item);
}
template<typename T>
static void Array_Clear(TArray TargetArray)
{
TargetArray.Empty();
}
template<typename T>
static void Array_Resize(TArray TargetArray, int32 Size)
{
TargetArray.SetNum(Size);
}
template<typename T>
static int32 Array_Length(const TArray TargetArray)
{
return TargetArray.Num();
}
template<typename T>
static int32 Array_LastIndex(const TArray TargetArray)
{
return TargetArray.Num() - 1;
}
template<typename T>
static void Array_Get(TArray TargetArray, int32 Index, T& Item)
{
Item = TargetArray[Index];
}
template<typename T>
static void Array_Set(TArray TargetArray, int32 Index, const T& Item, bool bSizeToFit)
{
if (ensure(Index >= 0))
{
if (!TargetArray.IsValidIndex(Index) && bSizeToFit)
{
TargetArray.SetNum(Index + 1);
}
if (TargetArray.IsValidIndex(Index))
{
TargetArray[Index] = Item;
}
}
}
template<typename T>
static bool Array_Contains(const TArray TargetArray, const T& ItemToFind)
{
return TargetArray.Contains(ItemToFind);
}
template<typename T>
static void SetArrayPropertyByName(UObject* Object, FName PropertyName, TArray Value)
{
UKismetArrayLibrary::GenericArray_SetArrayPropertyByName(Object, PropertyName, &Value);
}
//Replacements for CustomThunk functions from UDataTableFunctionLibrary
template<typename T>
static bool GetDataTableRowFromName(UDataTable* Table, FName RowName, T& OutRow)
{
return UDataTableFunctionLibrary::Generic_GetDataTableRowFromName(Table, RowName, &OutRow);
}
//Replacements for CustomThunk functions from UKismetSystemLibrary
template<typename T>
static void SetStructurePropertyByName(UObject* Object, FName PropertyName, const T& Value)
{
return UKismetSystemLibrary::Generic_SetStructurePropertyByName(Object, PropertyName, &Value);
}
};
template<typename IndexType, typename ValueType>
struct TSwitchPair
{
const IndexType& IndexRef;
ValueType& ValueRef;
TSwitchPair(const IndexType& InIndexRef, ValueType& InValueRef)
: IndexRef(InIndexRef)
, ValueRef(InValueRef)
{}
};
#if PLATFORM_COMPILER_HAS_VARIADIC_TEMPLATES
template<typename IndexType, typename ValueType>
ValueType& TSwitchValue(const IndexType& CurrentIndex, ValueType& DefaultValue, int OptionsNum)
{
return DefaultValue;
}
template<typename IndexType, typename ValueType, typename Head, typename... Tail>
ValueType& TSwitchValue(const IndexType& CurrentIndex, ValueType& DefaultValue, int OptionsNum, Head HeadOption, Tail... TailOptions)
{
if (CurrentIndex == HeadOption.IndexRef)
{
return HeadOption.ValueRef;
}
return TSwitchValue<IndexType, ValueType, Tail...>(CurrentIndex, DefaultValue, OptionsNum, TailOptions...);
}
#else //PLATFORM_COMPILER_HAS_VARIADIC_TEMPLATES
template<typename IndexType, typename ValueType>
ValueType& TSwitchValue(const IndexType& CurrentIndex, ValueType& DefaultValue, int OptionsNum, ...)
{
typedef TSwitchPair < IndexType, ValueType > OptionType;
ValueType* SelectedValuePtr = nullptr;
va_list Options;
va_start(Options, OptionsNum);
for (int OptionIt = 0; OptionIt < OptionsNum; ++OptionIt)
{
OptionType Option = va_arg(Options, OptionType);
if (Option.IndexRef == CurrentIndex)
{
SelectedValuePtr = &Option.ValueRef;
break;
}
}
va_end(Options);
return SelectedValuePtr ? *SelectedValuePtr : DefaultValue;
}
#endif //PLATFORM_COMPILER_HAS_VARIADIC_TEMPLATES | c | 29 | 0.748495 | 133 | 24.5625 | 208 | starcoderdata |
private Pair<String, String> resolveMethodAndSignature(ASTNode x,
com.sun.fortress.nodes.Type arrow, String methodName) throws Error {
Pair<String, String> method_and_signature = null;
String signature = null;
if ( arrow instanceof ArrowType ) {
// TODO should this be non-colliding single name instead?
// answer depends upon how intersection types are normalized.
// conservative answer is "no".
// methodName = Naming.mangleIdentifier(methodName);
signature = NamingCzar.jvmMethodDesc(arrow, component.getName());
} else if (arrow instanceof IntersectionType) {
IntersectionType it = (IntersectionType) arrow;
methodName = OverloadSet.actuallyOverloaded(it, paramCount) ?
OverloadSet.oMangle(methodName) : methodName;
signature = OverloadSet.getSignature(it, paramCount, typeAnalyzer);
} else {
throw sayWhat( x, "Neither arrow nor intersection type: " + arrow );
}
return new Pair<String,String>(methodName, signature);
} | java | 11 | 0.639011 | 84 | 46.25 | 24 | inline |
import json
from typing import Any, Dict
import requests
def lambda_handler(event: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
print(f"request: {json.dumps(event)}")
uuid_message = get_uuid_message()
return {
"statusCode": 200,
"headers": {"Content-Type": "text/plain"},
"body": uuid_message,
}
def get_uuid_message() -> str:
response = requests.get("https://httpbin.org/uuid")
uuid = response.json()["uuid"]
return f"Hello, CDK! Here is your UUID: {uuid}" | python | 10 | 0.620755 | 85 | 25.5 | 20 | starcoderdata |
static public void AddSimpleSetParametersToObject(
Utilities.CommandLineBuilder commandLineBuilder,
Framework.ITaskItem[] originalItems,
string valueQuoteChar,
bool foptimisticParameterDefaultValue
) {
System.Collections.Generic.IList<Framework.ITaskItem> items =
MsDeploy.Utility.SortParametersTaskItems(
originalItems,
foptimisticParameterDefaultValue,
MsDeploy.SimpleSyncParameterMetadata.Value.ToString()
);
if (commandLineBuilder != null && items != null)
{
System.Collections.Generic.List<string> arguments =
new System.Collections.Generic.List<string>(6);
foreach (Framework.ITaskItem item in items)
{
arguments.Clear();
// special for name
string name = item.ItemSpec;
if (!string.IsNullOrEmpty(name))
{
string valueData = MsDeploy.Utility.PutValueInQuote(name, valueQuoteChar);
arguments.Add(string.Concat("name=", valueData));
}
// the rest, build on the enum name
MsDeploy.Utility.BuildArgumentsBaseOnEnumTypeName(
item,
arguments,
typeof(MsDeploy.SimpleSyncParameterMetadata),
valueQuoteChar
);
commandLineBuilder.AppendSwitchUnquotedIfNotNull(
"-setParam:",
arguments.Count == 0 ? null : string.Join(",", arguments.ToArray())
);
}
}
} | c# | 18 | 0.500811 | 98 | 43.047619 | 42 | inline |
import { addStyles } from "../util"
let toast
export function setupToast() {
toast = document.createElement('div')
toast.classList.add('toast')
addStyles(toast, {
position: 'fixed',
top: 0,
left: 0,
right: 0,
margin: 'auto',
fontSize: '2rem',
textAlign: 'center',
fontFamily: 'sans-serif',
padding: '0.5rem',
background: '#202020',
color: '#ddd',
transition: 'transform 0.5s',
transform: 'translateY(-100%)'
})
document.body.append(toast)
}
export function showToast(text) {
toast.innerText = text
toast.style.transform = 'translateY(0)'
setTimeout(() => {
toast.style.transform = 'translateY(-100%)'
}, 2000)
} | javascript | 13 | 0.62029 | 47 | 19.323529 | 34 | starcoderdata |
package com.github.tavalin.orvibo.devices;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.tavalin.orvibo.OrviboClient;
import com.github.tavalin.orvibo.commands.CommandFactory;
import com.github.tavalin.orvibo.protocol.Message;
public class AllOne extends OrviboDevice {
/** The Constant logger. */
private final Logger logger = LoggerFactory.getLogger(AllOne.class);
private Path learnPath = null;
public AllOne() {
super(DeviceType.ALLONE);
}
public void emit(Path file) throws IOException {
Message message = CommandFactory.createEmitCommand(this, file);
OrviboClient orviboClient = getNetworkContext();
orviboClient.sendMessage(message);
}
public void learn(Path file) {
Message message = CommandFactory.createLearnCommand(this);
setLearnPath(file);
OrviboClient orviboClient = getNetworkContext();
orviboClient.sendMessage(message);
}
public void saveLearnedData(byte[] data) throws IOException {
if (data.length > 0) {
Path learnPath = getLearnPath();
if (learnPath == null) {
throw new IOException("Learn path has not been set. Could not save data.");
}
Path folder = learnPath.getParent();
if (!Files.exists(folder)) {
logger.debug("Folder does not exist: {}", folder.toAbsolutePath());
Files.createDirectory(folder);
logger.debug("Folder created: {}", folder.toAbsolutePath());
}
logger.debug("Writing learn data to {}", learnPath.toAbsolutePath());
Files.write(learnPath, data);
}
}
public Path getLearnPath() {
return learnPath;
}
public void setLearnPath(Path learnPath) {
this.learnPath = learnPath;
logger.debug("Learn path set to {}", learnPath.toAbsolutePath());
}
} | java | 14 | 0.647146 | 91 | 30.261538 | 65 | starcoderdata |
package opa
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/bradmccoydev/tfval/model"
"github.com/open-policy-agent/opa/rego"
)
func RetrieveOpaPolicyResponse(plan []byte, policyLocation string, opaRegoQuery string) string {
rs := GetOpaResultSet(plan, policyLocation, opaRegoQuery)
response := fmt.Sprintf("%v", rs[0].Expressions)
return strings.Replace(response, "},]", "}]", -1)
}
func GetDefaultOpaResponse(plan []byte, policyLocation string, opaRegoQuery string) string {
rs := GetOpaResultSet(plan, policyLocation, opaRegoQuery)
opaResponse := fmt.Sprintf("%v", rs[0].Expressions)
opaResponse = strings.Replace(opaResponse, "},]", "}]", -1)
b := []byte(opaResponse)
var validations model.TfValidation
if err := json.Unmarshal(b, &validations); err != nil {
fmt.Println(err)
}
weights := GetTfWeights(opaResponse)
scores := ""
for _, validation := range validations {
score := GetTfWeightByServiceNameAndAction(weights, validation.Data.Type, validation.Data.Change.Actions[0])
scores = fmt.Sprintf("%s{\"opa_resource_name\":\"%s\",\"opa_score\":%d},", scores, validation.Data.Address, score)
}
scores = strings.TrimRight(scores, ",")
return fmt.Sprintf("{\"opa_pass\":%t,\"opa_total_score\":%d,\"opa_max_acceptable_score\":%d,\"opa_scores\":[%s]}", validations[0].ValidationPassed, validations[0].Score, validations[0].MaxAcceptableScore, scores)
}
func CheckIfPlanPassesOpaPolicy(plan []byte, policyLocation string, opaRegoQuery string) bool {
rs := GetOpaResultSet(plan, policyLocation, opaRegoQuery)
// fmt.Println(rs[0].Expressions)
// fmt.Println(rs.Allowed())
return rs.Allowed()
}
func GetOpaScore(plan []byte, policyLocation string, opaRegoQuery string) int {
rs := GetOpaResultSet(plan, policyLocation, opaRegoQuery)
s := fmt.Sprint(rs[0].Expressions[0].Value)
i, _ := strconv.Atoi(s)
return i
}
func GetOpaConfig(opaConfig string) model.OpaConfig {
b := []byte(opaConfig)
var config model.OpaConfig
if err := json.Unmarshal(b, &config); err != nil {
fmt.Println(err)
}
return config
}
func GetOpaResultSet(plan []byte, policyLocation string, opaRegoQuery string) rego.ResultSet {
ctx := context.Background()
var input interface{}
r := rego.New(
rego.Query(opaRegoQuery),
rego.Load([]string{policyLocation}, nil))
query, err := r.PrepareForEval(ctx)
if err != nil {
fmt.Println(err)
}
if err := json.Unmarshal(plan, &input); err != nil {
fmt.Println(err)
}
rs, err := query.Eval(ctx, rego.EvalInput(input))
if err != nil {
fmt.Println(err)
}
return rs
}
func GetTfWeights(payload string) []model.Weight {
s := GetStringInBetweenTwoString(payload, "weights\":[", "}]")
lines := strings.Split(s, "}")
var weights []model.Weight
for _, line := range lines {
formatted := fmt.Sprintf("{ \"service\": %s%s", strings.Replace(line, ": {", ", ", -1), " },")
formatted = strings.Replace(formatted, ": , \"", ": \"", -1)
if strings.Contains(formatted, "create") {
var weight model.Weight
byte := []byte(strings.TrimRight(formatted, ","))
json.Unmarshal(byte, &weight)
weights = append(weights, weight)
}
}
return weights
}
func GetTfWeightByServiceNameAndAction(weights []model.Weight, serviceName string, action string) int {
actionWeight := 0
for _, weight := range weights {
if weight.Service == serviceName {
switch action {
case "delete":
actionWeight = weight.Delete
case "create":
actionWeight = weight.Create
case "modify":
actionWeight = weight.Modify
default:
actionWeight = 0
}
}
}
return actionWeight
}
func GetStringInBetweenTwoString(str string, startS string, endS string) (result string) {
s := strings.Index(str, startS)
if s == -1 {
return result
}
newS := str[s+len(startS):]
e := strings.Index(newS, endS)
if e == -1 {
return result
}
result = newS[:e]
return result
} | go | 13 | 0.686073 | 213 | 24.48366 | 153 | starcoderdata |
package org.multibit.hd.error_reporting.tasks;
import com.google.common.collect.ImmutableMultimap;
import com.yammer.dropwizard.tasks.Task;
import org.multibit.hd.error_reporting.ErrorReportingService;
import org.multibit.hd.error_reporting.resources.PublicErrorReportingResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
/**
* to provide the following to admin API:
*
* ingestion of persisted error reports
*
*
* @since 0.0.1
*
*/
public class IngestionTask extends Task {
private static final Logger log = LoggerFactory.getLogger(IngestionTask.class);
public IngestionTask() {
super("ingest");
}
@Override
public void execute(ImmutableMultimap<String, String> parameters, final PrintWriter output) throws Exception {
// Must be new or uncached to be here
log.debug("Ingesting persisted error reports to ELK.");
final File errorReportsDirectory = new File(ErrorReportingService.getErrorReportingDirectory().getAbsolutePath() + "/error-reports");
if (!errorReportsDirectory.exists()) {
output.println("Nothing to do. '" + errorReportsDirectory + "' is not present.");
return;
}
Path errorReportsPath = errorReportsDirectory.toPath();
FileVisitor visitor = new SimpleFileVisitor {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
output.print("Processing '" + file.toString() + "' ");
// Read file
String encryptedPayload = new String(Files.readAllBytes(file));
// Create a new resource (simulate an individual request)
PublicErrorReportingResource resource = new PublicErrorReportingResource();
final Response response = resource.submitEncryptedErrorReport(encryptedPayload);
if (response.getStatus() == 201) {
output.println("OK");
} else {
output.println("FAIL: " + response.getStatus());
}
Files.delete(file);
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(errorReportsPath, visitor);
} catch (IOException e) {
log.error("Failed to ingest error reports", e);
output.println("FAIL: " + e.getMessage());
}
}
} | java | 19 | 0.7 | 137 | 30 | 80 | starcoderdata |
package diy.uigeneric;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import diy.uigeneric.data.SampleServerDataSourceTest;
import diy.uigeneric.data.SampleServerIndirectListTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SampleServerDataSourceTest.class,
SampleServerIndirectListTest.class,
})
public class ApplicationSuiteServer {
/*
* PLEASE READ!
*
* - Run main program first.
* - Open Settings page.
* - Set base server address.
* - Run this test programs.
*/
} | java | 7 | 0.726688 | 76 | 24.916667 | 24 | starcoderdata |
void Part::Draw(QImage* pImage_)
{
if(m_pDrawing)
{
// 1.get accumulate transform
// from all parent
NTransform::TransformGroup* _pTransGroup
= new NTransform::TransformGroup();
NTransform::Transform* _pTrans
= GetTransform();
_pTrans->PrintDebugInfo();
_pTrans->setParent(_pTransGroup);
_pTransGroup->Add(_pTrans);
Part* _pParent = GetParent();
while(_pParent)
{
_pTrans = _pParent->GetTransform();
_pTrans->setParent(_pTransGroup);
_pTransGroup->Add(_pTrans);
_pParent = _pParent->GetParent();
}
// 2.draw self with right transform
_pTransGroup->PrintDebugInfo();
// every part's position
// and the translatings
// we discussed all based
// on logic coordinate
// to see the show coordinate
// with the show in logic coordinate
// before draw
// we add a logic to scree transform
// for every part
double _nMx[3][3] =
{
{1.0, 0.0 ,1.0},
{0.0, -1.0, 1.0},
{0.0, 0.0, 1.0},
};
NMatrix::Matrix _mxM(_nMx);
NTransform::MatrixTransform *_pMxTrans
= new NTransform::MatrixTransform(_mxM, _pTransGroup);
_pTransGroup->Add(_pMxTrans);
m_pDrawing->Draw(_pTransGroup, pImage_);
delete _pTransGroup;
}
// 3.let all child to draw
int _nSize = m_arrChilds.GetSize();
for(int i = 0; i < _nSize; i++)
{
m_arrChilds[i]->Draw(pImage_);
}
} | c++ | 11 | 0.464208 | 70 | 30.810345 | 58 | inline |
import tensorflow as tf
import keras
import pandas as pd
import numpy as np
from sklearn import linear_model, preprocessing
# Loading data from the hltv api
data = pd.DataFrame.from_dict(hltv.get_results());
# Encoding all non-numeric values
le = preprocessing.LabelEncoder()
for column in data:
if data[column].dtype != "int64":
data[column] = le.fit_transform(list(data[column]));
features = np.array(data.drop(["team1score"], 1).drop(["team2score"], 1));
labels = np.array(data["team1score"] + data["team2score"]);
print(data.head()) | python | 12 | 0.717902 | 74 | 28.105263 | 19 | starcoderdata |
Collections = {};
//CRFs = new Meteor.Collection("CRFs");
//Metadata = new Meteor.Collection("Metadata");
if (Meteor.isClient){
Template.registerHelper("Collections", Collections);
// Collections.Blobs = new FS.Collection("blobs", {
// stores: [Stores.blobs],
// chunkSize: 4 * 1024 * 1024
// });
} | javascript | 6 | 0.664756 | 54 | 23.928571 | 14 | starcoderdata |
public static Class<?> findPackageOrFail(final Class<?> component, final Predicate<Class<?>> tester,
final String api) {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
final String pck = component.getPackage() == null ? null : component.getPackage().getName();
if (pck != null) {
String currentPackage = pck;
do {
try {
final Class<?> pckInfo = loader.loadClass(currentPackage + ".package-info");
if (tester.test(pckInfo)) {
return pckInfo;
}
} catch (final ClassNotFoundException e) {
// no-op
}
final int endPreviousPackage = currentPackage.lastIndexOf('.');
if (endPreviousPackage < 0) { // we don't accept default package since it is not specific enough
break;
}
currentPackage = currentPackage.substring(0, endPreviousPackage);
} while (true);
}
throw new IllegalArgumentException("No @" + api + " for the component " + component
+ ", add it in package-info.java or disable this validation"
+ " (which can have side effects in integrations/designers)");
} | java | 15 | 0.540741 | 112 | 47.25 | 28 | inline |
using System;
using System.Runtime.InteropServices;
namespace RegHook
{
class WinAPI
{
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
internal delegate IntPtr RegOpenKeyEx_Delegate(
IntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
ref IntPtr hkResult);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyEx")]
internal static extern IntPtr RegOpenKeyEx(
IntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
ref IntPtr hkResult);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
internal delegate IntPtr RegCreateKeyEx_Delegate(
IntPtr hKey,
string subKey,
IntPtr Reserved,
string lpClass,
RegOption dwOptions,
RegSAM samDesired,
ref SECURITY_ATTRIBUTES lpSecurityAttributes,
out IntPtr hkResult,
out RegResult lpdwDisposition);
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[Flags]
public enum RegOption
{
NonVolatile = 0x0,
Volatile = 0x1,
CreateLink = 0x2,
BackupRestore = 0x4,
OpenLink = 0x8
}
[Flags]
public enum RegSAM
{
QueryValue = 0x0001,
SetValue = 0x0002,
CreateSubKey = 0x0004,
EnumerateSubKeys = 0x0008,
Notify = 0x0010,
CreateLink = 0x0020,
WOW64_32Key = 0x0200,
WOW64_64Key = 0x0100,
WOW64_Res = 0x0300,
Read = 0x00020019,
Write = 0x00020006,
Execute = 0x00020019,
AllAccess = 0x000f003f
}
public enum RegResult
{
CreatedNewKey = 0x00000001,
OpenedExistingKey = 0x00000002
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegCreateKeyEx")]
internal static extern IntPtr RegCreateKeyEx(
IntPtr hKey,
string subKey,
IntPtr Reserved,
string lpClass,
RegOption dwOptions,
RegSAM samDesired,
ref SECURITY_ATTRIBUTES lpSecurityAttributes,
out IntPtr hkResult,
out RegResult lpdwDisposition);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
internal delegate IntPtr RegCreateKey_Delegate(
IntPtr hKey,
string subKey,
ref IntPtr hkResult);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegCreateKeyA")]
internal static extern IntPtr RegCreateKey(
IntPtr hKey,
string subKey,
ref IntPtr hkResult);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
internal delegate IntPtr RegDeleteKeyEx_Delegate(
IntPtr hKey,
string subKey,
int samDesired,
int Reserved);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegDeleteKeyEx")]
internal static extern IntPtr RegDeleteKeyEx(
IntPtr hKey,
string subKey,
int samDesired,
int Reserved);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
internal delegate IntPtr RegSetValueEx_Delegate(
IntPtr hKey,
[MarshalAs (UnmanagedType.LPStr)]
string lpValueName,
int lpReserved,
Microsoft.Win32.RegistryValueKind type,
IntPtr lpData,
int lpcbData);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
internal delegate IntPtr RegQueryValueEx_Delegate(
IntPtr hKey,
string lpValueName,
int lpReserved,
ref Microsoft.Win32.RegistryValueKind type,
IntPtr lpData,
ref int lpcbData);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "RegQueryValueExW")]
internal static extern IntPtr RegQueryValueExW(
IntPtr hKey,
string lpValueName,
int lpReserved,
ref Microsoft.Win32.RegistryValueKind type,
IntPtr lpData,
ref int lpcbData);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
internal delegate IntPtr RegCloseKey_Delegate(
IntPtr hKey);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegCloseKey")]
internal static extern IntPtr RegCloseKey(
IntPtr hKey);
}
} | c# | 13 | 0.596617 | 116 | 33.545455 | 154 | starcoderdata |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_VR_VR_DEVICE_H
#define DEVICE_VR_VR_DEVICE_H
#include "base/callback.h"
#include "base/macros.h"
#include "device/vr/public/mojom/vr_service.mojom.h"
#include "device/vr/vr_export.h"
namespace device {
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class VrViewerType {
GVR_UNKNOWN = 0,
GVR_CARDBOARD = 1,
GVR_DAYDREAM = 2,
ORIENTATION_SENSOR_DEVICE = 10,
FAKE_DEVICE = 11,
OPENVR_UNKNOWN = 20,
OPENVR_VIVE = 21,
OPENVR_RIFT_CV1 = 22,
VIEWER_TYPE_COUNT,
};
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class XrRuntimeAvailable {
NONE = 0,
OPENVR = 1,
COUNT,
};
const unsigned int VR_DEVICE_LAST_ID = 0xFFFFFFFF;
class VRDeviceEventListener {
public:
virtual ~VRDeviceEventListener() {}
virtual void OnChanged(mojom::VRDisplayInfoPtr vr_device_info) = 0;
virtual void OnExitPresent() = 0;
virtual void OnActivate(mojom::VRDisplayEventReason reason,
base::OnceCallback on_handled) = 0;
virtual void OnDeactivate(mojom::VRDisplayEventReason reason) = 0;
};
// Represents one of the platform's VR devices. Owned by the respective
// VRDeviceProvider.
// TODO(mthiesse, crbug.com/769373): Remove DEVICE_VR_EXPORT.
class DEVICE_VR_EXPORT VRDevice {
public:
virtual ~VRDevice() {}
virtual unsigned int GetId() const = 0;
virtual void PauseTracking() = 0;
virtual void ResumeTracking() = 0;
virtual mojom::VRDisplayInfoPtr GetVRDisplayInfo() = 0;
virtual void SetMagicWindowEnabled(bool enabled) = 0;
virtual void ExitPresent() = 0;
virtual void RequestPresent(
mojom::VRSubmitFrameClientPtr submit_client,
mojom::VRPresentationProviderRequest request,
mojom::VRRequestPresentOptionsPtr present_options,
mojom::VRDisplayHost::RequestPresentCallback callback) = 0;
virtual void SetListeningForActivate(bool is_listening) = 0;
// The fallback device should only be provided in lieu of other devices.
virtual bool IsFallbackDevice() = 0;
// TODO(mthiesse): The browser should handle browser-side exiting of
// presentation before device/ is even aware presentation is being exited.
// Then the browser should call ExitPresent() on Device, which does device/
// exiting of presentation before notifying displays. This is currently messy
// because browser-side notions of presentation are mostly Android-specific.
virtual void OnExitPresent() = 0;
virtual void SetVRDeviceEventListener(VRDeviceEventListener* listener) = 0;
};
} // namespace device
#endif // DEVICE_VR_VR_DEVICE_H | c | 14 | 0.737631 | 79 | 32.372093 | 86 | starcoderdata |
"""Utility functions for clack."""
import os.path
import sys
__all__ = ('local_path', 'string_types')
def local_path(filename):
"""Return an absolute path to a file in the current directory."""
return os.path.join(os.path.dirname(os.path.realpath(__file__)), filename)
if sys.version_info >= (3,):
string_types = (str,)
else:
string_types = (basestring,) | python | 11 | 0.655172 | 78 | 21.176471 | 17 | starcoderdata |
@GetMapping("/games/lobbies/{gameSetUpId}/{playerToken}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public LobbyGetDTO getLobbyInfo(@PathVariable String gameSetUpId, @PathVariable String playerToken) {
//Check that SetupEntity actually exists
stringIsALong(gameSetUpId);
//Try to create active game
Long gsId = parseLong(gameSetUpId);
//add cards to repository
return gameService.getLobbyInfo(gsId, playerToken);
} | java | 7 | 0.684105 | 105 | 44.272727 | 11 | inline |
package com.dmall.mms.service.impl.membersku.handler;
import com.dmall.common.dto.BaseResult;
import com.dmall.common.util.ResultUtil;
import com.dmall.component.web.handler.AbstractCommonHandler;
import com.dmall.mms.feign.SkuServiceFeign;
import com.dmall.mms.generator.dataobject.MemberCollectionSkuDO;
import com.dmall.mms.generator.mapper.MemberCollectionSkuMapper;
import com.dmall.pms.api.dto.sku.response.get.GetSkuResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @description: 收藏sku处理器
* @author: created by hang.yu on 2020/2/29 17:08
*/
@Component
public class MemberCollectionSkuHandler extends AbstractCommonHandler<Long, MemberCollectionSkuDO, Long> {
@Autowired
private SkuServiceFeign skuServiceFeign;
@Autowired
private MemberCollectionSkuMapper memberCollectionSkuMapper;
@Override
public BaseResult processor(Long skuId) {
// 查询sku
BaseResult skuResponse = skuServiceFeign.get(skuId);
if (!skuResponse.getResult()) {
return ResultUtil.fail(skuResponse.getCode(), skuResponse.getMsg());
}
GetSkuResponseDTO data = skuResponse.getData();
MemberCollectionSkuDO memberCollectionSkuDO = new MemberCollectionSkuDO();
memberCollectionSkuDO.setSkuId(skuId);
memberCollectionSkuDO.setProductId(data.getBasicSku().getProductId());
memberCollectionSkuDO.setProductNo(data.getBasicSku().getProductNo());
memberCollectionSkuDO.setSkuNo(data.getBasicSku().getSkuNo());
memberCollectionSkuDO.setPrice(data.getBasicSku().getPrice());
memberCollectionSkuMapper.insert(memberCollectionSkuDO);
return ResultUtil.success(memberCollectionSkuDO.getId());
}
} | java | 12 | 0.765027 | 106 | 39.666667 | 45 | starcoderdata |
/**
* /author
*
* /file CFrameMgr.H
* /brief Keeps track of the room to virtual space transform
*
* Note: this pretty much came from gfxmgr in vrbase
*/
#ifndef CFRAMEMGR_H
#define CFRAMEMGR_H
#include
#include
#include
#include
typedef std::shared_ptr<class CFrameMgr> CFrameMgrRef;
class CFrameMgr : public std::enable_shared_from_this
{
public:
CFrameMgr();
~CFrameMgr();
/** This is the transformation between RoomSpace and VirtualSpace.
Initially, the two spaces are the same. As the user navigates
around VirtualSpace changes, but RoomSpace stays fixed to the
physical Cave, monitor, screen, trackers, etc.. This
transformation is composed of two parts: 1. a uniform scale
factor, 2. a rigid-body CoordinateFrame transformation.
*/
glm::dmat4 getRoomToVirtualSpaceFrame();
glm::dmat4 getVirtualToRoomSpaceFrame();
glm::dmat4 getVirtualToRoomSpaceFrameNoScale();
/// Sets the rigid-body CoordinateFrame transformation between the
/// Room and Virtual spaces.
void setRoomToVirtualSpaceFrame(const glm::dmat4 &roomToVirtual);
void setRoomToVirtualScaleFactor(double scale);
/// Use these to convert from RoomSpace to VirtualSpace, applies a
/// CoordinateFrame transformation as well as a scale.
glm::dvec3 roomPointToVirtualSpace(const glm::dvec3 &v);
glm::dvec3 roomVectorToVirtualSpace(const glm::dvec3 &v);
glm::dvec3 roomNormalToVirtualSpace(const glm::dvec3 &v);
double roomDistanceToVirtualSpace(const double &d);
/// Use these to convert from VirtualSpace to RoomSpace, applies a
/// CoordinateFrame transformation as well as a scale.
glm::dvec3 virtualPointToRoomSpace(const glm::dvec3 &v);
glm::dvec3 virtualVectorToRoomSpace(const glm::dvec3 &v);
glm::dvec3 virtualNormalToRoomSpace(const glm::dvec3 &v);
double virtualDistanceToRoomSpace(const double &d);
glm::dmat4 roomToVirtualSpace(const glm::dmat4 &c);
glm::dmat4 virtualToRoomSpace(const glm::dmat4 &c);
//Transforms the point into frame's object space. Assumes that the rotation matrix is orthonormal.
glm::dvec3 convertPointToObjectSpace(const glm::dmat4 &frame, const glm::dvec3 &v);
glm::dvec3 convertPointToWorldSpace(const glm::dmat4 &frame, const glm::dvec3 &v);
//Transforms the vector into frame's object space. Assumes that the rotation matrix is orthonormal.
glm::dvec3 convertVectorToObjectSpace(const glm::dmat4 &frame, const glm::dvec3 &v);
glm::dvec3 convertVectorToWorldSpace(const glm::dmat4 &frame, const glm::dvec3 &v);
static glm::vec3 vectorMultiply(const glm::mat4 &frame, const glm::vec3 &v);
static glm::vec3 pointMultiply(const glm::mat4 &frame, const glm::vec3 &pt);
static glm::dvec3 vectorMultiply(const glm::dmat4 &frame, const glm::dvec3 &v);
static glm::dvec3 pointMultiply(const glm::dmat4 &frame, const glm::dvec3 &v);
protected:
/// Transformation from RoomSpace to VirtualSpace
glm::dmat4 _roomToVirtual;
double _roomToVirtualScale;
};
#endif | c | 10 | 0.76393 | 101 | 34.694118 | 85 | starcoderdata |
//------------------------------------------------------------------------------
// DAO for accounting purposes
// Require index: `db.accounting.createIndex( { addr: 1, date: 1 } )`
//------------------------------------------------------------------------------
module.exports = class AccountTxDAO {
constructor(execDir, client) {
this.client = client;
this.collection = 'accounting';
}
insert(rec, callback) {
this.client.insert(this.collection, rec, callback);
}
upsert(queryObj, updateObj, callback) {
this.client.upsert(this.collection, queryObj, updateObj, callback);
}
get(wallet, startDate, endDate, callback) {
let queryObj = { addr: wallet, date: { $gte: startDate, $lt: endDate } };
let projectionObj = { _id: 0 };
this.client.queryWithProjection(this.collection, queryObj, projectionObj, callback);
}
} | javascript | 13 | 0.551445 | 88 | 32.307692 | 26 | starcoderdata |
"""
embedeval
~~~~~~~~~
NLP Embedding Evaluation Tool
:copyright: (c) 2019 by
:license: MIT, see LICENSE for more details.
"""
from typing import List, Tuple
from pathlib import Path
import numpy as np
from embedeval.errors import EmbedevalError
from embedeval.embedding import WordEmbedding
class SimpleWordEmbedding(WordEmbedding):
"""Represents a word2vec specific Word Embedding
This Word Embedding should only be used for small datasets
as it's purely implemented in Python and therefore somewhat slow.
"""
def __init__(self, path, word_vectors):
self._path = path
self.word_vectors = word_vectors
@property
def path(self) -> Path:
return self._path
@property
def shape(self) -> Tuple[int, int]:
return (len(self.word_vectors), self.word_vectors.values()[0].size)
def get_words(self) -> List[str]:
return list(self.word_vectors.keys())
def get_word_vector(self, word: str) -> np.array:
return self.word_vectors[word]
def load_embedding(path: Path) -> SimpleWordEmbedding:
"""Load the given Word2Vec Word Embedding
The format for the Embedding expects the n x m matrix size
in the first row of the text file.
The current implementation fails, if that's not the case.
"""
with open(path, "r", encoding="utf-8") as word2vec_file:
header_line = word2vec_file.readline()
try:
word_size, word_vector_size = [int(x) for x in header_line.split()]
except ValueError as exc:
if "not enough" in str(exc):
raise EmbedevalError(
"The given Embedding file doesn't contain the N x M "
"Embedding size in the header line"
)
elif "too many" in str(exc):
raise EmbedevalError(
"The given Embedding file has too many values in the header line"
)
elif "invalid literal" in str(exc):
raise EmbedevalError(
"The header line must contain two integers "
f"for the size but does: '{header_line}'"
)
else:
raise EmbedevalError(
"Unable to extract N x M Embedding size form the header line"
) from exc
word_vectors = {}
for word_number, line in enumerate(word2vec_file):
word, *raw_word_vector = line.split()
word_vector = [np.float32(x) for x in raw_word_vector]
if len(word_vector) != word_vector_size:
raise EmbedevalError(
f"Promised word vector size {word_vector_size} from header "
f"wasn't matched on line {word_number + 2} with a size of {len(word_vector)}"
)
word_vectors[word] = word_vector
if len(word_vectors) < word_size:
raise EmbedevalError(
f"Promised word size {word_size} from header "
f"wasn't matched with a size of {len(word_vectors)}"
)
return SimpleWordEmbedding(path, word_vectors) | python | 17 | 0.588235 | 97 | 30.96 | 100 | starcoderdata |
def init(publicKey, privateKey=None):
"""
Set public and private key
"""
global config
config['publicKey'] = publicKey
config['privateKey'] = privateKey | python | 7 | 0.644068 | 37 | 21.25 | 8 | inline |
def _generate_compose_file(self, command, additional_volumes=None, additional_env_vars=None):
"""Writes a config file describing a training/hosting environment.
This method generates a docker compose configuration file, it has an entry for each container
that will be created (based on self.hosts). it calls
:meth:~sagemaker.local_session.SageMakerContainer._create_docker_host to generate the config
for each individual container.
Args:
command (str): either 'train' or 'serve'
additional_volumes (list): a list of volumes that will be mapped to the containers
additional_env_vars (dict): a dictionary with additional environment variables to be
passed on to the containers.
Returns: (dict) A dictionary representation of the configuration that was written.
"""
boto_session = self.sagemaker_session.boto_session
additional_env_vars = additional_env_vars or []
additional_volumes = additional_volumes or {}
environment = []
optml_dirs = set()
aws_creds = _aws_credentials(boto_session)
if aws_creds is not None:
environment.extend(aws_creds)
environment.extend(additional_env_vars)
if command == 'train':
optml_dirs = {'output', 'input'}
services = {
h: self._create_docker_host(h, environment, optml_dirs,
command, additional_volumes) for h in self.hosts
}
content = {
# Some legacy hosts only support the 2.1 format.
'version': '2.1',
'services': services,
'networks': {
'sagemaker-local': {'name': 'sagemaker-local'}
}
}
docker_compose_path = os.path.join(self.container_root, DOCKER_COMPOSE_FILENAME)
yaml_content = yaml.dump(content, default_flow_style=False)
logger.info('docker compose file: \n{}'.format(yaml_content))
with open(docker_compose_path, 'w') as f:
f.write(yaml_content)
return content | python | 12 | 0.609426 | 101 | 38.703704 | 54 | inline |
@Override
public Set<Object> computeVariableValues(Value value, Stmt stmt) {
if (value instanceof StringConstant) {
return Collections.singleton((Object) ((StringConstant) value).value.intern());
} else if (value instanceof NullConstant) {
return Collections.singleton((Object) "<NULL>");
} else if (value instanceof Local) {
Local local = (Local) value;
ConstraintCollector constraintCollector =
new ConstraintCollector(new ExceptionalUnitGraph(AnalysisParameters.v().getIcfg()
.getMethodOf(stmt).getActiveBody()));
LanguageConstraints.Box lcb = constraintCollector.getConstraintOfAt(local, stmt);
RecursiveDAGSolverVisitorLC dagvlc =
new RecursiveDAGSolverVisitorLC(5, null,
new RecursiveDAGSolverVisitorLC.MethodReturnValueAnalysisInterface() {
@Override
public Set<Object> getMethodReturnValues(Call call) {
return MethodReturnValueManager.v().getMethodReturnValues(call);
}
});
if (dagvlc.solve(lcb)) {
// boolean flag = false;
// if (dagvlc.result.size() == 0 || flag == true) {
// System.out.println("ID: " + lcb.uid);
// // int dbg = 10;
// // while (dbg == 10) {
// System.out.println("Returning " + dagvlc.result);
// System.out.println("Returning.. " + lcb);
// dagvlc.solve(lcb);
// System.out.println("done");
// // }
// }
// System.out.println("Returning " + dagvlc.result);
return new HashSet<Object>(dagvlc.result);
} else {
return Collections.singleton((Object) TOP_VALUE);
}
} else {
return Collections.singleton((Object) TOP_VALUE);
}
} | java | 19 | 0.604155 | 91 | 40.44186 | 43 | inline |
/*
Consider a game where there are n children (numbered 1,2,…,n) in a circle.
During the game, every second child is removed from the circle, until there are no children left.
In which order will the children be removed?
Input
The only input line has an integer n.
Output
Print n integers: the removal order.
Constraints
1=n=2·10^5
Example
Input:
7
Output:
2 4 6 1 5 3 7
*/
#include
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// a is in powers of 2 beginning from 1
// b is offset
int n, a = 1, b = 0;
cin >> n;
while (n > 0)
{
for (int i = 2; i < n + 1; i += 2)
cout << a * i + b << ' ';
// odd number, start next sequence with 1
if (n & 1)
{
cout << a + b << ' ';
b += a;
}
else
b -= a;
// left bit shift, multiply by 2
a <<= 1;
// right bit shift, divide by 2
// every iteration removes half of remainder
n >>= 1;
}
return 0;
} | c++ | 11 | 0.538028 | 98 | 21.680851 | 47 | starcoderdata |
<?php
namespace App\Http\Controllers\API\Param;
use App\Http\Controllers\Controller;
use App\Http\Resources\Params\JabatanResource;
use App\Http\Resources\Params\PendidikanResource;
use App\Http\Resources\Params\StatusKeluargaResource;
use App\Models\Param;
class GetParamController extends Controller
{
public function pendidikan()
{
$param = Param::where([['category_param', 'pendidikan'], ['active', 1]])->orderBy('order', 'ASC')->get();
return PendidikanResource::collection($param);
}
public function jabatan()
{
$param = Param::where([['category_param', 'jabatan'], ['active', 1]])->orderBy('order', 'ASC')->get();
return JabatanResource::collection($param);
}
public function status_keluarga()
{
$param = Param::where([['category_param', 'status_keluarga'], ['active', 1]])->orderBy('order', 'ASC')->get();
return StatusKeluargaResource::collection($param);
}
} | php | 17 | 0.664927 | 118 | 30.933333 | 30 | starcoderdata |
private void ProcessControlFrame(Stream clientStream)
{
switch (CurrentHeader.Flags.Option)
{
case WebSocketFrameOption.Continuation:
case WebSocketFrameOption.Text:
case WebSocketFrameOption.Binary:
throw new WebSocketException("Text, Continuation or Binary are not protocol frames");
case WebSocketFrameOption.ConnectionClose:
this.Close(WebSocketCloseReasons.NormalClose);
break;
case WebSocketFrameOption.Ping:
case WebSocketFrameOption.Pong:
Int32 contentLength = _pongBuffer.Count;
if (CurrentHeader.ContentLength < 125)
contentLength = (Int32)CurrentHeader.ContentLength;
Int32 readed = 0;
while (CurrentHeader.RemainingBytes > 0)
{
readed = clientStream.Read(_pongBuffer.Array, _pongBuffer.Offset + readed, contentLength - readed);
CurrentHeader.DecodeBytes(_pongBuffer.Array, _pongBuffer.Offset, readed);
}
if (CurrentHeader.Flags.Option == WebSocketFrameOption.Pong)
_ping.NotifyPong(_pongBuffer);
else // pong frames echo what was 'pinged'
this.WriteInternal(_pongBuffer, readed, true, false, WebSocketFrameOption.Pong, WebSocketExtensionFlags.None);
break;
default: throw new WebSocketException("Unexpected header option '" + CurrentHeader.Flags.Option.ToString() + "'");
}
} | c# | 17 | 0.555556 | 134 | 50.117647 | 34 | inline |
import {
TOGGLE_MODE_EVENT
} from '../../util/EventHelper';
const VERY_HIGH_PRIORITY = 50000;
export default function PreserveElementColors(
eventBus, elementRegistry, graphicsFactory) {
this._elementRegistry = elementRegistry;
this._graphicsFactory = graphicsFactory;
this._elementColors = {};
eventBus.on(TOGGLE_MODE_EVENT, VERY_HIGH_PRIORITY, event => {
const active = event.active;
if (active) {
this.preserveColors();
} else {
this.resetColors();
}
});
}
PreserveElementColors.prototype.preserveColors = function() {
this._elementRegistry.forEach(element => {
this._elementColors[element.id] = {
stroke: element.businessObject.di.get('stroke'),
fill: element.businessObject.di.get('fill')
};
this.setColor(element, '#000', '#fff');
});
};
PreserveElementColors.prototype.resetColors = function() {
const elementColors = this._elementColors;
this._elementRegistry.forEach(element => {
if (elementColors[element.id]) {
this.setColor(element, elementColors[element.id].stroke, elementColors[element.id].fill);
}
});
this._elementColors = {};
};
PreserveElementColors.prototype.setColor = function(element, stroke, fill) {
const businessObject = element.businessObject;
businessObject.di.set('stroke', stroke);
businessObject.di.set('fill', fill);
const gfx = this._elementRegistry.getGraphics(element);
const type = element.waypoints ? 'connection' : 'shape';
this._graphicsFactory.update(type, element, gfx);
};
PreserveElementColors.$inject = [
'eventBus',
'elementRegistry',
'graphicsFactory'
]; | javascript | 18 | 0.695092 | 95 | 23.343284 | 67 | starcoderdata |
import React from 'react'
import { Space, Typography } from 'antd'
import { FacebookOutlined, ChromeOutlined } from '@ant-design/icons'
import logo from '../assets/logo.svg'
const { Text } = Typography
const Footer = () => {
return (
<div className={'footer-container'}>
<img width={164} height={50} src={logo} alt='Logo SKOB'/>
<Space direction='vertical' style={{ justifyContent: 'flex-end' }}>
<Text italic>Follow:
<a href='https://www.facebook.com/skobroudnice' target='_blank' rel="noreferrer">
<FacebookOutlined style={{ fontSize: '1.5rem' }} />
<a href='https://obroudnice.cz/' target='_blank' rel="noreferrer">
<ChromeOutlined style={{ fontSize: '1.5rem' }} />
<Text italic>Design made by © <a href='mailto:
)
}
export default Footer | javascript | 11 | 0.527159 | 101 | 36.466667 | 30 | starcoderdata |
const { Node, Stack } = require('../stackLL')
describe('Stack > Using Linked List', () => {
test('should create new node with correct default reference', () => {
let element1 = new Node()
expect(element1.data).toBeNull()
expect(element1.next).toBeNull()
let element2 = new Node(10)
expect(element2.data).toBe(10)
expect(element2.next).toBeNull()
})
test('should add a new node to the beginning of the stack', () => {
const stk = new Stack()
stk.push(10)
expect(stk.size()).toBe(1)
expect(stk.first.data).toBe(10)
expect(stk.first.next).toBeNull()
expect(stk.last.data).toBe(10)
expect(stk.last.next).toBeNull()
stk.push(20)
expect(stk.size()).toBe(2)
expect(stk.first.data).toBe(20)
expect(stk.first.next.data).toBe(10)
expect(stk.first.next.next).toBeNull()
expect(stk.last.data).toBe(10)
expect(stk.last.next).toBeNull()
})
test('should return the element which is popped from the stack', () => {
const stk = new Stack()
stk.push(10)
stk.push(20)
stk.push(30)
expect(stk.pop().data).toBe(30)
expect(stk.pop().data).toBe(20)
expect(stk.pop().data).toBe(10)
expect(stk.last).toBeNull() // after above step > first === last
try {
stk.pop()
} catch(error) {
expect(error).toBeInstanceOf(Error)
expect(error).toHaveProperty('message', 'Stack is empty, nothing to pop')
}
})
}) | javascript | 19 | 0.625784 | 79 | 27.7 | 50 | starcoderdata |
/*
Copyright 2021 The KodeRover Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package reaper
import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/koderover/zadig/pkg/microservice/reaper/internal/s3"
"github.com/koderover/zadig/pkg/setting"
"github.com/koderover/zadig/pkg/tool/log"
)
// 上传用户文件到s3
func (r *Reaper) archiveS3Files() (err error) {
if r.Ctx.FileArchiveCtx != nil && r.Ctx.StorageURI != "" {
var store *s3.S3
if store, err = s3.NewS3StorageFromEncryptedURI(r.Ctx.StorageURI); err != nil {
log.Errorf("failed to create s3 storage %s", r.Ctx.StorageURI)
return
}
if store.Subfolder != "" {
store.Subfolder = fmt.Sprintf("%s/%s/%d/%s", store.Subfolder, r.Ctx.PipelineName, r.Ctx.TaskID, "file")
} else {
store.Subfolder = fmt.Sprintf("%s/%d/%s", r.Ctx.PipelineName, r.Ctx.TaskID, "file")
}
src := filepath.Join(r.ActiveWorkspace, r.Ctx.FileArchiveCtx.FileLocation, r.Ctx.FileArchiveCtx.FileName)
err = s3.Upload(
context.Background(),
store,
src,
r.Ctx.FileArchiveCtx.FileName,
)
if err != nil {
log.Errorf("failed to upload package %s, %v", src, err)
return err
}
} else {
return r.archiveTestFiles()
}
return nil
}
func (r *Reaper) archiveTestFiles() error {
if r.Ctx.Archive == nil || r.Ctx.StorageURI == "" {
return nil
}
store, err := s3.NewS3StorageFromEncryptedURI(r.Ctx.StorageURI)
if err != nil {
log.Errorf("failed to create s3 storage %s, err: %s", r.Ctx.StorageURI, err)
return err
}
fileType := "test"
if strings.Contains(r.Ctx.Archive.File, ".tar.gz") {
fileType = "file"
}
if store.Subfolder != "" {
store.Subfolder = fmt.Sprintf("%s/%s/%d/%s", store.Subfolder, r.Ctx.PipelineName, r.Ctx.TaskID, fileType)
} else {
store.Subfolder = fmt.Sprintf("%s/%d/%s", r.Ctx.PipelineName, r.Ctx.TaskID, fileType)
}
filePath := path.Join(r.Ctx.Archive.Dir, r.Ctx.Archive.File)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
// no file found, skipped
//log.Warningf("upload filepath not exist")
return nil
}
err = s3.Upload(context.Background(), store, filePath, r.Ctx.Archive.File)
if err != nil {
log.Errorf("failed to upload package %s, %v", filePath, err)
return err
}
return nil
}
func (r *Reaper) archiveHTMLTestReportFile() error {
// 仅功能测试有HTML测试结果报告
if r.Ctx.TestType != setting.FunctionTest {
return nil
}
if r.Ctx.Archive == nil || r.Ctx.StorageURI == "" {
return nil
}
store, err := s3.NewS3StorageFromEncryptedURI(r.Ctx.StorageURI)
if err != nil {
log.Errorf("failed to create s3 storage %s, err: %s", r.Ctx.StorageURI, err)
return err
}
if store.Subfolder != "" {
store.Subfolder = fmt.Sprintf("%s/%s/%d/%s", store.Subfolder, r.Ctx.PipelineName, r.Ctx.TaskID, "test")
} else {
store.Subfolder = fmt.Sprintf("%s/%d/%s", r.Ctx.PipelineName, r.Ctx.TaskID, "test")
}
filePath := r.Ctx.GinkgoTest.TestReportPath
if filePath == "" {
return nil
}
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return nil
}
fileName := filepath.Base(r.Ctx.Archive.TestReportFile)
err = s3.Upload(context.Background(), store, filePath, fileName)
if err != nil {
log.Errorf("failed to upload package %s, %s", filePath, err)
return err
}
return nil
} | go | 13 | 0.684295 | 107 | 25.181818 | 143 | starcoderdata |
LRESULT CFFindDialog::OnInitDialog(UINT msg, WPARAM wparam, LPARAM lparam,
BOOL& handled) {
// Init() must be called before Create() or DoModal()!
DCHECK(automation_client_.get());
InstallMessageHook();
SendDlgItemMessage(IDC_FIND_TEXT, EM_EXLIMITTEXT, 0, kMaxFindChars);
BOOL result = CheckRadioButton(IDC_DIRECTION_DOWN, IDC_DIRECTION_UP,
IDC_DIRECTION_DOWN);
HWND text_field = GetDlgItem(IDC_FIND_TEXT);
::SetFocus(text_field);
return FALSE; // we set the focus ourselves.
} | c++ | 8 | 0.646018 | 74 | 36.733333 | 15 | inline |
package com.dcits.dcwlt.pay.batch.service;
/**
* Created by yangjld on 2021/3/12 0012.
*/
public interface IReportDataService {
void statistics(String reportDate);
} | java | 13 | 0.772727 | 111 | 27.6 | 10 | starcoderdata |
from datetime import datetime
from django.contrib.auth import get_user_model
from django.conf import settings
# 이메일 전송 관련 Imports
from django.core.mail import EmailMessage
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
# Rest Framework Serializers
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer
from .email.token import account_activation_token
from .email import text
from .models import Profile
class CustomUserSerializer(serializers.ModelSerializer):
""" 커스텀 유저 모델을 직렬화(Serialize)한다. """
# 기존 Model 필드를 덮어씌워 새롭게 정의한다.
password = serializers.CharField(write_only=True,
min_length=8,
style={'input_type': 'password'})
# Password 확인을 위해 새로운 필드를 하나 생성한다.
password_confirm = serializers.CharField(write_only=True,
style={'input_type': 'password'})
# 프로필 모델을 문자열 형태로 받아온다.
# profile = serializers.StringRelatedField()
class Meta:
model = get_user_model()
# Serializing 과정에서 'Validate'할 필드의 목록...이들은 'validated_data'가 된다.
fields = ('id', 'email', 'name', 'birthday','school', 'password', 'password_confirm', 'is_student')
read_only_fields = ('id', )
# 완전한 객체 인스턴스를 생성할 때 호출되는 create 메소드를 오버라이드한다.
def create(self, validated_data):
""" 새로운 유저를 생성하고 반환한다. (serializer.is_valid() 호출 시 실행된다) """
# CustomUserManager 클래스에 정의한 create_user 메소드를 호출하여 비밀번호를 암호화하고 CustomUser 생성.
user = get_user_model().objects.create_user(
email=validated_data['email'],
name=validated_data['name'],
birthday=validated_data['birthday'],
school=validated_data['school'],
password=validated_data['password'],
is_student=validated_data['is_student'],
# password_confirm 필드는 필요하지 않으므로, **validated_data 사용하지 않는다.
)
user.is_active = False # 이메일 인증을 하지 않은 경우, is_active 값을 False
user.save() # 변경 내용을 DB 저장
# 인증 토큰과 관련된 변수
domain = # 본인이 사용할 front end URL 입력
uidb64 = urlsafe_base64_encode(force_bytes(user.id))
token = account_activation_token.make_token(user)
# 이메일 전송과 관련된 변수
mail_subject = '[Your class] 회원가입 인증 메일입니다.'
mail_content = text.message(domain, uidb64, token)
to_email = user.email
email = EmailMessage(mail_subject, # 이메일 제목
mail_content, # 이메일 내용
to=[' to_email, ] # 이메일 수신자
)
email.send() # 이메일 전송
return user
# 'set_password' 메소드가 호출되는 것을 확실히 하기위해, update 메소드도 오버라이드한다.
def update(self, instance, validated_data):
""" 비밀번호를 set_password 메소드를 통해 설정하고 유저 정보를 업데이트 및 반환한다. """
password = validated_data.pop('password', None) # validated_data 딕셔너리에서 password 필드를 제거한다.
user = super().update(instance, validated_data) # super()를 통해 ModelSerializer 클래스의 update 메소드 호출.
if password:
user.set_password(password)
user.save()
return user
def validate_birthday(self, value):
""" birthday 필드에 대한 Validation 과정 """
today = datetime.now().date()
if (today - value).days < 2555:
raise serializers.ValidationError("만 7세 이하는 가입할 수 없습니다.")
return value
def validate(self, data):
""" password, password_confirm 필드에 대한 Validation 과정 """
if data['password'] != data['password_confirm']:
raise serializers.ValidationError("두 비밀번호가 일치하지 않습니다.")
return data
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
""" 토큰 획득 시 만료시간을 추가하기 위한 시리얼라이저 """
def validate(self, attrs):
data = super().validate(attrs)
data['access_expiration_date'] = datetime.now() + settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']
data['refresh_expiration_date'] = datetime.now() + settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME']
return data
class CustomTokenRefreshSerializer(TokenRefreshSerializer):
""" 토큰 재발급 시 만료시간을 추가하기 위한 시리얼라이저 """
def validate(self, attrs):
data = super().validate(attrs)
data['access_expiration_date'] = datetime.now() + settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']
return data
class ProfileSerializer(serializers.ModelSerializer):
user = CustomUserSerializer(read_only=True)
avatar = serializers.ImageField(read_only=True, use_url=True)
class Meta:
model = Profile
fields = ('id', 'user', 'nickname', 'avatar', )
read_only_fields = ('id',)
def validate_nickname(self, value):
if len(value) > 20:
raise serializers.ValidationError('닉네임은 20글자를 넘을 수 없습니다.')
return value
class ProfileAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('nickname', 'avatar',)
read_only_fields = ('nickname', ) | python | 13 | 0.625098 | 107 | 35.748201 | 139 | starcoderdata |
function () {
//inizializzo proprietà dell'oggetto che contiene una lista messaggi fake da dove pescare messaggi random
this.initializeSampleMessage();
//creo le conversazioni fake
this.createFakeThreads();
//carico le conversazioni
this.loadThreads();
//rimuovo splash screen
this.discardSplashScreen();
//collego gli handler
this.attachHandlers();
} | javascript | 7 | 0.755376 | 107 | 30.083333 | 12 | inline |
package subscriber
import (
"fmt"
"io"
"github.com/husainaloos/event-bus/message"
)
// WriterSubscriber Demonistration subscriber
type WriterSubscriber struct {
id string
doneChannel chan (message.Message)
isRunning bool
writer io.Writer
}
// NewWriterSubscriber constructor
func NewWriterSubscriber(ID string, w io.Writer) *WriterSubscriber {
return &WriterSubscriber{
id: ID,
doneChannel: make(chan message.Message),
isRunning: false,
writer: w,
}
}
// ID gets the ID
func (s WriterSubscriber) ID() string {
return s.id
}
// Subscribe Get the message and sends it
func (s *WriterSubscriber) Subscribe(m message.Message) {
if !s.isRunning {
return
}
fmt.Fprintf(s.writer, "subscriber ID: %s received message: %v\n", s.id, m)
//s.doneChannel <- m
}
// Run starts the subscriber
func (s *WriterSubscriber) Run() error {
s.isRunning = true
return nil
}
// GetDoneChannel returns the channel that will be filled with processed messages
func (s WriterSubscriber) GetDoneChannel() chan (message.Message) {
return s.doneChannel
}
// Stop stops the subscriber
func (s *WriterSubscriber) Stop() error {
s.isRunning = false
return nil
} | go | 14 | 0.719355 | 81 | 20.016949 | 59 | starcoderdata |
(function($){
$(function(){
$.lazyLoadXT.onload = function() {
var $el = $(this);
$el
.removeClass('lazy-hidden')
.addClass('animated ' + $el.attr('data-effect'));
};
$('.button-collapse').sideNav();
$('.carousel.carousel-slider').carousel({full_width: true});
$('.slider').slider();
$('select').material_select();
$('.modal').modal();
$('.parallax').parallax();
$('.scrollspy').scrollSpy();
$('ul.tabs').tabs();
$(document).ready(function(){
$('.target').pushpin({
top: 500,
bottom: 2000,
offset: 70
});
});
});
})(jQuery); // end of jQuery name space | javascript | 22 | 0.507508 | 64 | 25.68 | 25 | starcoderdata |
const showTip = (msg, { type = 'ok', delay = 1500, cb = () => {} } = {}) => {
const klas = `${type}-toast msg`
const _toast = document.getElementById('global-toast')
const _msg = _toast.getElementsByClassName('msg')[0]
_toast.addEventListener('transitionend', () => {
if (!_toast.classList.contains('show')) {
_msg.textContent = ''
cb()
}
}, false)
if (_toast && _msg) {
_msg.textContent = msg
_msg.className = klas
_toast.className = 'show'
setTimeout(() => {
_toast.className = ''
}, delay)
}
}
export default showTip | javascript | 15 | 0.580696 | 77 | 25.333333 | 24 | starcoderdata |
import Vue from 'vue';
import VueRouter from 'vue-router';
import Vuex from 'vuex';
// components
import Home from './components/Home.vue';
import NewsAndUpdate from './components/NewsAndUpdate.vue';
import Register from './components/Register.vue';
import RegisterSuccess from './components/Register/Successful.vue';
import LeaveMessage from './components/LeaveMessage.vue';
import ReceivedMessage from './components/LeaveMessage/ReceivedMessage.vue';
import TermsAndConditions from './components/TermsAndConditions.vue';
// use vuex and vue-router
Vue.use(VueRouter, Vuex);
// set new vue router instance
export default new VueRouter({
routes: [
// public page
{ path: '/', component: Home, name: 'home' },
{ path: '/news', component: NewsAndUpdate, name: 'news' },
{ path: '/register', component: Register, name: 'register' },
{ path: '/register-succes', component: RegisterSuccess, name: 'register-success' },
{ path: '/leave-message', component: LeaveMessage, name: 'message' },
{ path: '/message-received', component: ReceivedMessage, name: 'received-message' },
{ path: '/terms-and-conditions', component: TermsAndConditions, name: 'terms-and-conditions' },
]
}) | javascript | 13 | 0.700999 | 103 | 39.65625 | 32 | starcoderdata |
private void handleRegion(TaggedMap region) {
if (region != null && !region.isEmpty()) {
try {
// postpone writing out LAT_LON_BOX element until there is a child element
// likewise don't write Region element unless we have LAT_LON_BOX or Lod
LinkedList<String> waitingList = new LinkedList<String>();
waitingList.add(REGION);
waitingList.add(LAT_LON_ALT_BOX);
handleTaggedElement(NORTH, region, waitingList);
handleTaggedElement(SOUTH, region, waitingList);
// handle east/west as special case
// +180 might be normalized to -180.
// If east = -180 and west >=0 then Google Earth invalidate the Region and never be active.
Double east = region.getDoubleValue(EAST);
Double west = region.getDoubleValue(WEST);
if (east != null && west != null && west >= 0 && Double.compare(east, -180) == 0) {
while (!waitingList.isEmpty()) {
writer.writeStartElement(waitingList.removeFirst());
}
handleSimpleElement(EAST, "180");
handleSimpleElement(WEST, formatDouble(west));
} else {
handleTaggedElement(EAST, region, waitingList);
handleTaggedElement(WEST, region, waitingList);
}
handleTaggedElement(MIN_ALTITUDE, region, waitingList);
handleTaggedElement(MAX_ALTITUDE, region, waitingList);
// if altitudeMode is invalid then it will be omitted
AltitudeModeEnumType altMode = AltitudeModeEnumType.getNormalizedMode(region.get(ALTITUDE_MODE));
if (altMode != null) {
/*
if (!waitingList.isEmpty()) {
writer.writeStartElement(REGION);
writer.writeStartElement(LAT_LON_ALT_BOX);
waitingList.clear();
}
handleAltitudeMode(altMode);
*/
if (waitingList.isEmpty()) {
handleAltitudeMode(altMode);
}
// otherwise don't have LatLonAltBox so AltitudeMode has no meaning
}
if (waitingList.isEmpty()) {
writer.writeEndElement(); // end LatLonAltBox
} else {
waitingList.remove(1); // remove LatLonAltBox from consideration
// we still have Region in waiting list
}
// next check Lod
waitingList.add(LOD);
handleTaggedElement(MIN_LOD_PIXELS, region, waitingList);
handleTaggedElement(MAX_LOD_PIXELS, region, waitingList);
handleTaggedElement(MIN_FADE_EXTENT, region, waitingList);
handleTaggedElement(MAX_FADE_EXTENT, region, waitingList);
if (waitingList.isEmpty())
writer.writeEndElement(); // end Lod
//if (!waitingList.isEmpty()) System.out.println("XXX: *NO* LOD in region..."); // debug
//else System.out.println("XXX: got LOD in region..."); // debug
// if have 2 elements in map then have neither Lod nor Region to end
// if have 0 or 1 {Lod} elements in list then we need to end of Region
if (waitingList.size() < 2)
writer.writeEndElement(); // end Region
} catch (XMLStreamException e) {
throw new IllegalStateException(e);
}
}
} | java | 16 | 0.551128 | 113 | 51.794118 | 68 | inline |
bool apBreakpointHitEvent::writeSelfIntoChannel(osChannel& ipcChannel) const
{
bool retVal = true;
// Write the break reason:
ipcChannel << (gtInt32)_breakReason;
bool isFunctionCallPresent = (_aptrBreakedOnFunctionCall.pointedObject() != NULL);
ipcChannel << isFunctionCallPresent;
if (isFunctionCallPresent)
{
// Write the broken-on function:
retVal = _aptrBreakedOnFunctionCall->writeSelfIntoChannel(ipcChannel);
}
// Write the break address:
ipcChannel << (gtUInt64)_breakPointAddress;
// Write the error code:
ipcChannel << (gtInt32)_openGLErrorCode;
// Call my parent class's version of this function:
retVal = apEvent::writeSelfIntoChannel(ipcChannel) && retVal;
return retVal;
} | c++ | 9 | 0.7 | 86 | 26.535714 | 28 | inline |
package com.planet_ink.coffee_mud.core.collections;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.NoSuchElementException;
/*
Copyright 2000-2014
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class MultiEnumeration implements Enumeration
{
private final LinkedList enums=new LinkedList
private volatile Enumeration enumer=null;
public static interface MultiEnumeratorBuilder
{
public MultiEnumeration getList();
}
public MultiEnumeration(Enumeration esets)
{
if((esets!=null)&&(esets.length>0))
for(final Enumeration E : esets)
if(E!=null)
enums.add(E);
}
public MultiEnumeration(Collection esets)
{
if(esets!=null)
enums.addAll(esets);
}
public MultiEnumeration(Enumeration eset)
{
enums.add(eset);
}
public void addEnumeration(Enumeration set)
{
if(set != null)
enums.add(set);
}
@Override
public boolean hasMoreElements()
{
while((enumer==null)||(!enumer.hasMoreElements()))
{
if(enums.size()==0)
return false;
enumer=enums.removeFirst();
}
return enumer.hasMoreElements();
}
@Override
public K nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return enumer.nextElement();
}
} | java | 12 | 0.736294 | 81 | 23 | 76 | starcoderdata |
import ApiResponse from '/Core/Api/ApiResponse';
import Registry from '/Core/Registry';
function handleResponse(response) {
// Log Http responses to console if developerMode is enabled
return Registry.getStore('Core.Layout.AppStore').getData().then(data => {
if(data.developerMode){
console.log(response)
}
return new ApiResponse(response);
});
}
class ApiService {
constructor(url) {
this.url = url.toLowerCase();
}
crudList(filters, sorters, limit, page) {
return Http.get(_apiUrl + this.url).then(handleResponse).catch(handleResponse);
}
crudCreate(data) {
return Http.post(_apiUrl + this.url, data).then(handleResponse).catch(handleResponse);
}
crudDelete(id) {
return Http.delete(_apiUrl + this.url + '/' + id).then(handleResponse).catch(handleResponse);
}
crudRestore(id) {
return Http.post(_apiUrl + this.url + '/restore/'+id).then(handleResponse).catch(handleResponse);
}
crudReplace() {
}
crudGet(id) {
return Http.get(_apiUrl + this.url + '/' + id).then(handleResponse).catch(handleResponse);
}
crudUpdate(action, data, config = {}) {
return Http.patch(_apiUrl + this.url + '/' + action, data, config).then(handleResponse).catch(handleResponse);
}
get(action, data, config = {}) {
return Http.get(_apiUrl + this.url + '/' + action, data, config).then(handleResponse).catch(handleResponse);
}
delete(action, config = {}) {
return Http.delete(_apiUrl + this.url + '/' + action, config).then(handleResponse).catch(handleResponse);
}
head(action, config = {}) {
return Http.head(_apiUrl + this.url + '/' + action, config).then(handleResponse).catch(handleResponse);
}
post(action, data = {}, config = {}) {
return Http.post(_apiUrl + this.url + '/' + action, data, config).then(handleResponse).catch(handleResponse);
}
put(action, data = {}, config = {}) {
return Http.put(_apiUrl + this.url + '/' + action, data, config).then(handleResponse).catch(handleResponse);
}
patch(action, data = {}, config = {}) {
return Http.patch(_apiUrl + this.url + '/' + action, data, config).then(handleResponse).catch(handleResponse);
}
}
export default ApiService; | javascript | 13 | 0.685636 | 112 | 28.459459 | 74 | starcoderdata |
// SPDX-License-Identifier: GPL-2.0+
/* NetworkManager Applet -- allow user control over networking
*
*
*
* (C) Copyright 2007 - 2012 Red Hat, Inc.
*/
#ifndef NMA_WIRELESS_DIALOG_H
#define NMA_WIRELESS_DIALOG_H
#include
#include
#include
#include
#include
#include
#include
#include
#define NMA_TYPE_WIRELESS_DIALOG (nma_wireless_dialog_get_type ())
#define NMA_WIRELESS_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NMA_TYPE_WIRELESS_DIALOG, NMAWirelessDialog))
#define NMA_WIRELESS_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NMA_TYPE_WIRELESS_DIALOG, NMAWirelessDialogClass))
#define NMA_IS_WIRELESS_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NMA_TYPE_WIRELESS_DIALOG))
#define NMA_IS_WIRELESS_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NMA_TYPE_WIRELESS_DIALOG))
#define NMA_WIRELESS_DIALOG_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NMA_TYPE_WIRELESS_DIALOG, NMAWirelessDialogClass))
typedef struct {
GObject parent;
} NMAWirelessDialog;
typedef struct {
GObjectClass parent;
} NMAWirelessDialogClass;
GLIB_DEPRECATED_FOR(nma_wifi_dialog_get_type)
GType nma_wireless_dialog_get_type (void);
GLIB_DEPRECATED_FOR(nma_wifi_dialog_new)
GtkWidget *nma_wireless_dialog_new (NMClient *client,
NMRemoteSettings *settings,
NMConnection *connection,
NMDevice *device,
NMAccessPoint *ap,
gboolean secrets_only);
GLIB_DEPRECATED_FOR(nma_wifi_dialog_new_for_other)
GtkWidget *nma_wireless_dialog_new_for_other (NMClient *client,
NMRemoteSettings *settings);
GLIB_DEPRECATED_FOR(nma_wifi_dialog_new_for_create)
GtkWidget *nma_wireless_dialog_new_for_create (NMClient *client,
NMRemoteSettings *settings);
GLIB_DEPRECATED_FOR(nma_wifi_dialog_get_connection)
NMConnection * nma_wireless_dialog_get_connection (NMAWirelessDialog *dialog,
NMDevice **device,
NMAccessPoint **ap);
#endif /* NMA_WIRELESS_DIALOG_H */ | c | 8 | 0.660922 | 129 | 36.435484 | 62 | starcoderdata |
<?php
class homeController extends controller {
public function index($parametro = null) {
$this->loadView('', array(), false);
}
} | php | 10 | 0.628378 | 43 | 11.333333 | 12 | starcoderdata |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\MaterialSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="material-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'material_id') ?>
<?= $form->field($model, 'mat_identification') ?>
<?= $form->field($model, 'mat_description_pt') ?>
<?= $form->field($model, 'mat_description_en') ?>
<?= $form->field($model, 'uom_id') ?>
<?php // echo $form->field($model, 'mat_list_id') ?>
<?php // echo $form->field($model, 'mat_vpn') ?>
<?php // echo $form->field($model, 'mat_manufacturer') ?>
<?php // echo $form->field($model, 'mat_mpn') ?>
<?php // echo $form->field($model, 'mat_sn') ?>
<?php // echo $form->field($model, 'materialtype_id') ?>
<?php // echo $form->field($model, 'mat_bin') ?>
<?php // echo $form->field($model, 'mat_inventory_ref') ?>
<?php // echo $form->field($model, 'equip_id') ?>
<?php // echo $form->field($model, 'mat_dimenssion') ?>
<?php // echo $form->field($model, 'mat_unit_price') ?>
<?php // echo $form->field($model, 'mat_weight') ?>
<?php // echo $form->field($model, 'owner_id') ?>
<?php // echo $form->field($model, 'mat_picture') ?>
<?php // echo $form->field($model, 'mat_xdate1') ?>
<?php // echo $form->field($model, 'mat_xdate2') ?>
<?php // echo $form->field($model, 'mat_xdate3') ?>
<?php // echo $form->field($model, 'mat_xboolean1')->checkbox() ?>
<?php // echo $form->field($model, 'mat_xboolean2')->checkbox() ?>
<?php // echo $form->field($model, 'mat_xboolean3')->checkbox() ?>
<?php // echo $form->field($model, 'mat_xboolean4')->checkbox() ?>
<?php // echo $form->field($model, 'mat_xboolean5')->checkbox() ?>
<?php // echo $form->field($model, 'mat_xvarchar1') ?>
<?php // echo $form->field($model, 'mat_xvarchar2') ?>
<?php // echo $form->field($model, 'mat_xvarchar3') ?>
<?php // echo $form->field($model, 'mat_xinterger1') ?>
<?php // echo $form->field($model, 'mat_xinterger2') ?>
<?php // echo $form->field($model, 'mat_xinterger3') ?>
<?php // echo $form->field($model, 'vendor_id') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
<?php ActiveForm::end(); ?> | php | 11 | 0.541195 | 75 | 26.537634 | 93 | starcoderdata |
# minimalna vrijednost
O_MIN = [
38,
115,
46,
100,
38,
23,
8,
16,
]
# maksimalna vrijednost
O_MAX = [
78,
240,
96,
210,
82,
50,
18,
36,
]
# srednja vrijdnost
O_Z = [
58,
177,
71,
155,
60,
36,
13,
26,
]
# potrosnja
P = [
35,
105,
42,
91,
35,
21,
7,
14,
]
GROUP_O_minus = 0
GROUP_O_plus = 1
GROUP_A_minus = 2
GROUP_A_plus = 3
GROUP_B_minus = 4
GROUP_B_plus = 5
GROUP_AB_minus = 4
GROUP_AB_plus = 5 | python | 4 | 0.449905 | 23 | 8.280702 | 57 | starcoderdata |
void HumdrumFileBase::prepare_address(struct sockaddr_in *address,
const string& hostname, unsigned short int port) {
memset(address, 0, sizeof(struct sockaddr_in));
struct hostent *host_entry;
host_entry = gethostbyname(hostname.c_str());
if (host_entry == NULL) {
cerr << "Could not find address for " << hostname << endl;
exit(1);
}
// copy the address to the sockaddr_in struct.
memcpy(&address->sin_addr.s_addr, host_entry->h_addr_list[0],
host_entry->h_length);
// set the family type (PF_INET)
address->sin_family = host_entry->h_addrtype;
address->sin_port = htons(port);
} | c++ | 10 | 0.693709 | 66 | 29.25 | 20 | inline |
namespace BookmarksAPI.Services
{
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BookmarksAPI.Exceptions;
using BookmarksAPI.Services.Interfaces;
using DataWorkShop;
using DataWorkShop.Entities;
using DataWorkShop.Entities.Structures;
using EEFApps.ApiInstructions.DataInstructions.Instructions;
using EEFApps.ApiInstructions.DataInstructions.Instructions.Structures;
public class UserService : IUserService
{
private BookmarksDbContext context;
public UserService(BookmarksDbContext context)
{
this.context = context;
}
internal static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
public async Task GetById(string id)
{
var dbUser = await new ReceivingInstruction<User, string>(
this.context,
new ReceivingInstructionParams
{
Id = id
}
).Execute();
return dbUser;
}
public async Task Authenticate(string userName, string password)
{
if (string.IsNullOrWhiteSpace(userName))
{
throw new CustomException("User name is required");
}
if (string.IsNullOrWhiteSpace(password))
{
throw new CustomException("Password is required");
}
var dbUser = (await new ReceivingListInstruction new ListInstructionParams
{
FilterExpr = usr => usr.UserName == userName && usr.Status == UserStatusType.Active
}).Execute()).FirstOrDefault();
// Check user existence
if (dbUser == null)
{
throw new CustomException("Incorrect user name or password");
}
// Check password correctness
if (!VerifyPasswordHash(password, dbUser.PasswordHash, dbUser.PasswordSalt))
{
throw new CustomException("Incorrect user name or password");
}
return dbUser;
}
public async Task Create(User newUser, string password)
{
if (string.IsNullOrWhiteSpace(newUser.UserName))
{
throw new CustomException("User name is required");
}
if (string.IsNullOrWhiteSpace(password))
{
throw new CustomException("Password is required");
}
var numberOfExistingUsers = await new ReceivingCountedListInstruction new ListInstructionParams
{
FilterExpr = usr => usr.UserName == newUser.UserName
}).Execute();
if (numberOfExistingUsers > 0)
{
throw new CustomException("User name \"" + newUser.UserName + "\" is already taken");
}
byte[] passwordHash, passwordSalt;
UserService.CreatePasswordHash(password, out passwordHash, out passwordSalt);
newUser.PasswordHash = passwordHash;
newUser.PasswordSalt = passwordSalt;
newUser.Status = UserStatusType.Active;
var createdUser = await new CreationInstruction newUser).Execute();
// TODO: add registration confirmation
return createdUser;
}
private bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
{
if (storedHash.Length != 64)
{
throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
}
if (storedSalt.Length != 128)
{
throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
}
using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
{
var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedHash.Length; i++)
{
if (computedHash[i] != storedHash[i])
{
return false;
}
}
}
return true;
}
}
} | c# | 25 | 0.565606 | 133 | 33.35 | 140 | starcoderdata |
using System;
using System.Diagnostics.CodeAnalysis;
using Moq.Language;
using Moq.Language.Flow;
namespace Moq
{
internal sealed partial class MethodCallReturn<TMock, TResult>
{
public IVerifies Raises eventExpression, Func<T, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2>(Action eventExpression, Func<T1, T2, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2>(Func<T1, T2, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2>(Action<T1, T2> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3>(Action eventExpression, Func<T1, T2, T3, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3>(Func<T1, T2, T3, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3>(Action<T1, T2, T3> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4>(Action eventExpression, Func<T1, T2, T3, T4, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4>(Func<T1, T2, T3, T4, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4>(Action<T1, T2, T3, T4> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5>(Action eventExpression, Func<T1, T2, T3, T4, T5, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6>(Action<T1, T2, T3, T4, T5, T6> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7>(Func<T1, T2, T3, T4, T5, T6, T7, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7>(Action<T1, T2, T3, T4, T5, T6, T7> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8>(Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T1, T2, T3, T4, T5, T6, T7, T8> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> callback)
{
base.Callback(callback);
return this;
}
public IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Action eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IReturnsResult Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> valueExpression)
{
this.SetReturnDelegate(valueExpression);
return this;
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "This class provides typed members for the method-returning interfaces. It's never used through the base class type.")]
public new IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> callback)
{
base.Callback(callback);
return this;
}
}
} | c# | 11 | 0.698127 | 220 | 43.826087 | 299 | starcoderdata |
<?php
return array(
'extra' => array(
'routes' => array(
'vetor.panel' => function() {
$api = new modules\vetor\panel\PanelApi();
$api->api();
},
'vetor.panel/feed' => function() {
$url = isset($_GET['url']) ? $_GET['url'] : '';
$api = new modules\vetor\panel\PanelApi();
$api->feed($url);
}
)
)
); | php | 18 | 0.383592 | 63 | 27.1875 | 16 | starcoderdata |
import Page from '../Page';
class Home extends Page {
static init(props) {
console.log(props);
}
}
export default Home; | javascript | 8 | 0.653846 | 27 | 13.444444 | 9 | starcoderdata |
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
// Resend the whole inventory to prevent visual glitches due to client-prediction
// This would not be needed if the Container enforces the same restrictions on slots as vanilla
// Cursor Item
/*for (IContainerListener crafter : listeners) {
crafter.updateCraftingInventory(this, this.getInventory());
}
// Inventory
for (int i = 0; i < this.inventorySlots.size(); ++i) {
for (IContainerListener crafter : listeners) {
crafter.sendSlotContents(this, i, this.inventorySlots.get(i).getStack());
}
}*/
} | java | 6 | 0.619718 | 103 | 40.823529 | 17 | inline |
<?php
/**
* Created by IntelliJ IDEA.
* User: tonyxu
* Date: 31/07/2016
* Time: 7:28 PM
*/
namespace Menulog\Model;
class Restaurant
{
/**
* @var int $id
*/
protected $id;
/**
* @var Menu[] $menus
*/
protected $menus;
/**
* @var string $name
*/
protected $name;
/**
* @var string $description
*/
protected $description;
/**
* url in JE is https://www.just-eat.co.uk/restaurants-{$uniqueName}/menu
* @var string $uniqueName
*/
protected $uniqueName;
/**
* @var float $ratingAverage
*/
protected $ratingAverage;
/**
* @var Image $logo;
*/
protected $logo;
/**
* @var boolean $isOpenNowForDelivery
*/
protected $isOpenNowForDelivery;
/**
* @return Menu[]
*/
public function getMenus()
{
return $this->menus;
}
/**
* @param Menu[] $menus
*/
public function setMenus($menus)
{
$this->menus = $menus;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getUniqueName()
{
return $this->uniqueName;
}
/**
* @param string $uniqueName
*/
public function setUniqueName($uniqueName)
{
$this->uniqueName = $uniqueName;
}
/**
* @return float
*/
public function getRatingAverage()
{
return $this->ratingAverage;
}
/**
* @param float $ratingAverage
*/
public function setRatingAverage($ratingAverage)
{
$this->ratingAverage = $ratingAverage;
}
/**
* @return Image
*/
public function getLogo()
{
return $this->logo;
}
/**
* @param Image $logo
*/
public function setLogo($logo)
{
$this->logo = $logo;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return boolean
*/
public function isOpenNowForDelivery()
{
return $this->isOpenNowForDelivery;
}
/**
* @param boolean $isOpenNowForDelivery
*/
public function setIsOpenNowForDelivery($isOpenNowForDelivery)
{
$this->isOpenNowForDelivery = $isOpenNowForDelivery;
}
/**
* @return array
*/
public function toArray()
{
$result = array();
$result['id'] = $this->getId();
$result['logo'] = $this->getLogo() ? $this->getLogo()->toArray() : '';
$result['name'] = $this->getName();
$result['unique_name'] = $this->getUniqueName();
$result['rating_average'] = $this->getRatingAverage();
$result['description'] = $this->getDescription();
$result['menus'] = array();
if ($this->getMenus()) {
foreach($this->getMenus() as $menu){
$result['menus'][] = $menu->toArray();
}
}
return $result;
}
} | php | 14 | 0.504992 | 78 | 16.425121 | 207 | starcoderdata |
import numpy as np
# Script to generate data for inverse and inverse update tests
# Output for copy-and-paste to C++
def output_for_cpp(A,var_name='a'):
N = A.shape[0]
for i in range(N):
for j in range(N):
print('%s(%d,%d) = %12.10g;'%(var_name,i,j,A[i,j]))
A = np.array([
[2.3, 4.5, 2.6],
[0.5, 8.5, 3.3],
[1.8, 4.4, 4.9]])
#A = np.array([
#[2.3, 4.5, 2.6, 1.2],
#[0.5, 8.5, 3.3, 0.3],
#[1.8, 4.4, 4.9, 2.8],
#[0.8, 4.1, 3.2, 1.1]
#])
print(A)
print('det A',np.abs(np.linalg.det(A)))
print('log det A',np.log(np.abs(np.linalg.det(A))))
Ainv = np.linalg.inv(A)
print(Ainv)
output_for_cpp(Ainv)
print('')
row = np.array([1.9, 2.0, 3.1])
#row = np.array([[1.9, 2.0, 3.1],
# [0.1, 4.2, 1.4]])
#row = np.array([3.2, 0.5, 5.9, 3.7])
B = A.copy()
# update row
#B[0,:] = row
# update column
B[:,0] = row
#B[:,0] = row[0]
#B[:,1] = row[1]
print('Updated A with column to get matrix B:')
print(B)
print('det B',np.abs(np.linalg.det(B)))
print('log det B',np.log(np.abs(np.linalg.det(B))))
print('det ratio',np.linalg.det(B)/np.linalg.det(A))
Binv = np.linalg.inv(B)
print('')
output_for_cpp(Binv,var_name='b') | python | 13 | 0.556332 | 62 | 19.087719 | 57 | starcoderdata |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016,
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: openssl_privatekey
author: " (@Spredzy)"
version_added: "2.3"
short_description: Generate OpenSSL private keys.
description:
- "This module allows one to (re)generate OpenSSL private keys. It uses
the pyOpenSSL python library to interact with openssl. One can generate
either RSA or DSA private keys. Keys are generated in PEM format."
requirements:
- "python-pyOpenSSL"
options:
state:
required: false
default: "present"
choices: [ present, absent ]
description:
- Whether the private key should exist or not, taking action if the state is different from what is stated.
size:
required: false
default: 4096
description:
- Size (in bits) of the TLS/SSL key to generate
type:
required: false
default: "RSA"
choices: [ RSA, DSA ]
description:
- The algorithm used to generate the TLS/SSL private key
force:
required: false
default: False
choices: [ True, False ]
description:
- Should the key be regenerated even it it already exists
path:
required: true
description:
- Name of the file in which the generated TLS/SSL private key will be written. It will have 0600 mode.
'''
EXAMPLES = '''
# Generate an OpenSSL private key with the default values (4096 bits, RSA)
# and no public key
- openssl_privatekey:
path: /etc/ssl/private/ansible.com.pem
# Generate an OpenSSL private key with a different size (2048 bits)
- openssl_privatekey:
path: /etc/ssl/private/ansible.com.pem
size: 2048
# Force regenerate an OpenSSL private key if it already exists
- openssl_privatekey:
path: /etc/ssl/private/ansible.com.pem
force: True
# Generate an OpenSSL private key with a different algorithm (DSA)
- openssl_privatekey:
path: /etc/ssl/private/ansible.com.pem
type: DSA
'''
RETURN = '''
size:
description: Size (in bits) of the TLS/SSL private key
returned:
- changed
- success
type: integer
sample: 4096
type:
description: Algorithm used to generate the TLS/SSL private key
returned:
- changed
- success
type: string
sample: RSA
filename:
description: Path to the generated TLS/SSL private key file
returned:
- changed
- success
type: string
sample: /etc/ssl/private/ansible.com.pem
'''
from ansible.module_utils.basic import *
try:
from OpenSSL import crypto
except ImportError:
pyopenssl_found = False
else:
pyopenssl_found = True
import os
class PrivateKeyError(Exception):
pass
class PrivateKey(object):
def __init__(self, module):
self.size = module.params['size']
self.state = module.params['state']
self.name = os.path.basename(module.params['path'])
self.type = module.params['type']
self.force = module.params['force']
self.path = module.params['path']
self.mode = module.params['mode']
self.changed = True
self.check_mode = module.check_mode
def generate(self, module):
"""Generate a keypair."""
if not os.path.exists(self.path) or self.force:
self.privatekey = crypto.PKey()
if self.type == 'RSA':
crypto_type = crypto.TYPE_RSA
else:
crypto_type = crypto.TYPE_DSA
try:
self.privatekey.generate_key(crypto_type, self.size)
except (TypeError, ValueError):
raise PrivateKeyError(get_exception())
try:
privatekey_file = os.open(self.path,
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
self.mode)
os.write(privatekey_file, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.privatekey))
os.close(privatekey_file)
except IOError:
self.remove()
raise PrivateKeyError(get_exception())
else:
self.changed = False
file_args = module.load_file_common_arguments(module.params)
if module.set_fs_attributes_if_different(file_args, False):
self.changed = True
def remove(self):
"""Remove the private key from the filesystem."""
try:
os.remove(self.path)
except OSError:
e = get_exception()
if e.errno != errno.ENOENT:
raise PrivateKeyError(e)
else:
self.changed = False
def dump(self):
"""Serialize the object into a dictionnary."""
result = {
'size': self.size,
'type': self.type,
'filename': self.path,
'changed': self.changed,
}
return result
def main():
module = AnsibleModule(
argument_spec = dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
size=dict(default=4096, type='int'),
type=dict(default='RSA', choices=['RSA', 'DSA'], type='str'),
force=dict(default=False, type='bool'),
path=dict(required=True, type='path'),
),
supports_check_mode = True,
add_file_common_args = True,
)
if not pyopenssl_found:
module.fail_json(msg='the python pyOpenSSL module is required')
path = module.params['path']
base_dir = os.path.dirname(module.params['path'])
if not os.path.isdir(base_dir):
module.fail_json(name=base_dir, msg='The directory %s does not exist or the file is not a directory' % base_dir)
if not module.params['mode']:
module.params['mode'] = int('0600', 8)
private_key = PrivateKey(module)
if private_key.state == 'present':
if module.check_mode:
result = private_key.dump()
result['changed'] = module.params['force'] or not os.path.exists(path)
module.exit_json(**result)
try:
private_key.generate(module)
except PrivateKeyError:
e = get_exception()
module.fail_json(msg=str(e))
else:
if module.check_mode:
result = private_key.dump()
result['changed'] = os.path.exists(path)
module.exit_json(**result)
try:
private_key.remove()
except PrivateKeyError:
e = get_exception()
module.fail_json(msg=str(e))
result = private_key.dump()
module.exit_json(**result)
if __name__ == '__main__':
main() | python | 16 | 0.596487 | 120 | 27.789272 | 261 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using HMPPS.ErrorReporting;
using Sitecore;
using Sitecore.Pipelines.HttpRequest;
using Sitecore.Security;
using Sitecore.Security.Authentication;
using Sitecore.Web;
using HMPPS.Utilities.Helpers;
using HMPPS.Utilities.Models;
using HMPPS.Utilities.Interfaces;
namespace HMPPS.Authentication.Pipelines
{
public class OAuth2SignInCallback : AuthenticationProcessorBase
{
private readonly IUserDataService _userDataService;
public OAuth2SignInCallback(IUserDataService userDataService, ILogManager logManager)
{
_userDataService = userDataService;
LogManager = logManager;
}
public override void Process(HttpRequestArgs args)
{
// NOTE - no error handling added. Failed requests are expected to result in an unhandled exception, which should show friendly error page.
// Only act on unauthenticated requests against the sign-in callback URL
if (Context.User == null || Context.User.IsAuthenticated ||
Context.User.Identity.GetType() == typeof(UserProfile) ||
!args.Context.Request.Url.AbsoluteUri.StartsWith(Settings.SignInCallbackUrl)) return;
// Validate token and obtain claims
//var tempCookie = args.Context.Request.Cookies[Settings.TempCookieName];
var tempCookie = new CookieHelper(Settings.TempCookieName, args.Context);
var tempHttpCookie = tempCookie.GetCookie();
var claims = ValidateCodeAndGetClaims(args.Context.Request.QueryString["code"], args.Context.Request.QueryString["state"], tempHttpCookie).ToList();
var userData = new UserIdamData(claims);
_userDataService.SaveUserIdamDataToCookie(claims, args.Context);
// Build sitecore user and log in - this will persist until log out or session ends.
var user = BuildVirtualUser(userData);
AuthenticationManager.LoginVirtualUser(user);
var targetUrl = tempCookie.GetValue("returnUrl") ?? "/";
tempCookie.Delete();
WebUtil.Redirect(targetUrl);
}
private IEnumerable ValidateCodeAndGetClaims(string code, string state, HttpCookie tempCookie)
{
if (tempCookie == null)
throw new InvalidOperationException("Could not validate identity token. No temp cookie found.");
if (string.IsNullOrWhiteSpace(tempCookie.Values["state"]) || tempCookie.Values["state"] != state)
throw new InvalidOperationException("Could not validate identity token. Invalid state.");
if (string.IsNullOrWhiteSpace(tempCookie.Values["nonce"]))
throw new InvalidOperationException("Could not validate identity token. Invalid nonce.");
var nonce = tempCookie.Values["nonce"];
var tokenManager = new TokenManager(LogManager);
//TODO: Call the async version - but you can't from within a pipeline! Move this into a controller and redirect to it?
var tokenResponse = tokenManager.RequestAccessToken(code);
var claimsPrincipal = tokenManager.ValidateIdentityToken(tokenResponse.IdentityToken, nonce);
var claims = tokenManager.ExtractClaims(tokenResponse, claimsPrincipal);
return claims;
}
}
} | c# | 20 | 0.686851 | 160 | 40.285714 | 84 | starcoderdata |
async _run() {
try {
this.running = true;
// main blocking loop
// abort if this.running is set to false
// from here on, user can end debugger with ctrl+c
while (this.running) {
if (this.argv.ngrok) {
// agent: ngrok
// simply block, ngrokServer keeps running in background
await sleep(1000);
} else {
// agent: concurrent
// agent: non-concurrent
// wait for activation, run it, complete, repeat
const activation = await this.agentMgr.waitForActivations();
if (!activation) {
return;
}
const id = activation.$activationId;
delete activation.$activationId;
log.verbose("Parameters:", activation);
const startTime = Date.now();
// run this activation on the local docker container
// which will block if the actual debugger hits a breakpoint
const result = await this.invoker.run(activation, id);
const duration = Date.now() - startTime;
// pass on the local result to the agent in openwhisk
if (!await this.agentMgr.completeActivation(id, result, duration)) {
return;
}
}
}
} finally {
await this.shutdown();
}
} | javascript | 16 | 0.457002 | 88 | 36.022727 | 44 | inline |