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
#include "op_config_file_utils.hpp" #include "yaml_json_emitter.hpp" #include "yaml-cpp/eventhandler.h" #include "yaml-cpp/emitfromevents.h" #include "../src/nodeevents.h" #include #include #include #include namespace openperf::config::file { bool op_config_is_number(std::string_view value) { if (value.empty()) { return false; } char* endptr; // Is it an integer? strtoll(value.data(), &endptr, 0); if (value.data() + value.length() == endptr) { return true; } // How about a double? strtod(value.data(), &endptr); if (value.data() + value.length() == endptr) { return true; } return false; } std::tuple<std::string_view, std::string_view> op_config_split_path_id(std::string_view path_id) { size_t last_slash_location = path_id.find_last_of('/'); if (last_slash_location == std::string_view::npos) { // No slash. Not a valid /path/id string. return std::tuple(std::string_view(), std::string_view()); } if (last_slash_location == 0) { return std::tuple(path_id, std::string_view()); } return std::tuple(path_id.substr(0, last_slash_location), path_id.substr(last_slash_location + 1)); } tl::expected<std::string, std::string> op_config_yaml_to_json(const YAML::Node& yaml_src) { std::ostringstream output_stream; yaml_json_emitter emitter(output_stream); NodeEvents events(yaml_src); try { events.Emit(emitter); } catch (std::exception& e) { return (tl::make_unexpected( "Error while converting YAML configuration to JSON. " + std::string(e.what()))); } return output_stream.str(); } } // namespace openperf::config::file
c++
17
0.626712
66
25.545455
66
starcoderdata
/* * Copyright (c) 2022 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.opengauss.mppdbide.view.handler.connection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.opengauss.mppdbide.utils.IMessagesConstants; import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; import org.opengauss.mppdbide.view.ui.connectiondialog.UserInputDialog; /** * * Title: class * * Description: The Class ClientSSLKeyDialog. * * @since 3.0.0 */ public class ClientSSLKeyDialog extends UserInputDialog { private String keyFileName; private Label keySSl; private Text clSSLKeyFilePathText; private Button sslKeyBrowseBtn; /** * Instantiates a new client SSL key dialog. * * @param parent the parent * @param serverObject the server object */ public ClientSSLKeyDialog(Shell parent, Object serverObject) { super(parent, serverObject); } /** * Creates the dialog area. * * @param parent the parent * @return the control */ @Override protected Control createDialogArea(Composite parent) { Composite curComposite = (Composite) getBlankDialogArea(parent); curComposite.setLayout(new GridLayout(1, false)); GridData grid2 = new GridData(); grid2.grabExcessHorizontalSpace = true; grid2.horizontalAlignment = GridData.FILL; grid2.verticalAlignment = GridData.FILL; grid2.horizontalIndent = 5; grid2.verticalIndent = 0; grid2.minimumWidth = 400; curComposite.setLayoutData(grid2); GridLayout valueFieldLayout = new GridLayout(2, false); valueFieldLayout.horizontalSpacing = 0; valueFieldLayout.marginWidth = 0; valueFieldLayout.marginHeight = 5; valueFieldLayout.verticalSpacing = 2; keySSl = new Label(curComposite, SWT.NULL); keySSl.setText(MessageConfigLoader.getProperty(IMessagesConstants.ENTER_CLIENT_SSLPVT_KEYFILE)); Composite clientKeyComposite = new Composite(curComposite, SWT.NULL); clientKeyComposite.setLayout(valueFieldLayout); clientKeyComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); clSSLKeyFilePathText = new Text(clientKeyComposite, SWT.READ_ONLY | SWT.BORDER); clSSLKeyFilePathText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); clSSLKeyFilePathText.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); inputControl = clSSLKeyFilePathText; sslKeyBrowseBtn = new Button(clientKeyComposite, SWT.NONE); sslKeyBrowseBtn.setText(MessageConfigLoader.getProperty(IMessagesConstants.DB_CONN_BROWSE)); sslKeyBrowseBtn.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.OPEN); dialog.setFilterNames( new String[] {MessageConfigLoader.getProperty(IMessagesConstants.BTN_CLIENT_PVTKEY)}); dialog.setFilterExtensions( new String[] {MessageConfigLoader.getProperty(IMessagesConstants.BTN_CLIENT_PVTKEY)}); String clientKeyPath = dialog.open(); clSSLKeyFilePathText.setText(clientKeyPath != null ? clientKeyPath : ""); if (!"".equals(clSSLKeyFilePathText.getText())) { enableButtons(); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); return curComposite; } /** * On success UI action. * * @param obj the obj */ @Override public void onSuccessUIAction(Object obj) { } /** * Checks if is connect DB. * * @return true, if is connect DB */ @Override protected boolean isConnectDB() { return true; } /** * On critical exception UI action. * * @param e the e */ @Override public void onCriticalExceptionUIAction(DatabaseCriticalException e) { } /** * On operational exception UI action. * * @param e the e */ @Override public void onOperationalExceptionUIAction(DatabaseOperationException e) { } /** * On presetup failure UI action. * * @param exception the e */ @Override public void onPresetupFailureUIAction(MPPDBIDEException exception) { } /** * Gets the window title. * * @return the window title */ @Override protected String getWindowTitle() { return MessageConfigLoader.getProperty(IMessagesConstants.ENTRE_CLIENTSSLKEY); } /** * Gets the header. * * @return the header */ @Override protected String getHeader() { return MessageConfigLoader.getProperty(IMessagesConstants.ENTER_CLIENT_SSLPVT_KEYFILE); } /** * Perform ok operation. */ @Override protected void performOkOperation() { keyFileName = clSSLKeyFilePathText.getText(); Path sslPath = Paths.get(keyFileName).toAbsolutePath().normalize(); if (!Files.isReadable(sslPath)) { printErrorMessage(MessageConfigLoader.getProperty(IMessagesConstants.INVALID_SSL_KEY), false); } else { close(); } } /** * Gets the key file name. * * @return the key file name */ public String getKeyFileName() { return this.keyFileName; } }
java
20
0.67001
110
30.126697
221
starcoderdata
const BUTTON_CLICK = 'app/user/SET_BUTTON_CLICK'; const SET_VALUE = 'app/user/SET_VALUE'; const AUTHENTICATE_USER = 'app/user/AUTHENTICATE_USER'; const SET_WALLET_ADDRESS = 'app/user/SET_WALLET_ADDRESS'; const NEW_USER = 'app/user/NEW_USER'; const SAVE_USER = 'app/user/SAVE_USER'; const FETCH_NFT_DATA = 'app/user/FETCH_NFT_DATA'; const SET_NFT_DATA = 'app/user/SET_NFT_DATA'; const CREATE_NFT = 'app/user/CREATE_NFT'; export { BUTTON_CLICK, SET_VALUE, AUTHENTICATE_USER, SET_WALLET_ADDRESS, NEW_USER, SAVE_USER, FETCH_NFT_DATA, SET_NFT_DATA, CREATE_NFT, };
javascript
11
0.713816
57
26.636364
22
starcoderdata
import http from './httpRequest' const baseUrl = 'http://192.168.3.11:8081/api' // 病人 export function Patient_GetList (params) { return http({ url: baseUrl + '/Patient/GetList', method: 'GET', params: params }) } // 检验 export function getLisList (params) { return http({ url: baseUrl + '/Lis/GetList', method: 'GET', params: params }) } export function getLisReportList (params) { return http({ url: baseUrl + '/Lis/GetReportList', method: 'GET', params: params }) } // 检查 export function getPacsList (params) { return http({ url: baseUrl + '/Pacs/GetList', method: 'GET', params: params }) } export function getPacsReportList (params) { return http({ url: baseUrl + '/Pacs/GetReportList', method: 'GET', params: params }) } // 医嘱 export function getPatientOrderSinglet (params) { return http({ url: baseUrl + '/PatientOrder/GetSingle', method: 'get', params: params }) }
javascript
11
0.627572
49
17.692308
52
starcoderdata
namespace LaTuerca.Migrations { using System; using System.Data.Entity.Migrations; public partial class Compra : DbMigration { public override void Up() { CreateTable( "dbo.Compras", c => new { Id = c.Int(nullable: false, identity: true), Fecha = c.DateTime(nullable: false, storeType: "date"), NumeroFactura = c.Int(nullable: false), ProveedorId = c.Int(nullable: false), Total = c.Decimal(nullable: false, precision: 18, scale: 2), Pagado = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Proveedors", t => t.ProveedorId, cascadeDelete: true) .Index(t => t.ProveedorId); CreateTable( "dbo.CompraDetalles", c => new { Id = c.Int(nullable: false, identity: true), CompraId = c.Int(nullable: false), Cantidad = c.Int(nullable: false), RepuestoId = c.Int(nullable: false), Precio = c.Decimal(nullable: false, precision: 18, scale: 2), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Compras", t => t.CompraId, cascadeDelete: true) .ForeignKey("dbo.Repuestoes", t => t.RepuestoId, cascadeDelete: false) .Index(t => t.CompraId) .Index(t => t.RepuestoId); } public override void Down() { DropForeignKey("dbo.Compras", "ProveedorId", "dbo.Proveedors"); DropForeignKey("dbo.CompraDetalles", "RepuestoId", "dbo.Repuestoes"); DropForeignKey("dbo.CompraDetalles", "CompraId", "dbo.Compras"); DropIndex("dbo.CompraDetalles", new[] { "RepuestoId" }); DropIndex("dbo.CompraDetalles", new[] { "CompraId" }); DropIndex("dbo.Compras", new[] { "ProveedorId" }); DropTable("dbo.CompraDetalles"); DropTable("dbo.Compras"); } } }
c#
27
0.464423
86
40.672727
55
starcoderdata
const { siteURL, router } = require('$config/config'); const makeDisputeDownloadUrl = dispute => `${siteURL}${router.helpers.Disputes.download.url(dispute.id)}`; module.exports = ({ dispute, }) => `Thank you for disputing your debt! You can download a copy of your dispute here: > ${makeDisputeDownloadUrl(dispute)} If you opted to mail the dispute yourself, it is a good idea to send it certified mail so you can be sure it was received. If you need help mailing it, we will send you the tracking info once it is sent. Keep in touch with us! It's easy on the platform to send admins a message or photos of responses you receive from your collector(s). And we love to hear, of course, when the debt is discharged or removed from your credit. When you win, we all win. Love, TDC P.S. You can also post any news you receive from the collector on the community pages. The more information we have about how collectors are responding to these disputes the better we can catch those who are breaking the law and organize together for debt relief.`;
javascript
11
0.759242
265
54.526316
19
starcoderdata
/* * File: repfirst.c * ---------------- * This file implements and tests the function ReplaceFirst. */ #include #include "genlib.h" #include "strlib.h" #include "simpio.h" /* Function prototypes */ string ReplaceFirst(string str, string pattern, string replacement); /* Main program */ main() { string str, pattern, replacement; printf("This program edits a string by replacing the first\n"); printf("instance of a pattern substring by a new string.\n"); printf("Enter the string to be edited:\n"); str = GetLine(); printf("Enter the pattern string: "); pattern = GetLine(); printf("Enter the replacement string: "); replacement = GetLine(); str = ReplaceFirst(str, pattern, replacement); printf("%s\n", str); } /* * Function: ReplaceFirst * Usage: newstr = ReplaceFirst(str, pattern, replacement); * -------------------------------------------------------- * This function searches through the string str and replaces the * first instance of the pattern with the specified replacement. * If the pattern string does not appear, str is returned unchanged. */ string ReplaceFirst(string str, string pattern, string replacement) { string head, tail; int pos; pos = FindString(pattern, str, 0); if (pos == -1) return (str); head = SubString(str, 0, pos - 1); tail = SubString(str, pos + StringLength(pattern), StringLength(str) - 1); return (Concat(Concat(head, replacement), tail)); }
c
10
0.633355
68
26.981481
54
starcoderdata
private void TextBlockLocation_PreviewMouseDown(object sender, MouseButtonEventArgs e) { // Show the location window LocationWindow locationWindow = new LocationWindow(); locationWindow.Owner = this; locationWindow.ShowDialog(); if (InvisibleManCore.isSelectServer) // If you choose a new server location, set the new information to InvisibleManCore { LabelCountry.Content = InvisibleManCore.serverInformations[InvisibleManCore.index].serverName; InvisibleManCore.isSelectServer = false; ChangeServer(); } }
c#
13
0.640244
132
45.928571
14
inline
var cp = require('child_process'); var fs = require('fs'); var h = require('../helper'); var log = require('../log'); var Plugin = require('../plugin.js'); var session = require('../session'); // Please note that we DON'T want implement a lightweight judge engine // here, thus we are NOT going to support all the problems!!! // // Only works for those problems could be easily tested. // // [Usage] // // https://github.com/skygragon/leetcode-cli-plugins/blob/master/docs/cpp.run.md // var plugin = new Plugin(100, 'golang.run', '2017.07.29', 'Plugin to run golang code locally for debugging.'); plugin.testProblem = function (problem, cb) { let ori = null; let tmp = null; if (session.argv.tpl) { log.info('Rewrite source code ' + problem.file); let code = fs.readFileSync(problem.file).toString() let strs = code.split('//--ignore--'); code = strs[strs.length - 1] ori = problem.file; tmp = ori + '.tmp'; fs.writeFileSync(tmp, code); problem.file = tmp; } let ans = plugin.next.testProblem(problem, cb); if (session.argv.tpl) { fs.unlinkSync(problem.file); problem.file = ori; } return ans }; plugin.submitProblem = function (problem, cb) { let ori = null; let tmp = null; if (session.argv.tpl) { log.info('Rewrite source code ' + problem.file); let code = fs.readFileSync(problem.file).toString() let strs = code.split('//--ignore--'); code = strs[strs.length - 1] ori = problem.file; tmp = ori + '.tmp'; fs.writeFileSync(tmp, code); problem.file = tmp; } let ans = plugin.next.submitProblem(problem, cb); if (session.argv.tpl) { fs.unlinkSync(problem.file); problem.file = ori; } return ans }; plugin.exportProblem = function (problem, opts) { let header = ''; if (session.argv.tpl) { log.info('Rewrite source code ' + problem.file); header = 'package main\n\n//--ignore--' } return header + plugin.next.exportProblem(problem, opts); }; module.exports = plugin;
javascript
11
0.645414
80
26.186667
75
starcoderdata
namespace proland { class TerrainNode; /** * A deformation of space. Such a deformation maps a 3D source point to a 3D * destination point. The source space is called the <i>local</i> space, while * the destination space is called the <i>deformed</i> space. Source and * destination points are defined with their x,y,z coordinates in an orthonormal * reference frame. A Deformation is also responsible to set the shader uniforms * that are necessary to project a TerrainQuad on screen, taking the deformation * into account. The default implementation of this class implements the * identity deformation, i.e. the deformed point is equal to the local one. * @ingroup terrain * @authors Eric Bruneton, Antoine Begault */ PROLAND_API class Deformation : public Object { public: /** * Creates a new Deformation. */ Deformation(); /** * Deletes this Deformation. */ virtual ~Deformation(); /** * Returns the deformed point corresponding to the given source point. * * @param localPt a point in the local (i.e., source) space. * @return the corresponding point in the deformed (i.e., destination) space. */ virtual vec3d localToDeformed(const vec3d &localPt) const; /** * Returns the differential of the deformation function at the given local * point. This differential gives a linear approximation of the deformation * around a given point, represented with a matrix. More precisely, if p * is near localPt, then the deformed point corresponding to p can be * approximated with localToDeformedDifferential(localPt) * (p - localPt). * * @param localPt a point in the local (i.e., source) space. <i>The z * coordinate of this point is ignored, and considered to be 0</i>. * @return the differential of the deformation function at the given local * point. */ virtual mat4d localToDeformedDifferential(const vec3d &localPt, bool clamp = false) const; /** * Returns the local point corresponding to the given source point. * * @param deformedPt a point in the deformed (i.e., destination) space. * @return the corresponding point in the local (i.e., source) space. */ virtual vec3d deformedToLocal(const vec3d &deformedPt) const; /** * Returns the local bounding box corresponding to the given source disk. * * @param deformedPt the source disk center in deformed space. * @param deformedRadius the source disk radius in deformed space. * @return the local bounding box corresponding to the given source disk. */ virtual box2f deformedToLocalBounds(const vec3d &deformedCenter, double deformedRadius) const; /** * Returns an orthonormal reference frame of the tangent space at the given * deformed point. This reference frame is such that its xy plane is the * tangent plane, at deformedPt, to the deformed surface corresponding to * the local plane z=0. Note that this orthonormal reference frame does * <i>not</i> give the differential of the inverse deformation funtion, * which in general is not an orthonormal transformation. If p is a deformed * point, then deformedToLocalFrame(deformedPt) * p gives the coordinates of * p in the orthonormal reference frame defined above. * * @param deformedPt a point in the deformed (i.e., destination) space. * @return the orthonormal reference frame at deformedPt defined above. */ virtual mat4d deformedToTangentFrame(const vec3d &deformedPt) const; /** * Sets the shader uniforms that are necessary to project on screen the * TerrainQuad of the given TerrainNode. This method can set the uniforms * that are common to all the quads of the given terrain. * * @param context the SceneNode to which the TerrainNode belongs. This node * defines the absolute position and orientation of the terrain in * world space (through SceneNode#getLocalToWorld). * @param n a TerrainNode. */ virtual void setUniforms(ptr<SceneNode> context, ptr<TerrainNode> n, ptr<Program> prog) const; /** * Sets the shader uniforms that are necessary to project on screen the * given TerrainQuad. This method can set the uniforms that are specific to * the given quad. * * @param context the SceneNode to which the TerrainNode belongs. This node * defines the absolute position and orientation of the terrain in * world space (through SceneNode#getLocalToWorld). * @param q a TerrainQuad. */ virtual void setUniforms(ptr<SceneNode> context, ptr<TerrainQuad> q, ptr<Program> prog) const; /** * Returns the distance in local (i.e., source) space between a point and a * bounding box. * * @param localPt a point in local space. * @param localBox a bounding box in local space. */ virtual float getLocalDist(const vec3d &localPt, const box3d &localBox) const; /** * Returns the visibility of a bounding box in local space, in a view * frustum defined in deformed space. * * @param t a TerrainNode. This is node is used to get the camera position * in local and deformed space with TerrainNode#getLocalCamera and * TerrainNode#getDeformedCamera, as well as the view frustum planes * in deformed space with TerrainNode#getDeformedFrustumPlanes. * @param localBox a bounding box in local space. * @return the visibility of the bounding box in the view frustum. */ virtual SceneManager::visibility getVisibility(const TerrainNode *t, const box3d &localBox) const; protected: /** * The transformation from camera space to screen space. */ mutable mat4f cameraToScreen; /** * The transformation from local space to screen space. */ mutable mat4d localToScreen; /** * The transformation from local space to tangent space (in z=0 plane). */ mutable mat3f localToTangent; /** * The program that contains the uniforms that were set during the last * call to setUniforms(ptr<SceneNode>, ptr<TerrainNode>, ...). */ mutable ptr<Program> lastNodeProg; /** * The program that contains the uniforms that were set during the last * call to setUniforms(ptr<SceneNode>, ptr<TerrainQuad>, ...). */ mutable ptr<Program> lastQuadProg; /** * The coordinates of a TerrainQuad (ox,oy,l,l). */ mutable ptr<Uniform4f> offsetU; /** * The camera coordinates relatively to a TerrainQuad. This vector is * defined as (camera.x - ox) / l, (camera.y - oy) / l), (camera.z - * groundHeightAtCamera) / l), 1. */ mutable ptr<Uniform4f> cameraU; /** * The blending parameters for geomorphing. This vector is defined by * (splitDistance + 1, splitDistance - 1). */ mutable ptr<Uniform2f> blendingU; /** * The transformation from local space to screen space. */ mutable ptr<UniformMatrix4f> localToScreenU; /** * The transformation from local tile coordinates to tangent space. */ mutable ptr<UniformMatrix3f> tileToTangentU; /** * The deformed corners of a quad in screen space. */ mutable ptr<UniformMatrix4f> screenQuadCornersU; /** * The deformed vertical vectors at the corners of a quad, * in screen space. */ mutable ptr<UniformMatrix4f> screenQuadVerticalsU; virtual void setScreenUniforms(ptr<SceneNode> context, ptr<TerrainQuad> q, ptr<Program> prog) const; }; }
c
11
0.684197
104
37.034826
201
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 br.org.gdt.beans; import br.org.gdt.model.RecHabilidade; import br.org.gdt.service.RecHabilidadeService; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; /** * * @author Anderson */ @ManagedBean @RequestScoped public class RecHabilidadeBean { private boolean formAtivo = false; private RecHabilidade habilidade = new RecHabilidade(); private List habilidades; @ManagedProperty("#{recHabilidadeService}") private RecHabilidadeService recHabilidadeService; public RecHabilidadeBean() { } public void Salvar() { if (habilidade.getRecIdhabilidade() > 0) { recHabilidadeService.Alterar(habilidade); } else { recHabilidadeService.Inserir(habilidade); } habilidades = recHabilidadeService.ListarTodas(); } public String PreparaEdicao(RecHabilidade habilidade) { this.formAtivo = true; this.habilidade = habilidade; return "habilidades"; } public String Excluir(RecHabilidade habilidade) { recHabilidadeService.Excluir(habilidade.getRecIdhabilidade()); habilidades.remove(habilidade); return "habilidades"; } public List ListarTodas() { if (habilidades == null) { habilidades = recHabilidadeService.ListarTodas(); } return habilidades; } public void Adicionar() { this.formAtivo = true; this.habilidade = new RecHabilidade(); } public void cancel() { this.formAtivo = false; this.habilidade = new RecHabilidade(); } public RecHabilidade getHabilidade() { return habilidade; } public void setHabilidade(RecHabilidade habilidade) { this.habilidade = habilidade; } public List getHabilidades() { return habilidades; } public void setHabilidades(List habilidades) { this.habilidades = habilidades; } public RecHabilidadeService getRecHabilidadeService() { return recHabilidadeService; } public void setRecHabilidadeService(RecHabilidadeService recHabilidadeService) { this.recHabilidadeService = recHabilidadeService; } public boolean isFormAtivo() { return formAtivo; } public void setFormAtivo(boolean formAtivo) { this.formAtivo = formAtivo; } }
java
9
0.649013
84
26.613861
101
starcoderdata
<?php Route::post('/tiketux/menu/api/list/v1', 'Tiketux\Menu\Api\MenuApi@list_halaman'); Route::post('/tiketux/menu/api/detail/v1', 'Tiketux\Menu\Api\MenuApi@detail'); Route::post('/tiketux/menu/api/delete/v1', 'Tiketux\Menu\Api\MenuApi@delete'); Route::post('/tiketux/menu/api/save/v1', 'Tiketux\Menu\Api\MenuApi@save'); Route::get('/menu/api/list', 'Tiketux\Menu\Api\MenuApi@list');
php
6
0.727488
82
46
9
starcoderdata
import io from 'socket.io-client'; import { document } from 'global'; const location = document.location; const port = location.port === '' ? (location.protocol === 'https:' ? 443 : 80) : location.port; const url = `${location.protocol}//${location.hostname}:${port}/`; export default io.connect(url, { path: '/api_socket' });
javascript
4
0.668622
96
30.090909
11
starcoderdata
<?php /** * PHPCoord. * * @author */ declare(strict_types=1); namespace PHPCoord\Geometry\Extents\BoundingBoxOnly; /** * Australasia and Oceania/American Samoa - 2 main island groups and Rose Island. * @internal */ class Extent3110 { public function __invoke(): array { return [ [ [ [-168.09695119791, -14.493235966848], [-168.19694920856, -14.493235966848], [-168.19694920856, -14.580481709789], [-168.09695119791, -14.580481709789], [-168.09695119791, -14.493235966848], ], ], [ [ [-170.51187379253, -14.204306196095], [-170.87322752583, -14.204306196095], [-170.87322752583, -14.425555635571], [-170.51187379253, -14.425555635571], [-170.51187379253, -14.204306196095], ], ], [ [ [-169.38735542361, -14.118008545322], [-169.72809554498, -14.118008545322], [-169.72809554498, -14.304122921053], [-169.38735542361, -14.304122921053], [-169.38735542361, -14.118008545322], ], ], ]; } }
php
15
0.552932
209
30.487179
39
starcoderdata
#!/usr/bin/env python import urllib.request import sys import json import subprocess import os import fnmatch import pathlib import shutil vendor_file_template = """// Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY. // Package %s is required to provide support for vendoring modules package %s """ include_vendor_file_template = """// Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY. // Package include is required to provide support for vendoring modules package include import ( %s ) """ CHROME_VERSIONS_URL = "https://omahaproxy.appspot.com/all.json?os=linux&channel=stable" V8_VERSION_FILE = "v8_version" deps_path = os.path.dirname(os.path.realpath(__file__)) v8go_path = os.path.abspath(os.path.join(deps_path, os.pardir)) env = os.environ.copy() v8_path = os.path.join(deps_path, "v8") v8_include_path = os.path.join(v8_path, "include") deps_include_path = os.path.join(deps_path, "include") def get_directories_names(path): flist = [] for p in pathlib.Path(path).iterdir(): if p.is_dir(): flist.append(p.name) return sorted(flist) def package_name(package, index, total): name = f'_ "rogchap.com/v8go/deps/include/{package}"' if (index + 1 == total): return name else: return name + '\n' def create_include_vendor_file(src_path, directories): package_names = [] total_directories = len(directories) for index, directory_name in enumerate(directories): package_names.append(package_name(directory_name, index, total_directories)) with open(os.path.join(src_path, 'vendor.go'), 'w') as temp_file: temp_file.write(include_vendor_file_template % (' '.join(package_names))) def create_vendor_files(src_path): directories = get_directories_names(src_path) create_include_vendor_file(src_path, directories) for directory in directories: directory_path = os.path.join(src_path, directory) vendor_go_file_path = os.path.join(directory_path, 'vendor.go') if os.path.isfile(vendor_go_file_path): continue with open(os.path.join(directory_path, 'vendor.go'), 'w') as temp_file: temp_file.write(vendor_file_template % (directory, directory)) def update_v8_version_file(src_path, version): with open(os.path.join(src_path, V8_VERSION_FILE), "w") as v8_file: v8_file.write(version) def read_v8_version_file(src_path): v8_version_file = open(os.path.join(src_path, V8_VERSION_FILE), "r") return v8_version_file.read().strip() def get_latest_v8_info(): with urllib.request.urlopen(CHROME_VERSIONS_URL) as response: json_response = response.read() return json.loads(json_response) # Current version current_v8_version_installed = read_v8_version_file(deps_path) # Get latest version latest_v8_info = get_latest_v8_info() latest_stable_v8_version = latest_v8_info[0]["versions"][0]["v8_version"] if current_v8_version_installed != latest_stable_v8_version: subprocess.check_call(["git", "fetch", "origin", latest_stable_v8_version], cwd=v8_path, env=env) # checkout latest stable commit subprocess.check_call(["git", "checkout", latest_stable_v8_version], cwd=v8_path, env=env) shutil.rmtree(deps_include_path) shutil.copytree(v8_include_path, deps_include_path, dirs_exist_ok=True) create_vendor_files(deps_include_path) update_v8_version_file(deps_path, latest_stable_v8_version)
python
14
0.697365
98
30.108108
111
starcoderdata
<?php namespace App\Exports; use App\Models\Tadtprod2record; use Maatwebsite\Excel\Concerns\FromCollection; class Tadtprod2Export implements FromCollection { /** * @return \Illuminate\Support\Collection */ public function collection() { return Tadtprod2record::select('T_Adt_Prod2_Ubic_Cod', 'T_Adt_Prod2_Prod_Ref', 'T_Adt_Prod2_Piezas', 'T_Adt_Prod2_Cant_x_Pieza', 'T_Adt_Prod2_Saldo', 'T_Adt_Prod2_Total', 'T_Adt_Prod2_Lote', 'T_Adt_Prod2_Vencimiento')->get(); } }
php
11
0.693227
233
28.529412
17
starcoderdata
package yuku.alkitab.base.widget; import androidx.recyclerview.widget.RecyclerView; import com.afollestad.materialdialogs.MaterialDialog; public class MaterialDialogAdapterHelper { public static abstract class Adapter extends RecyclerView.Adapter { private MaterialDialog dialog; public void setDialog(MaterialDialog dialog) { this.dialog = dialog; } public void dismissDialog() { this.dialog.dismiss(); } } public static MaterialDialog show(MaterialDialog.Builder builder, Adapter adapter) { final MaterialDialog dialog = builder .adapter(adapter, null) .build(); adapter.setDialog(dialog); dialog.show(); return dialog; } }
java
8
0.777778
93
24.258065
31
starcoderdata
def when_background_tasks_enabled(fn): def wrapper(*args, **kwargs): if settings.LD_DISABLE_BACKGROUND_TASKS: return return fn(*args, **kwargs) # Expose attributes from wrapped TaskProxy function attrs = vars(fn) for key, value in attrs.items(): setattr(wrapper, key, value) return wrapper
python
9
0.639769
55
28
12
inline
# -*- coding: utf-8 -*- # Copyright (c) 2017, Dataent Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import dataent from dataent.model.document import Document from dataent.utils import get_source_value class DataMigrationMapping(Document): def get_filters(self): if self.condition: return dataent.safe_eval(self.condition, dict(dataent=dataent)) def get_fields(self): fields = [] for f in self.fields: if not (f.local_fieldname[0] in ('"', "'") or f.local_fieldname.startswith('eval:')): fields.append(f.local_fieldname) if dataent.db.has_column(self.local_doctype, self.migration_id_field): fields.append(self.migration_id_field) if 'name' not in fields: fields.append('name') return fields def get_mapped_record(self, doc): '''Build a mapped record using information from the fields table''' mapped = dataent._dict() key_fieldname = 'remote_fieldname' value_fieldname = 'local_fieldname' if self.mapping_type == 'Pull': key_fieldname, value_fieldname = value_fieldname, key_fieldname for field_map in self.fields: key = get_source_value(field_map, key_fieldname) if not field_map.is_child_table: # field to field mapping value = get_value_from_fieldname(field_map, value_fieldname, doc) else: # child table mapping mapping_name = field_map.child_table_mapping value = get_mapped_child_records(mapping_name, doc.get(get_source_value(field_map, value_fieldname))) mapped[key] = value return mapped def get_mapped_child_records(mapping_name, child_docs): mapped_child_docs = [] mapping = dataent.get_doc('Data Migration Mapping', mapping_name) for child_doc in child_docs: mapped_child_docs.append(mapping.get_mapped_record(child_doc)) return mapped_child_docs def get_value_from_fieldname(field_map, fieldname_field, doc): field_name = get_source_value(field_map, fieldname_field) if field_name.startswith('eval:'): value = dataent.safe_eval(field_name[5:], dict(dataent=dataent)) elif field_name[0] in ('"', "'"): value = field_name[1:-1] else: value = get_source_value(doc, field_name) return value
python
18
0.716955
88
29.472222
72
starcoderdata
<div class="m-grid__item m-grid__item--fluid m-wrapper"> <div class="m-content"> <div class="m-portlet"> <div class="m-portlet__head"> <div class="m-portlet__head-caption"> <div class="m-portlet__head-title"> <h3 class="m-portlet__head-text"> Day wise report view <div class="m-portlet__body"> <table class="table table-bordered"> <td style="width: 30%"> Vbs <td style="width: 30%"> if(isset($daywise_report_view['date']) && !empty($daywise_report_view['date'])) { $newDate = date("d-m-Y", strtotime($daywise_report_view['date'])); echo $newDate; } ?> <td style="width: 30%"> if(isset($daywise_report_view['men']) && !empty($daywise_report_view['men'])) { echo $daywise_report_view['men']; } ?> <td style="width: 30%"> if(isset($daywise_report_view['women']) && !empty($daywise_report_view['women'])) { echo $daywise_report_view['women']; } ?> <td style="width: 30%"> if(isset($daywise_report_view['boys']) && !empty($daywise_report_view['boys'])) { echo $daywise_report_view['boys']; } ?> <td style="width: 30%"> if(isset($daywise_report_view['girls']) && !empty($daywise_report_view['girls'])) { echo $daywise_report_view['girls']; } ?> <td style="width: 30%"> oF Work if(isset($daywise_report_view['place_of_work']) && !empty($daywise_report_view['place_of_work'])) { echo $daywise_report_view['place_of_work']; } ?> <td style="width: 30%"> Information if(isset($daywise_report_view['work_information']) && !empty($daywise_report_view['work_information'])) { echo $daywise_report_view['work_information']; } ?> <td style="width: 30%"> points if(isset($daywise_report_view['prayer_points']) && !empty($daywise_report_view['prayer_points'])) { echo $daywise_report_view['prayer_points']; } ?> <td style="width: 30%"> if(isset($daywise_report_view['achievements']) && !empty($daywise_report_view['achievements'])) { echo $daywise_report_view['achievements']; } ?> <td style="width: 30%"> if(isset($daywise_report_view['challenges']) && !empty($daywise_report_view['challenges'])) { echo $daywise_report_view['challenges']; } ?> <!-- -->
php
13
0.392157
207
44.697917
96
starcoderdata
<?php use Cake\Routing\Router; Router::scope('/', function ($routes) { $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']); $routes->connect('/some_alias', ['controller' => 'tests_apps', 'action' => 'some_method'], ['_name' => 'some']); });
php
14
0.605505
116
39.875
8
starcoderdata
BOOL CSession::IsExecutable() { // We are ready to execute if we have a root file, we are not currently // debugging it, we are not a DWI session, it is an executable, not a DLL, // is for our architecture, and is not for CE. // // We used to require the IMAGE_FILE_32BIT_MACHINE bit be set, but it turns // out that this bit is not required to be set. In fact, many modules from // the COM+ team do not have this bit set. return (m_pModuleRoot && !m_pProcess && !(m_dwFlags & DWSF_DWI) && (m_pModuleRoot->GetCharacteristics() & IMAGE_FILE_EXECUTABLE_IMAGE) && !(m_pModuleRoot->GetCharacteristics() & IMAGE_FILE_DLL) && #if defined(_IA64_) (m_pModuleRoot->GetMachineType() == IMAGE_FILE_MACHINE_IA64) && #elif defined(_X86_) (m_pModuleRoot->GetMachineType() == IMAGE_FILE_MACHINE_I386) && #elif defined(_ALPHA64_) // Must come before _ALPHA_ check (m_pModuleRoot->GetMachineType() == IMAGE_FILE_MACHINE_ALPHA64) && #elif defined(_ALPHA_) (m_pModuleRoot->GetMachineType() == IMAGE_FILE_MACHINE_ALPHA) && #elif defined(_AMD64_) (m_pModuleRoot->GetMachineType() == IMAGE_FILE_MACHINE_AMD64) && #else #error("Unknown Target Machine"); #endif (m_pModuleRoot->GetSubsystemType() != IMAGE_SUBSYSTEM_WINDOWS_OLD_CE_GUI) && (m_pModuleRoot->GetSubsystemType() != IMAGE_SUBSYSTEM_WINDOWS_CE_GUI)); }
c++
23
0.636991
87
48.034483
29
inline
<?php namespace KenticoCloud\Deliver\Helpers; class Helper { static protected $instance = null; static public function getInstance(){ $class = get_called_class(); if(!$class::$instance){ $class::$instance = new $class; } return $class::$instance; } }
php
11
0.725543
98
20.705882
17
starcoderdata
<?php namespace App\Http\Controllers\ValidationsApi\V1; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Exceptions\HttpResponseException; class MerchantsRequest extends FormRequest { /** * Baboon Script By [it v 1.6.37] * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Baboon Script By [it v 1.6.37] * Get the validation rules that apply to the request. * * @return array (onCreate,onUpdate,rules) methods */ protected function onCreate() { return [ 'mrchant_name'=>'required|string', 'mobile'=>'required|numeric', 'category_id'=>'required|integer|exists:categories,id', 'status'=>'required|string|in:yes,no', ]; } protected function onUpdate() { return [ 'mrchant_name'=>'required|string', 'mobile'=>'required|numeric', 'category_id'=>'required|integer|exists:categories,id', 'status'=>'required|string|in:yes,no', ]; } public function rules() { return request()->isMethod('put') || request()->isMethod('patch') ? $this->onUpdate() : $this->onCreate(); } /** * Baboon Script By [it v 1.6.37] * Get the validation attributes that apply to the request. * * @return array */ public function attributes() { return [ 'mrchant_name'=>trans('admin.mrchant_name'), 'mobile'=>trans('admin.mobile'), 'category_id'=>trans('admin.category_id'), 'status'=>trans('admin.status'), ]; } /** * Baboon Script By [it v 1.6.37] * response redirect if fails or failed request * * @return redirect */ public function response(array $errors) { return $this->ajax() || $this->wantsJson() ? response([ 'status' => false, 'StatusCode' => 422, 'StatusType' => 'Unprocessable', 'errors' => $errors, ], 422) : back()->withErrors($errors)->withInput(); // Redirect back } }
php
13
0.624882
69
23.686047
86
starcoderdata
#!/usr/bin/env python # This script is use to convert ori/traj file types to json # Author: 4/2/2015 import sys import os import json import math def convert_ori_to_json(input, output): print 'reading form', input print 'exporting to', output fin = open(input, 'r') fout = open(output, 'w') # read vsize vsize = int(fin.readline()) ori = {} vertices = [] faces = [] for i in range(0, vsize): coord = [float(x) for x in fin.readline().split()] vertices.append(coord) ori['vertices'] = vertices # read csize csize = int(fin.readline()) creases = [] for i in range(0, csize): items = fin.readline().split() crease = [int(items[0]), int(items[1]), float(items[2]), int(items[3]), int(items[4])] creases.append(crease) ori['creases'] = creases # read faces fsize = int(fin.readline()) faces = [] for i in range(0, fsize): face = [int(x) for x in fin.readline().split()] faces.append(face) ori['faces'] = faces # base face base_face_id = int(fin.readline()) ordered_faces = [] # ordered face list for i in range(0, fsize): ordered_faces.append(int(fin.readline())) ori['base_face_id'] = base_face_id ori['ordered_face_ids'] = ordered_faces # make it a little bit human readable json_str = json.dumps(ori, indent=2) fout.write(json_str) fin.close() fout.close() pass def convert_traj_to_json(input, output): print 'reading form', input print 'exporting to', output with open(input, 'r') as fin: with open(output, 'w') as fout: trajs = [] for line in fin: trajs.append([float(x)*math.pi/180.0 for x in line.split()]) t = {} t['trajs'] = trajs json_str = json.dumps(t) fout.write(json_str) pass def main(): if len(sys.argv) < 2: print sys.argv[0], '*.ori / *.trj' else: for filename in sys.argv: if filename == sys.argv[0]: continue if filename.startswith('-'): continue if filename.endswith('.ori'): convert_ori_to_json(filename, filename+'.json') elif filename.endswith('.trj'): convert_traj_to_json(filename, filename+'.json') elif filename.endswith('.json'): print 'skipping', filename else: print 'unknown file type', filename if __name__ == '__main__': main()
python
17
0.549231
94
22.645455
110
starcoderdata
// // BTEHomePageViewController.h // BTE // // Created by wangli on 2018/1/12. // Copyright © 2018年 wangli. All rights reserved. // #import "BHBaseController.h" #import "BTEHomePageTableView.h" @interface BTEHomePageViewController : BHBaseController @property (nonatomic,retain) BTEHomePageTableView *homePageTableView;//市场分析视图 @property (nonatomic, strong) UIViewController *luzDogVc; @property (nonatomic, strong) UIViewController *brandDogVc; @property (nonatomic, strong) UIViewController *contractDogVc; @property (nonatomic, strong) UIViewController *researchDogVc; @end
c
5
0.787879
82
28.857143
21
starcoderdata
static sqInt rgbMapfromto(sqInt sourcePixel, sqInt nBitsIn, sqInt nBitsOut) { sqInt srcPix; sqInt destPix; sqInt d; sqInt mask; if ((d = nBitsOut - nBitsIn) > 0) { /* Expand to more bits by zero-fill */ /* Transfer mask */ mask = (1 << nBitsIn) - 1; srcPix = sourcePixel << d; mask = mask << d; destPix = srcPix & mask; mask = mask << nBitsOut; srcPix = srcPix << d; return (destPix + (srcPix & mask)) + ((srcPix << d) & (mask << nBitsOut)); } else { if (d == 0) { if (nBitsIn == 5) { return sourcePixel & 32767; } if (nBitsIn == 8) { return sourcePixel & 16777215; } return sourcePixel; } if (sourcePixel == 0) { return sourcePixel; } d = nBitsIn - nBitsOut; /* Transfer mask */ mask = (1 << nBitsOut) - 1; srcPix = ((usqInt) sourcePixel) >> d; destPix = srcPix & mask; mask = mask << nBitsOut; srcPix = ((usqInt) srcPix) >> d; destPix = (destPix + (srcPix & mask)) + ((((usqInt) srcPix) >> d) & (mask << nBitsOut)); if (destPix == 0) { return 1; } return destPix; } }
c
16
0.543907
90
21.787234
47
inline
<?php namespace Database\Seeders; use App\Models\Addon; use Illuminate\Database\Seeder; class AddonsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Addon::create([ 'name' => 'Sir', ]); Addon::create([ 'name' => ' ]); Addon::create([ 'name' => 'Šunka', ]); Addon::create([ 'name' => 'Kulen', ]); Addon::create([ 'name' => 'Pančeta', ]); Addon::create([ 'name' => 'Pečenica', ]); Addon::create([ 'name' => ' ]); Addon::create([ 'name' => ' ]); Addon::create([ 'name' => 'Pečurke', ]); Addon::create([ 'name' => 'Masline', ]); Addon::create([ 'name' => 'Jaje', ]); } }
php
12
0.397759
59
16.274194
62
starcoderdata
import re import subprocess import requests class TestRunner: log_url = 'https://api.travis-ci.{urlsuffix}/v3/job/{job}/log.txt' line_regex = r'^(ERROR|FAIL): (.*?) \((.*?)\)' def __init__(self, manage_path: str, pipenv: bool, fail_only: bool, error_only: bool, dry: bool): self.pipenv = pipenv self.manage_path = manage_path self.failed_only = fail_only self.errored_only = error_only self.dry = dry self.errored: list = [] self.failed: list = [] def get_tests(self, job_num: int, url_suffix: str) -> bool: rawlog_url = self.log_url.format( job=job_num, urlsuffix=url_suffix ) line_regex = re.compile(self.line_regex) response = requests.get(rawlog_url) if response.status_code == 200: lines = response.text.split('\n') for line in lines: match = line_regex.match(line) if match: fail_type = match.group(1) test_function = match.group(2) test_class = match.group(3) full_test = test_class + '.' + test_function if fail_type == 'ERROR': self.errored.append(full_test) else: self.failed.append(full_test) return True print('Request for {} failed :('.format(rawlog_url)) return False def run_tests(self) -> None: tests = self.tests_to_run command = ['python', 'manage.py', 'test'] + tests if self.pipenv: command = ['pipenv', 'run'] + command if self.dry: print(command) else: subprocess.run(command, cwd=self.manage_path) @property def tests_to_run(self) -> list: if self.failed_only: return self.failed if self.errored_only: return self.errored return self.failed + self.errored
python
18
0.516953
70
28.492754
69
starcoderdata
const BASE_URL = 'https://cms.miayam.io/wp-json/wp/v2'; const POSTS_API = `${BASE_URL}/posts?orderby=date&order=desc`; const TAGS_API = `${BASE_URL}/tags`; const Cache = require('@11ty/eleventy-cache-assets'); const fetch = require('node-fetch'); const chunk = require('lodash.chunk'); const highlight = require('./highlight'); const getTags = async () => { // Get unique list of tags try { const json = await Cache(TAGS_API,{ duration: '30m', type: 'json' }); const tagsFromAPI = json.map(item => ({ id: item.id, name: item.slug, wording: item.name, description: item.description, href: `/tags/${item.slug}/` })); const customTag = { id: 0, name: 'all', wording: 'All', description: 'All posts.', href: '/' }; // Return formatted data. return [ customTag, ...tagsFromAPI ]; } catch (err) { console.log(`WordPress API call failed: ${err}`); return null; } } // Fetch number of WordPress post pages. const getTotalPages = async () => { try { const res = await fetch(`${POSTS_API}&_fields=id&page=1`); return res.headers.get('x-wp-totalpages') || 0; } catch(err) { console.log(`WordPress API call failed: ${err}`); return 0; } }; // Fetch list of WordPress posts. const getPosts = async (page = 1) => { try { const posts = await Cache(`${POSTS_API}&page=${page}`, { duration: '30m', type: 'json' }); // Return formatted data. return formatData(posts); } catch (err) { console.log(`WordPress API call failed: ${err}`); return null; } }; const appendPrevAndNextItemByTag = ({ data, tags }) => { const normalizedData = data; const normalizedTags = tags; normalizedTags.forEach((tag) => { const isUntagged = tag.id === 0 ; const taggedItems = isUntagged ? data : data.filter(item => item.tags.includes(tag.id)); taggedItems.forEach((taggedItem, index, thisArray) => { const next = thisArray[index - 1]; // Because it's in descending order const prev = thisArray[index + 1]; // Because it's in descending order const labels = taggedItem.tags.map(tagId => tags.find(tag => tag.id === tagId).name); taggedItem["prev"] = {...taggedItem["prev"], [tag.name]: prev}; taggedItem["next"] = {...taggedItem["next"], [tag.name]: next}; taggedItem["labels"] = labels; const position = normalizedData.findIndex((item) => item.id === taggedItem.id); normalizedData[position] = taggedItem; }); }); return normalizedData; }; const categorizeDataByTag = ({ data, tags, paginationSize }) => { const tagMap = []; tags.forEach(tag => { const taggedItems = tag.id === 0 ? data : data.filter(item => item.tags.includes(tag.id)); const pagedItems = chunk(taggedItems, paginationSize); pagedItems.forEach((pagedItem, index) => { const subPath = tag.name === 'all' ? '' : `/tags/${tag.name}`; const href = `${subPath}${index ? `/${index + 1}/` : '/'}`; tagMap.push({ tagName: tag.name, tagWording: tag.wording, pageNumber: index, pageData: pagedItem, href: href, pagination: { total: pagedItems.length, baseLink: subPath, currentIndex: index, articlesCount: pagedItem.length } }); }); }); return tagMap; }; // Strip HTML tags const formatExcerpt = (str) => { const excerptContent = str .replace(/( '\n') .replace(/( .split(' ') .slice(0, 20) .join(' '); return `${excerptContent} [&hellip;]`; }; // Format data const formatData = (data) => { return data .filter(p => p.content.rendered && !p.content.protected) .map(p => { return { id: p.id, url: `/articles/${p.slug}`, slug: p.slug, date: p.date, formattedDate: (new Date(p.date)).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric'}), title: p.title.rendered, content: highlight(p.content.rendered), excerpt: formatExcerpt(highlight(p.excerpt.rendered)), tags: p.tags, }; }); }; module.exports = { appendPrevAndNextItemByTag, categorizeDataByTag, getTotalPages, getPosts, getTags };
javascript
26
0.585216
118
25.889571
163
starcoderdata
# Generated by Django 3.1.6 on 2021-02-19 13:58 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='EmailHeaders', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uid', models.IntegerField()), ('seen', models.BooleanField(default=False)), ('subject', models.CharField(blank=True, max_length=255)), ('sender_name', models.CharField(blank=True, max_length=255)), ('sender_email', models.EmailField(max_length=254)), ('size', models.IntegerField()), ('received_at', models.DateTimeField()), ('message_id', models.CharField(max_length=255)), ('folder', models.CharField(max_length=255)), ('receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Reference', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('reference', models.CharField(max_length=255)), ('email_header', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emails.emailheaders')), ], ), migrations.CreateModel( name='Newsletter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('list_unsubscribe', models.CharField(max_length=255)), ('one_click', models.BooleanField(default=False)), ('unsubscribed', models.BooleanField(default=False)), ('sender_email', models.EmailField(max_length=254)), ('receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='InReplyTo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('in_reply_to', models.CharField(max_length=255)), ('email_header', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emails.emailheaders')), ], ), migrations.AddField( model_name='emailheaders', name='unsubscribe', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emails.newsletter'), ), migrations.CreateModel( name='Attachment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('size', models.IntegerField()), ('email_header', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emails.emailheaders')), ], ), ]
python
18
0.577047
128
45.040541
74
starcoderdata
float MSLayersAtAngle::sumX0D(int il, int ol, const PixelRecoPointRZ& pointI, const PixelRecoPointRZ& pointO) const { // if layer not at this angle (WHY???) revert to slow comp if (il >= int(indeces.size()) || ol >= int(indeces.size()) || indeces[il] < 0 || indeces[ol] < 0) return sumX0D(pointI, pointO); LayerItr iI = theLayers.begin() + indeces[il]; LayerItr iO = theLayers.begin() + indeces[ol]; return sqrt(sum2RmRn(iI, iO, pointO.r(), SimpleLineRZ(pointI, pointO))); }
c++
13
0.677551
117
48.1
10
inline
/* * SPDX-License-Identifier: Apache-2.0 * * Name: * C Example code for MOXA Buzzer Library * * Description: * Example code for demonstrating the usage of MOXA Buzzer Library in C * * Authors: * 2018 */ #include #include #include #include #define EXECUTION_TIME 11 extern char mx_errmsg[256]; int main(int argc, char *argv[]) { unsigned long duration; int ret; if (argc != 2) { fprintf(stderr, "Usage: %s argv[0]); fprintf(stderr, "\t0: Keep beeping\n"); fprintf(stderr, "\t1 ~ 10: in seconds\n"); fprintf(stderr, "\tNote: the range of duration is 1 ~ 60 for\n"); fprintf(stderr, "\t Moxa buzzer control library\n"); exit(99); } duration = atol(argv[1]); ret = mx_buzzer_init(); if (ret < 0) { fprintf(stderr, "Initialize Moxa buzzer control library failed\n"); fprintf(stderr, "Error code: %d\n", ret); fprintf(stderr, "Error message: %s\n", mx_errmsg); exit(1); } printf("Testing Buzzer:\n"); printf("\tThe process will be executed for %d seconds.\n\n", EXECUTION_TIME); if (duration > 10) { fprintf(stderr, "Duration out of range: must be 0 ~ 10\n"); exit(1); } else if (duration > 0) { printf("Play Buzzer for %ld seconds.\n", duration); } else { printf("Keep playing Buzzer.\n"); } ret = mx_buzzer_play_sound(duration); if (ret < 0) { fprintf(stderr, "Failed to play Buzzer.\n"); fprintf(stderr, "Error code: %d\n", ret); fprintf(stderr, "Error message: %s\n", mx_errmsg); exit(1); } printf("Sleep for %d seconds.\n", EXECUTION_TIME); sleep(EXECUTION_TIME); if (duration == 0) { printf("\nStop Buzzer.\n"); ret = mx_buzzer_stop_sound(); if (ret < 0) { fprintf(stderr, "Failed to stop Buzzer.\n"); fprintf(stderr, "Error code: %d\n", ret); fprintf(stderr, "Error message: %s\n", mx_errmsg); exit(1); } } exit(0); }
c
12
0.636082
78
22.658537
82
starcoderdata
from enum import IntFlag __all__ = ("ZipFlags", "ZIP_FL") class ZipFlags(IntFlag): nocase = 1 nodir = 1 << 1 compressed = 1 << 2 unchanged = 1 << 3 recompress = 1 << 4 encrypted = 1 << 5 enc_guess = 0 enc_raw = 1 << 6 enc_strict = 1 << 7 local = 1 << 8 central = 1 << 9 enc_utf_8 = 1 << 11 enc_cp437 = 1 << 12 overwrite = 1 << 13 ZIP_FL = ZipFlags
python
6
0.586035
33
15.708333
24
starcoderdata
def __enter__(self) -> None: """ Enter method for context manager Args: N/A Returns: None Raises: N/A """ def patched_open(cls: Driver) -> None: """ Patched Driver.open method Patched at the driver and dealing w/ the on open/auth things as this way we never have to think about which transport is being used Args: cls: scrapli Drive self Returns: None Raises: N/A """ instance_name = self.create_instance_name(scrapli_conn=cls) connection_profile = self.create_connection_profile(scrapli_conn=cls) instance_object = ScrapliReplayInstance( replay_mode=self.replay_mode, connection_profile=connection_profile, replay_session=self.replay_session.get(instance_name, {}), ) self.wrapped_instances[instance_name] = instance_object if self.replay_mode == ReplayMode.REPLAY: instance_object.setup_replay_mode(scrapli_conn=cls) else: if self._block_network is True: # if block network is true and we got here then there is no session recorded, so # we need to skip this test pytest.skip( "scrapli-replay block-network is True, no session recorded, " "skipping test..." ) # if we are not in replay mode, we are in record or overwrite (same/same) so setup # the record read/write channel methods and then do "normal" stuff instance_object.setup_record_mode(scrapli_conn=cls) cls.transport.open() cls._pre_open_closing_log(closing=False) # pylint: disable=W0212 if cls.transport_name in ("system",) and not cls.auth_bypass: cls.channel.channel_authenticate_ssh( auth_password=cls.auth_password, auth_private_key_passphrase=cls.auth_private_key_passphrase, ) if ( cls.transport_name in ( "telnet", "asynctelnet", ) and not cls.auth_bypass ): cls.channel.channel_authenticate_telnet( auth_username=cls.auth_username, auth_password=cls.auth_password ) if self.replay_mode == ReplayMode.RECORD: instance_object.telnet_patch_update_log(auth_username=cls.auth_username) if cls.on_open: cls.on_open(cls) cls._post_open_closing_log(closing=False) # pylint: disable=W0212 self._patched_open = mock.patch.object( target=scrapli.driver.base.sync_driver.Driver, attribute="open", new=patched_open ) self._patched_open.start()
python
15
0.521122
100
34.25
88
inline
def base_app(instance_path): """Flask application fixture.""" app_ = Flask('testapp', instance_path=instance_path) app_.config.update( SECRET_KEY='SECRET_KEY', TESTING=True, REST_ENABLE_CSRF=False, ) @app_.route('/ping') def ping(): return 'ping' return app_
python
8
0.578125
56
21.928571
14
inline
package com.dudu.chat; import com.dudu.common.StandardObjectMapper; import com.dudu.database.DBHelper; import com.dudu.database.StoredProcedure; import com.dudu.database.ZetaMap; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import javax.sql.DataSource; import java.sql.Connection; import java.util.Date; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * We use SQL Server to store data. * * We deploy write through policy for managing new messages. * New messages are written into both SQL server and redis */ public class PersistentRedisChatRoom extends RedisChatRoom { private static final Logger logger = LogManager.getLogger(PersistentRedisChatRoom.class); private static final ObjectMapper objectMapper = StandardObjectMapper.getInstance(); private static ChatParticipant NULL_PARTICIPANT = new ChatParticipant() {{ setParticipantId(-520); }}; private static ChatMessage NULL_MESSAGE = new ChatMessage() {{ setMessageId(-520); }}; private DataSource source; // time to live private int ttl = 2*60*60; private BlockingQueue workingQueue; private ThreadPoolExecutor threadPoolExecutor; private MonitorThread monitorThread; /** * load from an existing room * * @param roomId * @param jedisPool * @param source where messages will be stored. * @throws Exception */ public PersistentRedisChatRoom(long roomId, JedisPool jedisPool, DataSource source) { super(String.valueOf(roomId), jedisPool); this.source = source; this.workingQueue = new ArrayBlockingQueue<>(100); this.threadPoolExecutor = new ThreadPoolExecutor(1, 4, 1, TimeUnit.MINUTES, workingQueue); this.monitorThread = new MonitorThread(); this.monitorThread.start(); checkCache(); } /** * create a new room * * @param jedisPool * @param source * @param roomName * @throws Exception */ public PersistentRedisChatRoom(JedisPool jedisPool, DataSource source, String roomName) throws Exception { super(jedisPool); this.source = source; this.workingQueue = new ArrayBlockingQueue<>(100); this.threadPoolExecutor = new ThreadPoolExecutor(1, 4, 1, TimeUnit.MINUTES, workingQueue); this.monitorThread = new MonitorThread(); this.monitorThread.start(); try (Connection conn = source.getConnection(); Jedis jedis = jedisPool.getResource()) { // ask for a room id from database StoredProcedure sp = new StoredProcedure(conn, "sp_ChatRoomCreate"); sp.addParameter("ChatRoomName", roomName); List zmaps = sp.execToZetaMaps(); long roomId = zmaps.get(0).getLong("RoomId", 0); if (roomId == 0) { logger.error("Failed to create a new room"); throw new IllegalArgumentException(""); } // move to the newly created room this.setRoomId(String.valueOf(roomId)); // set up cache of this room jedis.hset(redisKeyParticipants(), String.valueOf(NULL_PARTICIPANT.getParticipantId()), objectMapper.writeValueAsString(NULL_PARTICIPANT)); jedis.expire(redisKeyParticipants(), ttl); jedis.lpush(redisKeyMessages(), objectMapper.writeValueAsString(NULL_MESSAGE)); jedis.expire(redisKeyMessages(), ttl); } } /** * * @param participant */ @Override public void join(ChatParticipant participant) { checkCache(); if (participant.getParticipantId() == 0) { // join in database try (Connection conn = source.getConnection()) { StoredProcedure sp = new StoredProcedure(conn, "sp_ChatRoomUserJoin"); sp.addParameter("RoomId", participant.getRoomId()); sp.addParameter("UserId", participant.getUserId()); List zetaMaps = sp.execToZetaMaps(); int error = zetaMaps.get(0).getInt("Error", -1); if (error != 0) throw new RuntimeException("sp_ChatRoomUserJoin: Error=" + error); participant = ChatParticipant.from(zetaMaps.get(0)); } catch (Exception e) { logger.error("Failed to join the user: UserId=" + participant.getUserId() + ", RoomId=" + participant.getRoomId()); return; } } super.join(participant); } @Override public void exit(ChatParticipant participant) { checkCache(); if (participant.getParticipantId() != 0) { try (Connection conn = source.getConnection()) { StoredProcedure sp = new StoredProcedure(conn, "sp_ChatRoomUserExit"); sp.addParameter("ParticipantId", participant.getParticipantId()); int error = sp.execToZetaMaps().get(0).getInt("Error", -1); if (error != 0) throw new RuntimeException("sp_ChatRoomUserExit: Error=" + error); } catch (Exception e) { logger.error("Failed to exit the user: ParticipantId="+participant.getParticipantId()); return; } } super.exit(participant); } @Override public void publish(ChatMessage message) { checkCache(); super.publish(message); // asynchronous write to database threadPoolExecutor.execute(() -> { try (Connection conn = source.getConnection()) { StoredProcedure sp = new StoredProcedure(conn, "sp_ChatRoomNewMessage"); sp.addParameter("PariticpantId", message.getParticipantId()); sp.addParameter("Message", message.getMessage()); sp.addParameter("CreatedAt", message.getCreatedAt()); int error = sp.execToZetaMaps().get(0).getInt("Error", -1); if (error != 0) throw new RuntimeException("sp_ChatRoomNewMessage. Error=" + error); } catch (Exception e) { logger.error("Failed to save a message to sql server: ", e); } }); } /** * MUST invoke this before method calls that use cache. * * check if room is in the cache. bring to cache if it is a missing hit. */ private void checkCache() { try (Connection conn = source.getConnection(); Jedis jedis = jedisPool.getResource()) { if (!jedis.exists(redisKeyParticipants())) { jedis.hset(redisKeyParticipants(), String.valueOf(NULL_PARTICIPANT.getParticipantId()), objectMapper.writeValueAsString(NULL_PARTICIPANT)); jedis.expire(redisKeyParticipants(), ttl); // participants from database String select = "SELECT * FROM ChatRoomParticipants WHERE RoomId = ? AND Exited = 0"; List zetaMaps = DBHelper.getHelper().execToZetaMaps(conn, select, roomId); for (ZetaMap zetaMap : zetaMaps) { ChatParticipant participant = ChatParticipant.from(zetaMap); jedis.hset(redisKeyParticipants(), String.valueOf(participant.getParticipantId()), objectMapper.writeValueAsString(participant)); } } if (!jedis.exists(redisKeyMessages())) { jedis.lpush(redisKeyMessages(), objectMapper.writeValueAsString(NULL_MESSAGE)); jedis.expire(redisKeyMessages(), ttl); // messages from database String select = "SELECT m.* FROM ChatRoomMessages m " + " INNER JOIN ChatRoomParticipants p ON p.ParticipantId = m.ParticipantId " + " INNER JOIN ChatRooms r ON r.RoomId = p.RoomId " + "WHERE r.RoomId = ?"; List zetaMaps = DBHelper.getHelper().execToZetaMaps(conn, select, roomId); for (ZetaMap zetaMap: zetaMaps) { ChatMessage chatMessage = ChatMessage.from(zetaMap); jedis.lpush(redisKeyMessages(), objectMapper.writeValueAsString(chatMessage)); } } } catch (Exception e) { logger.error("Failed to check on cache."); } } @Override public List getAllMessages() { checkCache(); List messages = super.getAllMessages(); messages.removeIf((msg) -> msg.getMessageId() == NULL_MESSAGE.getMessageId()); return messages; } @Override public List getAllParticipants() { checkCache(); List participants = super.getAllParticipants(); participants.removeIf((p) -> p.getParticipantId() == NULL_PARTICIPANT.getParticipantId()); return participants; } public ChatParticipant createNewParticipant(long userId) { ChatParticipant chatParticipant = new ChatParticipant(); chatParticipant.setUserId(userId); chatParticipant.setRoomId(Long.parseLong(roomId)); return chatParticipant; } public ChatMessage createNewMessage(long participantId, String message) { ChatMessage chatMessage = new ChatMessage(); chatMessage.setParticipantId(participantId); chatMessage.setMessage(message); chatMessage.setCreatedAt(new Date()); return chatMessage; } public void close() { super.close(); monitorThread.stop = true; } private class MonitorThread extends Thread { private boolean stop = false; @Override public void run() { super.run(); try { while (!stop) { sleep(5000); logger.info("Number of messages queued up: " + workingQueue.size()); } } catch (Exception ignored) { } } } }
java
18
0.615029
155
36.472924
277
starcoderdata
<?php namespace BrightTALK\lib\ACSQueryBuilder\Expression; abstract class Composite implements ExpressionInterface { /** * @var string */ protected $preSeparator = '('; /** * @var string */ protected $separator = ' '; /** * @var string */ protected $postSeparator = ')'; /** * @var array */ protected $parts = array(); /** * @param array $parts */ public function __construct(array $parts = array()) { $this->parts = $parts; } /** * @return string */ public function getPreSeparator() { return $this->preSeparator; } /** * @return string */ public function getSeparator() { return $this->separator; } /** * @return string */ public function getPostSeparator() { return $this->postSeparator; } /** * @return array */ public function getParts() { return $this->parts; } /** * Addend a new part to an existing expression * * @param ExpressionInterface $part * @return Composite */ public function appendPart(ExpressionInterface $part) { $this->parts[] = $part; return $this; } /** * @return string */ public function __toString() { return $this->preSeparator . implode($this->separator, $this->parts) . $this->postSeparator; } }
php
13
0.521769
100
16.104651
86
starcoderdata
<?php namespace Module\WeChat\Domain\Model; use Zodream\ThirdParty\WeChat\EventEnum; /** * 微信公众号用户资料表 * 从公众号中拉取的数据可以保存在此表 * @property integer $id * @property integer $wid * @property string $event * @property string $keywords * @property integer $match * @property integer $created_at * @property integer $updated_at */ class ReplyModel extends EditorModel { /** * 激活状态 */ const STATUS_ACTIVE = 1; /** * 禁用状态 */ const STATUS_DISABLED = 0; const PROCESSOR_DEFAULT = 'process'; public static $statuses = [ self::STATUS_ACTIVE => '启用', self::STATUS_DISABLED => '禁用' ]; /** * @inheritdoc */ public static function tableName() { return 'wechat_reply'; } protected function rules() { return [ 'wid' => 'required|int', 'event' => 'required|string:0,20', 'keywords' => 'string:0,60', 'match' => 'required|int:0,9', 'content' => 'required', 'type' => 'required|string:0,10', 'created_at' => 'int', 'updated_at' => 'int', ]; } /** * @inheritdoc */ public function labels() { return [ 'id' => 'ID', 'wid' => '所属微信公众号ID', 'event' => '事件', 'event_name' => '事件名', 'keywords' => '关键字', 'match' => '匹配方式', 'content' => 'Content', 'type' => 'Type', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } public static function getMessageReply($wid) { $data = static::where('event', EventEnum::Message) ->where('wid', $wid) ->orderBy('`match`', 'asc') ->orderBy('updated_at', 'asc')->get('id', 'keywords', '`match`'); $args = []; foreach ($data as $item) { foreach (explode(',', $item->keywords) as $val) { $val = trim($val); if (!empty($val)){ $args[$val] = [ 'id' => $item->id, 'match' => $item->match ]; } } } return $args; } public static function cacheReply($wid, $refresh = false) { $key = 'wx_reply_'. $wid; if ($refresh) { cache()->set($key, static::getMessageReply($wid)); } return cache()->getOrSet($key, function () use ($wid) { return static::getMessageReply($wid); }); } /** * @param $wid * @param $content * @return int */ public static function findIdWithCache($wid, $content) { $data = self::cacheReply($wid); if (isset($data[$content])) { return $data[$content]['id']; } foreach ($data as $key => $item) { if ($item['match'] > 0) { continue; } if (strpos($content, $key.'') !== false) { return $item['id']; } } return 0; } /** * @param $wid * @param $content * @return ReplyModel|null */ public static function findWithCache($wid, $content) { $id = self::findIdWithCache($wid, $content); return $id > 0 ? static::where('wid', $wid)->where('id', $id)->first() : null; } public static function findWithEvent($event, $wid) { return static::where('event', $event) ->where('wid', $wid)->first(); } }
php
17
0.460977
86
25.007299
137
starcoderdata
def generateConvDict(unitScale): conv = {} # unit conversion dictionary conv.update([['GPa', (10**9)*(unitScale**2)], # to N/length^2 ['MPa', (10**6)*(unitScale**2)], # to N/length^2 ['kPa', (10**3)*(unitScale**2)], # to N/length^2 ['pascal', unitScale**2], # to N/length^2 ['Pa', unitScale**2], # to N/length^2 ['g/cm^3', (10**6)*(unitScale**3)], # to (N-s^2/length)/length^3 ['kg/m^3', (10**-3)*(unitScale**3)], # to (N-s^2/length)/length^3 ['kg/mm^3', (10**6)*(unitScale**3)], # to (N-s^2/length)/length^3 ['N', 1], # to N ['kN', 10**3], # to N ['N', 1], # to N ['N-mm', (10**-3)*(unitScale**-1)], # to N-length ['m/s^2', 1], # to length/s^2 ['mm/s^2', (10**-3)/unitScale], # to length/s^2 ['N/A', 1], # dimensionless ['1/C', 1], # to 1/C ['C', 1], # to Celsius (temperature values will be converted somewhere else) ['1/K', 1], # to 1/K ['K', 1], # to Kelvin (temperature values will be converted somewhere else) ['F', 1], # to Fahrenheit (temperature values will be converted somewhere else) ['W/(m*K)', unitScale], # to (N-length/s)/(K-length) ['J/(kg*K)', unitScale**-2], # to (N-length)/(K-(N-s^2/length)) ['J/(kg-K)', unitScale**-2]]) # to (N-length)/(K-(N-s^2/length)) return conv
python
12
0.289941
120
85.703704
27
inline
public void delete(final int offset, final int length) { // run in dispatch thread runMapping(new MapVoidAction("remove") { // NOI18N @Override public void map() { try { txtEditorPane().getDocument().remove(offset, length); } catch (BadLocationException e) { throw new JemmyException("Cannot delete " + length + " characters from position " + offset + ".", e); } } }); }
java
21
0.450172
73
35.4375
16
inline
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ListaPreco extends Model { protected $fillable = [ 'nome', 'percentual_alteracao' ]; public function itens(){ return $this->hasMany('App\ProdutoListaPreco', 'lista_id', 'id'); } }
php
10
0.667897
73
15.9375
16
starcoderdata
namespace itk { /** \class FlatStructuringElement * \brief A class to support a variety of flat structuring elements, * including versions created by decomposition of lines. * * FlatStructuringElement provides several static methods, which can * be used to create a structuring element with a particular shape, * size, etc. Currently, those methods allow to create a ball, a box, * a cross structuring element, and let create a structuring element * based on an image. * * \ingroup ITKMathematicalMorphology * * \wiki * \wikiexample{Morphology/FlatStructuringElement,Erode a binary image using a flat (box) structuring element} * \endwiki */ template< unsigned int VDimension > class FlatStructuringElement:public Neighborhood< bool, VDimension > { public: /** Standard class typedefs. */ typedef FlatStructuringElement< VDimension > Self; typedef Neighborhood< bool, VDimension > Superclass; /** External support for pixel type. */ typedef typename Superclass::PixelType PixelType; /** Iterator typedef support. Note the naming is intentional, i.e., * AllocatorType::iterator and AllocatorType::const_iterator, because the * allocator may be a vnl object or other type, which uses this form. */ typedef typename Superclass::Iterator Iterator; typedef typename Superclass::ConstIterator ConstIterator; /** Size and value typedef support. */ typedef typename Superclass::SizeType SizeType; typedef typename Superclass::OffsetType OffsetType; /** Radius typedef support. */ typedef typename Superclass::RadiusType RadiusType; /** External slice iterator type typedef support. */ typedef typename Superclass::SliceIteratorType SliceIteratorType; /** External support for dimensionality. */ itkStaticConstMacro(NeighborhoodDimension, unsigned int, VDimension); typedef Vector< float, VDimension > LType; typedef std::vector< LType > DecompType; /** Default destructor. */ virtual ~FlatStructuringElement() {} /** Default consructor. */ FlatStructuringElement() { m_Decomposable = false; } /** Various constructors */ /** * Create a box structuring element. The structuring element is * is decomposable. */ static Self Box(RadiusType radius); /** Create a ball structuring element */ static Self Ball(RadiusType radius); /** Create a cross structuring element */ static Self Cross(RadiusType radius); /** Create an annulus structuring element */ static Self Annulus(RadiusType radius, unsigned int thickness = 1, bool includeCenter = false); /** * Create a polygon structuring element. The structuring element is * is decomposable. * lines is the number of elements in the decomposition */ static Self Polygon(RadiusType radius, unsigned lines); /** * Returns wether the structuring element is decomposable or not. If the * structuring is decomposable, the set of lines associated with the * structuring may be used by an algorithm instead of the standard buffer. */ bool GetDecomposable() const { return m_Decomposable; } void SetDecomposable( bool v ) { m_Decomposable = v; } /** Return the lines associated with the structuring element */ const DecompType & GetLines() const { return ( m_Lines ); } void AddLine( LType l ) { m_Lines.push_back(l); } bool CheckParallel(LType NewVec) const; /** * Fill the buffer of the structuring element based on the lines * associated to the structuring element */ void ComputeBufferFromLines(); protected: void PrintSelf(std::ostream & os, Indent indent) const; private: bool m_Decomposable; DecompType m_Lines; template< unsigned int VDimension3 > struct StructuringElementFacet { Vector< float, VDimension3 > P1, P2, P3; }; typedef StructuringElementFacet< VDimension > FacetType; template<class TStructuringElement, class TRadius> static void GeneratePolygon(TStructuringElement & res, TRadius radius, unsigned lines); static void GeneratePolygon(itk::FlatStructuringElement<2> & res, itk::Size<2> radius, unsigned lines); static void GeneratePolygon(itk::FlatStructuringElement<3> & res, itk::Size<3> radius, unsigned lines); typedef Vector< float, 2 > LType2; typedef Vector< float, 3 > LType3; typedef StructuringElementFacet< 3 > FacetType3; }; }
c
11
0.716994
110
29.993007
143
inline
// Copyright (C) 2021 Control of Networked Systems, University of Klagenfurt, Austria. // // All rights reserved. // // This software is licensed under the terms of the BSD-2-Clause-License with // no commercial use allowed, the full terms of which are made available // in the LICENSE file. No license in patents is granted. // // You can contact the author at #ifndef GPS_CONVERSION_H #define GPS_CONVERSION_H #include namespace mars { /// /// \brief The GpsCoordinates struct /// struct GpsCoordinates { GpsCoordinates() = default; GpsCoordinates(double latitude, double longitude, double altitude) : latitude_(latitude), longitude_(longitude), altitude_(altitude) { } double latitude_{ 0 }; double longitude_{ 0 }; double altitude_{ 0 }; friend std::ostream& operator<<(std::ostream& out, const GpsCoordinates& coordinates); }; /// /// \brief The GpsConversion class /// /// \note (2006). Sigma-point Kalman filtering for integrated GPS and inertial navigation. /// class GpsConversion { public: GpsConversion(mars::GpsCoordinates coordinates); GpsConversion() = default; /// /// \brief get_enu get current GPS reference coordinates /// \param coordinates GPS coordinates /// \return ENU local position /// Eigen::Matrix<double, 3, 1> get_enu(mars::GpsCoordinates coordinates); /// /// \brief get_gps_reference /// \return GPS reference coordinates /// mars::GpsCoordinates get_gps_reference(); /// /// \brief set_gps_reference /// \param coordinates GPS coordinates /// void set_gps_reference(mars::GpsCoordinates coordinates); private: GpsCoordinates reference_; ///< GPS reference coordinates Eigen::Matrix3d ecef_ref_orientation_; Eigen::Matrix<double, 3, 1> ecef_ref_point_; bool reference_is_set{ false }; /// /// \brief deg2rad /// \param deg /// \return rad /// double deg2rad(const double& deg); /// /// \brief WGS84ToECEF World Geodetic System 1984 model (WGS-84) to Earth-Centered-Earth-Fixed (ECEF) /// \param coordinates GPS coordinates /// \return ecef position /// Eigen::Matrix<double, 3, 1> WGS84ToECEF(const mars::GpsCoordinates& coordinates); /// /// \brief ECEFToENU Earth-Centered-Earth-Fixed (ECEF) to East-North-Up (ENU) /// \param ecef ecef reference /// \return ENU local position /// Eigen::Matrix<double, 3, 1> ECEFToENU(const Eigen::Matrix<double, 3, 1>& ecef); /// /// \brief WGS84ToENU World Geodetic System 1984 model (WGS-84) to East-North-Up (ENU) based on given reference /// coordinates 'reference_' /// \param coordinates GPS coordinates /// \return ENU local position /// Eigen::Matrix<double, 3, 1> WGS84ToENU(const mars::GpsCoordinates& coordinates); }; } #endif // GPS_CONVERSION_H
c
15
0.692198
113
26.94
100
starcoderdata
//--------------------------------------------------------------------- // <copyright file="RandomIEnumerableStrategy.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // //--------------------------------------------------------------------- using System; using System.Collections.Generic; namespace Microsoft.SqlServer.Test.TestShell.Core.InputSpaceModeling { /// /// An exploration strategy for IEnumerable types which that returns one (or a fixed number of) random value(s) from the collection each time. /// /// <typeparam name="T">the type of the items of the collection. public class RandomIEnumerableStrategy : RandomStrategyFromCategory { /// /// Initializes a new instance of the <see cref="RandomIEnumerableStrategy&lt;T&gt;"/> class. /// /// <param name="items">The items. /// <exception cref="ArgumentNullException"><paramref name="items"/> is /// <exception cref="ArgumentOutOfRangeException"><paramref name="items"/> is empty. public RandomIEnumerableStrategy(Func<int, int> nextInt, params T[] items) : this(nextInt, (IEnumerable 1) { } /// /// Initializes a new instance of the <see cref="RandomIEnumerableStrategy&lt;T&gt;"/> class. /// /// <param name="items">The items. /// <exception cref="ArgumentNullException"><paramref name="items"/> is /// <exception cref="ArgumentOutOfRangeException"><paramref name="items"/> is empty. public RandomIEnumerableStrategy(Func<int, int> nextInt, IEnumerable items) : this(nextInt, items, 1) { } /// /// Initializes a new instance of the <see cref="RandomIEnumerableStrategy&lt;T&gt;"/> class. /// /// <param name="items">The items. /// <param name="numberOfValuesToReturn">The fixed number of random values to return each time (deafult is 1). /// <exception cref="ArgumentNullException"><paramref name="items"/> is /// <exception cref="ArgumentOutOfRangeException"><paramref name="items"/> is empty. /// <exception cref="ArgumentOutOfRangeException"><paramref name="numberOfValuesToReturn"/> is less than 1. public RandomIEnumerableStrategy(Func<int, int> nextInt, IEnumerable items, int numberOfValuesToReturn) : base(new PointCategory nextInt, items), numberOfValuesToReturn) { if (new List == 0) { throw new ArgumentOutOfRangeException("items", "The collection must have at least one value."); } } } }
c#
14
0.65742
143
47.775862
58
starcoderdata
using Livraria.Domain.Commands.Inputs; using Livraria.Domain.Handler; using Livraria.Domain.Interfaces.Repositories; using Livraria.Domain.Query; using Livraria.Infra.Interfaces.Commands; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; namespace LivrariaApi.Controllers { [Consumes("application/json")] [Produces("application/json")] [ApiController] public class LivroController : ControllerBase { private readonly ILivroRepository _repository; private readonly LivroHandler _handler; public LivroController(ILivroRepository repository, LivroHandler handler) { _repository = repository; _handler = handler; } [HttpGet] [Route("v1/livro/{id}")] public LivroQueryResult ObterLivro(long id) { return _repository.Obter(id); } [HttpGet] [Route("v1/livro")] public List ListarLivros() { return _repository.Listar(); } [HttpPost] [Route("v1/livro")] public ICommandResult Inserir([FromBody] AdicionarLivroCommand command) { return _handler.Handle(command); } [HttpPut] [Route("v1/livro/{id}")] public ICommandResult Atualizar(long id, [FromBody] AtualizarLivroCommand command) { command.Id = id; return _handler.Handle(command); } [HttpDelete] [Route("v1/livro/{id}")] public ICommandResult Excluir(long id) { var command = new ExcluirLivroCommand() { Id = id}; return _handler.Handle(command); } } }
c#
15
0.609049
90
26.365079
63
starcoderdata
<?php declare(strict_types=1); namespace Oro\Bundle\LayoutBundle\Command\Util; use phpDocumentor\Reflection\DocBlockFactory; use phpDocumentor\Reflection\Types\ContextFactory; /** * Extracts method information about php methods (Method description, arguments and return type and description). */ class MethodPhpDocExtractor { private DocBlockFactory $docBlockFactory; private ContextFactory $contextFactory; public function __construct() { $this->docBlockFactory = DocBlockFactory::createInstance(); $this->contextFactory = new ContextFactory(); } public function extractPublicMethodsInfo($object): array { $ro = new \ReflectionObject($object); $reflectionMethods = $ro->getMethods(\ReflectionMethod::IS_PUBLIC); $methods = []; foreach ($reflectionMethods as $reflectionMethod) { if (!preg_match('/^(get|has|is)(.+)$/i', $reflectionMethod->getName())) { continue; } $methods[] = $this->extractMethodInfo($reflectionMethod); } return $methods; } private function extractMethodInfo(\ReflectionMethod $reflectionMethod): array { $methodInfo = [ 'name' => $reflectionMethod->getName(), 'return' => [ 'type' => $reflectionMethod->getReturnType(), 'description' => '', ], 'arguments' => [], ]; $parameters = $reflectionMethod->getParameters(); foreach ($parameters as $parameter) { $parameterName = $parameter->getName(); $methodInfo['arguments'][$parameterName] = [ 'name' => $parameterName, 'type' => (string)$parameter->getType(), 'required' => !$parameter->isOptional(), 'description' => '', ]; if ($parameter->isOptional()) { $methodInfo['arguments'][$parameterName]['default'] = $parameter->getDefaultValue(); } } $docBlock = $this->docBlockFactory->create( $reflectionMethod, $this->contextFactory->createFromReflector($reflectionMethod) ); $methodInfo['description'] = trim($docBlock->getSummary()); $description = \trim((string)$docBlock->getDescription()); if (!empty($description)) { $methodInfo['description'] .= "\n".$description; } $docBlockParameters = $docBlock->getTagsByName('param'); /** @var \phpDocumentor\Reflection\DocBlock\Tags\Param $docBlockParameter */ foreach ($docBlockParameters as $docBlockParameter) { $variableName = $docBlockParameter->getVariableName(); $methodInfo['arguments'][$variableName]['type'] = (string)$docBlockParameter->getType(); $methodInfo['arguments'][$variableName]['description'] = (string)$docBlockParameter->getDescription(); } $docBlocksReturn = $docBlock->getTagsByName('return'); /** @var \phpDocumentor\Reflection\DocBlock\Tags\Return_ $docBlockReturn */ $docBlockReturn = empty($docBlocksReturn) ? null : $docBlocksReturn[0]; if (null !== $docBlockReturn) { $methodInfo['return']['type'] = (string)$docBlockReturn->getType(); $methodInfo['return']['description'] = (string)$docBlockReturn->getDescription(); } return $methodInfo; } }
php
15
0.598839
114
37.277778
90
starcoderdata
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //frontend route Route::get('/', 'homeController@index'); Route::get('/product_by_caregory/{id}', 'homeController@product_by_category'); Route::get('/product_by_manufacture/{id}', 'homeController@product_by_manufacture'); Route::get('/product_details/{id}', 'homeController@product_details'); //add to cart raout Route::get('/show_cart','CartController@show_cart'); Route::post('/add_to_cart', 'CartController@add_to_cart'); //backend route Route::get('/admin', 'adminController@index'); Route::get('/dashboard', 'superAdminController@index'); Route::post('/admin_dashboard', 'adminController@dashboard'); Route::get('/logout', 'superAdminController@logout'); //category related route //Route::get('/cat','categoryController@index'); //Route::get('/add_category','categoryController@create'); //Route::post('/save_category','categoryController@store'); //Route::get('/edit/{id}','categoryController@edit'); //Route::get('/delete_cat/{id}','categoryController@destroy'); //Route::get('/unactive_category/{category_id}','categoryController@unactive_category'); //Route::get('/active_category/{category_id}','categoryController@active_category'); Route::resource('/category','categoryController'); Route::get('/inactive/{id}', 'categoryController@category_inactive'); Route::get('/active/{id}', 'categoryController@category_active'); //manufacture rotes are here Route::resource('/manufacture','manufactureController'); Route::get('/inactive/{id}', 'manufactureController@manufacture_inactive'); Route::get('/active/{id}', 'manufactureController@manufacture_active'); //product route Route::resource('/product','productController'); Route::get('/inactive/{id}', 'productController@product_inactive'); Route::get('/active/{id}', 'productController@product_active'); Route::resource('/slider','sliderController'); Route::get('/inactive/{id}', 'sliderController@slider_inactive'); Route::get('/active/{id}', 'sliderController@slider_active');
php
6
0.685582
88
34
68
starcoderdata
package log // Logger interface is used to emit logging information about the // broker to common output(s). type Logger interface { CopyWith(prefix string, isDebug bool) Logger DebugEnabled() bool Prefix() string Debug(...interface{}) Debugf(string, ...interface{}) Debugln(...interface{}) Info(...interface{}) Infof(string, ...interface{}) Infoln(...interface{}) Warn(...interface{}) Warnf(string, ...interface{}) Warnln(...interface{}) Error(...interface{}) Errorf(string, ...interface{}) Errorln(...interface{}) Panic(...interface{}) Panicf(string, ...interface{}) Panicln(...interface{}) }
go
8
0.683077
65
20.666667
30
starcoderdata
require( "../setup" ); var fount = require( "fount" ); var path = require( "path" ); describe( "Server Index", function() { var registerSpy, dependecies; before( function() { dependecies = { "./init": sinon.stub(), "babel/register": {} }; registerSpy = sinon.spy( fount, "register" ); return proxyquire( path.resolve( __dirname, "../../index" ), dependecies ); } ); after( function() { registerSpy.restore(); } ); it( "should invoke the init factory", function() { dependecies[ "./init" ].should.be.calledOnce; } ); it( "should register postal", function() { registerSpy.should.be.calledWith( "postal" ); } ); it( "should register loggingCollectorConfig", function() { registerSpy.should.be.calledWith( "loggingCollectorConfig" ); } ); it( "should register ahpubsub", function() { registerSpy.should.be.calledWith( "ahpubsub" ); } ); } );
javascript
15
0.653217
77
28.580645
31
starcoderdata
package com.taoswork.tallycheck.info.descriptor.tab; import com.taoswork.tallycheck.info.descriptor.base.NamedOrdered; import com.taoswork.tallycheck.info.descriptor.group.IGroupInfo; import java.util.List; /** * Created by on 2015/8/9. */ public interface ITabInfo extends NamedOrdered { List getGroups(); }
java
6
0.784367
65
25.5
14
starcoderdata
package de.bergwerklabs.framework.commons.spigot.general; import java.security.SecureRandom; import java.util.NavigableMap; import java.util.Random; import java.util.TreeMap; /** * Created by on 22.06.2017. * * class is used for picking items randomly based on their weight. * * @author */ public class WeightedLootTable { private final NavigableMap<Double, T> map = new TreeMap<>(); private final Random random; private double total = 0; public WeightedLootTable() { this(new SecureRandom()); } /** @param random Used for choosing randomly. */ public WeightedLootTable(SecureRandom random) { this.random = random; } /** * Adds a new entry to the table. * * @param weight Weight the entry should have. * @param result Associated object * @return another {@code WeightedLootTable} for method chaining. */ public WeightedLootTable add(double weight, T result) { if (weight <= 0) return this; total += weight; map.put(total, result); return this; } /** * Gets randomly weight-based chosen entry. * * @return randomly weight-based chosen entry. */ public T next() { double value = random.nextDouble() * total; return map.higherEntry(value).getValue(); } }
java
10
0.678878
74
23.207547
53
starcoderdata
@Override void setAllStyles() { super.setAllStyles(); // axes this.xAxisTitleVisible = theme.isXAxisTitleVisible(); this.yAxisTitleVisible = theme.isYAxisTitleVisible(); this.axisTitleFont = theme.getAxisTitleFont(); this.xAxisTicksVisible = theme.isXAxisTicksVisible(); this.yAxisTicksVisible = theme.isYAxisTicksVisible(); this.axisTickLabelsFont = theme.getAxisTickLabelsFont(); this.axisTickMarkLength = theme.getAxisTickMarkLength(); this.axisTickPadding = theme.getAxisTickPadding(); this.axisTickMarksColor = theme.getAxisTickMarksColor(); this.axisTickMarksStroke = theme.getAxisTickMarksStroke(); this.axisTickLabelsColor = theme.getAxisTickLabelsColor(); this.isAxisTicksLineVisible = theme.isAxisTicksLineVisible(); this.isAxisTicksMarksVisible = theme.isAxisTicksMarksVisible(); this.plotMargin = theme.getPlotMargin(); this.axisTitlePadding = theme.getAxisTitlePadding(); this.xAxisTickMarkSpacingHint = theme.getXAxisTickMarkSpacingHint(); this.yAxisTickMarkSpacingHint = theme.getYAxisTickMarkSpacingHint(); this.isXAxisLogarithmic = false; this.isYAxisLogarithmic = false; this.xAxisMin = null; this.xAxisMax = null; this.yAxisMinMap.clear(); this.yAxisMaxMap.clear(); // Chart Plot Area /////////////////////////////// this.isPlotGridVerticalLinesVisible = theme.isPlotGridVerticalLinesVisible(); this.isPlotGridHorizontalLinesVisible = theme.isPlotGridHorizontalLinesVisible(); this.isPlotTicksMarksVisible = theme.isPlotTicksMarksVisible(); this.plotGridLinesColor = theme.getPlotGridLinesColor(); this.plotGridLinesStroke = theme.getPlotGridLinesStroke(); // Error Bars /////////////////////////////// this.errorBarsColor = theme.getErrorBarsColor(); this.isErrorBarsColorSeriesColor = theme.isErrorBarsColorSeriesColor(); // Formatting //////////////////////////////// this.locale = Locale.getDefault(); this.timezone = TimeZone.getDefault(); this.datePattern = null; // if not null, this override pattern will be used this.xAxisDecimalPattern = null; this.yAxisDecimalPattern = null; this.yAxisGroupDecimalPatternMap = new HashMap<>(); this.xAxisLogarithmicDecadeOnly = true; this.yAxisLogarithmicDecadeOnly = true; }
java
8
0.726293
85
44.509804
51
inline
package net.stemmaweb.model; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * This model contains a graph or subgraph returned from the Neo4j db * @author PSE FS 2015 Team2 */ @XmlRootElement @JsonInclude(Include.NON_NULL) public class GraphModel { /** * A set of readings that make up a portion of a variant graph. */ private HashSet readings; /** * A set of reading relations that make up a portion of a variant graph. */ private HashSet relations; /** * A set of sequence links that make up a portion of a variant graph. */ private HashSet sequences; public GraphModel(List readings, List relations, List sequences) { this(); this.readings.addAll(readings); this.relations.addAll(relations); this.sequences.addAll(sequences); } public GraphModel() { super(); this.readings = new HashSet<>(); this.relations = new HashSet<>(); this.sequences = new HashSet<>(); } public HashSet getReadings() { return readings; } public void setReadings(List readings) { this.readings.clear(); this.readings.addAll(readings); } public void addReadings(Set readings) { this.readings.addAll(readings); } public HashSet getRelations() { return relations; } public void setRelations(List relations) { this.relations.clear(); this.relations.addAll(relations); } public void addRelations(Set relations) { this.relations.addAll(relations); } public HashSet getSequences() { return sequences; } public void setSequences(List sequences) { this.sequences.clear(); this.sequences.addAll(sequences); } public void addSequences(Set sequences) { this.sequences.addAll(sequences); } }
java
8
0.687637
114
27.772152
79
starcoderdata
func (r *Root) ValidKey(keyID string, role string) bool { // Checks if id is a valid key for role if _, ok := r.Keys[keyID]; !ok { return false } rootRole, ok := r.Roles[role] if !ok { return false } for _, id := range rootRole.KeyIDs { if id == keyID { return true } } return false }
go
9
0.611842
57
18.0625
16
inline
import cv2 import numpy as np def cvt_back_ground(path,color): """ 功能:给证件照更换背景色(常用背景色红、白、蓝) 输入参数:path:照片路径 color:背景色 """ im=cv2.imread(path) im_hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV) aim=np.uint8([[im[0,0,:]]]) hsv_aim=cv2.cvtColor(aim,cv2.COLOR_BGR2HSV) mask=cv2.inRange(im_hsv,np.array([hsv_aim[0,0,0]-5,100,100]),np.array([hsv_aim[0,0,0]+5,255,255])) mask_inv=cv2.bitwise_not(mask) img1=cv2.bitwise_and(im,im,mask=mask_inv) bg=im.copy() rows,cols,channels=im.shape bg[:rows,:cols,:]=color img2=cv2.bitwise_and(bg,bg,mask=mask) img=cv2.add(img1,img2) image={'im':im,'im_hsv':im_hsv,'mask':mask,'img':img} for key in image: cv2.namedWindow(key) cv2.imshow(key,image[key]) cv2.waitKey(0) return img # 证件照换底片颜色 if __name__== '__main__': img = cvt_back_ground('cz2.jpg', [0, 0, 180])
python
12
0.607216
102
27.529412
34
starcoderdata
## Partially adapted from pumpy written by ## https://github.com/tomwphillips/pumpy """ Created on Mon Jun 28 08:14:00 2021 @author: """ from __future__ import print_function import serial class Chain(serial.Serial): """Create Chain object. Harvard syringe pumps are daisy chained together in a 'pump chain' off a single serial port. A pump address is set on each pump. You must first create a chain to which you then add Pump objects. Chain is a subclass of serial.Serial. Chain creates a serial.Serial instance with the required parameters, flushes input and output buffers (found during testing that this fixes a lot of problems) and logs creation of the Chain. """ def __init__(self, port): serial.Serial.__init__(self,port=port, stopbits=serial.STOPBITS_TWO, parity=serial.PARITY_NONE, timeout=2) self.flushOutput() self.flushInput() class Pump: """Create Pump object. Argument: Chain: pump chain Optional arguments: address: pump address. Default is 0. name: used in logging. Default is Pump 11. """ def __init__(self, chain, address=0, name='Pump 11'): self.name = name self.serialcon = chain self.address = '{0:02.0f}'.format(address) try: self.write('ADDRESS') resp = self.read() print(resp) if int(resp[0:2]) != int(self.address): raise PumpError('No response from pump at address %s' % self.address) except PumpError: self.serialcon.close() raise def __repr__(self): string = '' for attr in self.__dict__: string += '%s: %s\n' % (attr,self.__dict__[attr]) return string def write(self,command): self.serialcon.write(str.encode(self.address) + str.encode(command) + b'\r') def read(self): response = b"" while True: temp = self.serialcon.readline() if temp == b'00>': break response = response + temp return response.decode('utf-8') def logflowrate(self): self.write(self.address+'irate') resp = self.read() strings = resp.splitlines() flowrate = strings[-1] print(strings) return flowrate def setiflowrate(self, flowrate,unit): print(flowrate) self.write(self.address+'irate' + " "+ flowrate +" " +unit) class PumpError(Exception): pass
python
14
0.591533
114
30.506173
81
starcoderdata
const config = require('../config.json'); const bcrypt = require('bcryptjs'); const db = require('../_helpers/db'); const Item = db.Item; module.exports = { addItem, getAllItems, getUserItems, }; async function addItem(itemObj) { const item = await new Item(itemObj); await item.save(); } async function getAllItems() { const items = await Item.find({}, {_id:0}); return items.toObject(); } async function getUserItems(userId) { const items = await Item.find({userId:userId}); return items.toObject(); }
javascript
11
0.689981
48
19.346154
26
starcoderdata
#include "pch.h" #include "InstancingBuffer.h" #include "Engine.h" InstancingBuffer::InstancingBuffer() { } InstancingBuffer::~InstancingBuffer() { } void InstancingBuffer::Init(uint32 maxCount) { _maxCount = maxCount; const int32 bufferSize = sizeof(InstancingParams) * maxCount; D3D12_HEAP_PROPERTIES heapProperty = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD); D3D12_RESOURCE_DESC desc = CD3DX12_RESOURCE_DESC::Buffer(bufferSize); DEVICE->CreateCommittedResource( &heapProperty, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&_buffer)); } void InstancingBuffer::Clear() { _data.clear(); } void InstancingBuffer::AddData(InstancingParams& params) { _data.push_back(params); } void InstancingBuffer::PushData() { const uint32 dataCount = GetCount(); if (dataCount > _maxCount) Init(dataCount); const uint32 bufferSize = dataCount * sizeof(InstancingParams); void* dataBuffer = nullptr; D3D12_RANGE readRange{ 0, 0 }; _buffer->Map(0, &readRange, &dataBuffer); memcpy(dataBuffer, &_data[0], bufferSize); _buffer->Unmap(0, nullptr); _bufferView.BufferLocation = _buffer->GetGPUVirtualAddress(); _bufferView.StrideInBytes = sizeof(InstancingParams); _bufferView.SizeInBytes = bufferSize; }
c++
9
0.743711
86
21.333333
57
starcoderdata
<?php /** * Summary * * Description * * @author */ namespace SudoCms\SiteBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Sudoux\Cms\SiteBundle\Entity\Domain; use Sudoux\Cms\SiteBundle\Form\DomainType; use Sudoux\Cms\SiteBundle\Entity\Site; use Doctrine\ORM\EntityRepository; use SudoCms\SiteBundle\Form\SettingsType; /** * Class SiteType extends AbstractType - Summary * * Description of this class * * @package SudoCms\SiteBundle\Form * @author */ class SiteType extends AbstractType { /** * @type \Sudoux\Cms\SiteBundle\Entity\Domain * @author */ private $primaryDomain; /** * @var \Sudoux\Cms\SiteBundle\Entity\Site * @author */ protected $site; /** * @param \Sudoux\Cms\SiteBundle\Entity\Site $site * @param \Sudoux\Cms\SiteBundle\Entity\Domain $primaryDomain */ public function __construct(Site $site, Domain $primaryDomain = null) { $this->site = $site; $this->primaryDomain = $primaryDomain; } /** * @param \Symfony\Component\Form\FormBuilderInterface $builder * @param array $options * @author */ public function buildForm(FormBuilderInterface $builder, array $options) { $site = $this->site; $builder ->add('name') ->add('primary_domain', new DomainType()) ->add('timezone', 'timezone', array( 'empty_value' => 'Select your timezone', 'preferred_choices' => array( 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Phoenix', 'America/Los_Angeles', 'America/Adak', 'Pacific/Honolulu', 'America/Anchorage' ) )) ->add('configure', 'checkbox', array( 'label' => 'Configure site now?', 'required' => false, )); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Sudoux\Cms\SiteBundle\Entity\Site' )); } public function getName() { return 'sudoux_mortgagebundle_sitetype'; } }
php
15
0.622699
76
21.372549
102
starcoderdata
(function(){ var now = new Date(); var hours = now.getHours(); var bodyClass = ''; var $greeting = document.getElementById('js_greeting'); var $body = document.getElementsByTagName("BODY")[0]; var greetingString = 'Hello!'; console.log(hours); if (hours > 20 || hours < 4) { bodyClass = 'night'; greetingString = 'Good night!'; } else if (hours > 16) { bodyClass = 'evening'; greetingString = 'Good evening!'; } else if (hours > 11) { bodyClass = 'noon'; greetingString = 'Good afternoon!'; } else if (hours > 3 ) { bodyClass = 'morning'; greetingString = 'Good morning!'; } if ($greeting !== null) $greeting.textContent = greetingString; if ($body !== null) $body.classList.add(bodyClass); }());
javascript
17
0.611549
65
25.275862
29
starcoderdata
// Copyright 2018 The gVisor 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 tcpip import ( "fmt" "time" "inet.af/netstack/sync" ) // stdClock implements Clock with the time package. // // +stateify savable type stdClock struct { // baseTime holds the time when the clock was constructed. // // This value is used to calculate the monotonic time from the time package. // As per https://golang.org/pkg/time/#hdr-Monotonic_Clocks, // // Operating systems provide both a “wall clock,” which is subject to // changes for clock synchronization, and a “monotonic clock,” which is not. // The general rule is that the wall clock is for telling time and the // monotonic clock is for measuring time. Rather than split the API, in this // package the Time returned by time.Now contains both a wall clock reading // and a monotonic clock reading; later time-telling operations use the wall // clock reading, but later time-measuring operations, specifically // comparisons and subtractions, use the monotonic clock reading. // // ... // // If Times t and u both contain monotonic clock readings, the operations // t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out using // the monotonic clock readings alone, ignoring the wall clock readings. If // either t or u contains no monotonic clock reading, these operations fall // back to using the wall clock readings. // // Given the above, we can safely conclude that time.Since(baseTime) will // return monotonically increasing values if we use time.Now() to set baseTime // at the time of clock construction. // // Note that time.Since(t) is shorthand for time.Now().Sub(t), as per // https://golang.org/pkg/time/#Since. baseTime time.Time `state:"nosave"` // monotonicOffset is the offset applied to the calculated monotonic time. // // monotonicOffset is assigned maxMonotonic after restore so that the // monotonic time will continue from where it "left off" before saving as part // of S/R. monotonicOffset MonotonicTime `state:"nosave"` // monotonicMU protects maxMonotonic. monotonicMU sync.Mutex `state:"nosave"` maxMonotonic MonotonicTime } // NewStdClock returns an instance of a clock that uses the time package. func NewStdClock() Clock { return &stdClock{ baseTime: time.Now(), } } var _ Clock = (*stdClock)(nil) // Now implements Clock.Now. func (*stdClock) Now() time.Time { return time.Now() } // NowMonotonic implements Clock.NowMonotonic. func (s *stdClock) NowMonotonic() MonotonicTime { sinceBase := time.Since(s.baseTime) if sinceBase < 0 { panic(fmt.Sprintf("got negative duration = %s since base time = %s", sinceBase, s.baseTime)) } monotonicValue := s.monotonicOffset.Add(sinceBase) s.monotonicMU.Lock() defer s.monotonicMU.Unlock() // Monotonic time values must never decrease. if s.maxMonotonic.Before(monotonicValue) { s.maxMonotonic = monotonicValue } return s.maxMonotonic } // AfterFunc implements Clock.AfterFunc. func (*stdClock) AfterFunc(d time.Duration, f func()) Timer { return &stdTimer{ t: time.AfterFunc(d, f), } } type stdTimer struct { t *time.Timer } var _ Timer = (*stdTimer)(nil) // Stop implements Timer.Stop. func (st *stdTimer) Stop() bool { return st.t.Stop() } // Reset implements Timer.Reset. func (st *stdTimer) Reset(d time.Duration) { st.t.Reset(d) } // NewStdTimer returns a Timer implemented with the time package. func NewStdTimer(t *time.Timer) Timer { return &stdTimer{t: t} }
go
12
0.723976
94
29.946565
131
starcoderdata
<?php use App\Models\Nhandan; use App\Models\Process; use App\Models\Taikhoan; use App\Process\DataProcess; use App\Process\DataProcessFive; $member = DataProcess::getUserOfGroupMessage($message->IDNhomTinNhan); ?> <div id="{{ $message->IDTinNhan }}" onmouseleave="onleaveHoverFeelHide('{{ $message->IDTinNhan }}')" class="mess-user chat-rights z-0 w-full py-1 flex relative"> <div class="mess-user-feel z-50 hidden h-auto relative"> <div class="cursor-pointer color-word absolute top-1/2 pl-2" style="transform: translateY(-50%);"> <ul class="w-full flex relative"> <ul id="{{$message->IDTinNhan}}Feel" class="-left-2 absolute bottom-full flex flex-column dark:bg-dark-second bg-white rounded-lg border-solid dark:border-dark-third border-gray-300 border rounded-3xl hidden"> <li class="px-2 py-2 text-xl cursor-pointer rounded-full hover:bg-gray-300 dark:hover:bg-dark-third" onclick="feelMessage('{{$message->IDTinNhan}}','0@1')">👍 <li class="px-2 py-2 text-xl cursor-pointer rounded-full hover:bg-gray-300 dark:hover:bg-dark-third" onclick="feelMessage('{{$message->IDTinNhan}}','1@1')">❤️ <li class="px-2 py-2 text-xl cursor-pointer rounded-full hover:bg-gray-300 dark:hover:bg-dark-third" onclick="feelMessage('{{$message->IDTinNhan}}','2@1')">😆 <li class="px-2 py-2 text-xl cursor-pointer rounded-full hover:bg-gray-300 dark:hover:bg-dark-third" onclick="feelMessage('{{$message->IDTinNhan}}','3@1')">😥 <li class="px-2 py-2 text-xl cursor-pointer rounded-full hover:bg-gray-300 dark:hover:bg-dark-third" onclick="feelMessage('{{$message->IDTinNhan}}','4@1')">😮 <li class="px-2 py-2 text-xl cursor-pointer rounded-full hover:bg-gray-300 dark:hover:bg-dark-third" onclick="feelMessage('{{$message->IDTinNhan}}','5@1')">😡 <li onclick="feelViewMessage('{{ $message->IDTinNhan }}')" class="feel-mess px-1 mr-1 rounded-full hover:bg-gray-300 dark:hover:bg-dark-third"> <i class="far fa-smile text-xm"> <li onclick="viewRemoveMessage( '{{ $message->IDTinNhan }}', '{{ $message->IDTaiKhoan }}', '{{ $message->IDNhomTinNhan }}')" class="px-1.5 rounded-full hover:bg-gray-300 dark:hover:bg-dark-third"> <i class="far fa-trash-alt text-xm"> <div class="mess-user-r1 pl-2 flex mr-4" style="width: inherit;"> <div class="mess-right {{ json_decode($message->NoiDung)[0]->LoaiTinNhan == 0 ? ' mess-right-child-'.$message->IDNhomTinNhan : '' }} relative break-all ml-auto border-none outline-none p-1.5 rounded-lg relative text-white " style="max-width:75%;font-size: 15px;"> @switch(json_decode($message->NoiDung)[0]->LoaiTinNhan) @case('0') {{json_decode($message->NoiDung)[0]->NoiDungTinNhan}} @break @case('1') @include('Modal/ModalChat/Child/Image',['json' => json_decode($message->NoiDung)]) @break @case('2') @include('Modal/ModalChat/Child/ChatSticker',[ 'value' => Nhandan::where('nhandan.IDNhanDan', '=', json_decode($message->NoiDung)[0]->DuongDan)->get()[0], 'json' => json_decode($message->NoiDung)[0] ]) @break @endswitch <span id="{{ $message->IDTinNhan }}NumFeelMessage" class=" z-10 absolute cursor-pointer" style="border-radius: 20px;bottom:-13px;left:82%;white-space: nowrap;"> {{Process::getFeelMesage($message->IDTinNhan)}} <div class=" mess-user-r2 mess-user-r2{{$message->IDNhomTinNhan}} " id="{{ $message->IDTinNhan }}right" style=" width: 4%;"> <div class="w-full clear-both"> @if ($message->TrangThai == 0) @else @php $trangThais = explode('#',DataProcess::getTrangThaiTinNhan($message->TrangThai,$message->IDTaiKhoan)); @endphp @switch($trangThais[1]) @case('0') <i class="far fa-check-circle img-mess-right absolute bottom-1.5 text-gray-300"> @break @case('1') <i class="fas fa-check-circle img-mess-right absolute bottom-1.5 text-gray-300"> @break @case('2') @if (DataProcessFive::checkShowOrHideMessageRight($message->IDNhomTinNhan, $member[0]->IDTaiKhoan) != $message->IDTinNhan) @else <img src="{{ Taikhoan::where('IDTaiKhoan','=',$trangThais[0])->get()[0]->AnhDaiDien }}" class="img-mess-right absolute right-3 w-6 h-6 p-0.5 mt-1 mr-7 object-cover rounded-full bottom-2 -right-8" alt=""> @endif @break @endswitch @endif
php
8
0.56198
215
54.135417
96
starcoderdata
#include<iostream> #include<vector> #include<algorithm> using namespace std; typedef long long LL; const LL INF=1e18; int N,K,i,j; int X[1234]; int A[1234][1234]; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin>>K; if(K<=500) { cout<<K; for(i=0;i<K;i++) { cout<<'\n'; for(j=0;j<K;j++) cout<<j+1<<' '; } cout<<endl; return 0; } N=K+3>>2<<1; for(i=0;i<N;i++) for(j=0;j<N;j++) A[i][j]=(i&1)*N+(i+j)%N; for(i=0;i<K;i++) X[i]=i; for(i=K;i<N*2;i++) X[i]=i-N; cout<<N; for(i=0;i<N;i++) { cout<<'\n'; for(j=0;j<N;j++) cout<<X[A[i][j]]+1<<' '; } cout<<endl; return 0; }
c++
15
0.407268
37
17.136364
44
codenet
package com.itijavafinalprojectteam8.view; import com.itijavafinalprojectteam8.controller.operations.Props; import com.itijavafinalprojectteam8.controller.operations.log.GuiLogger; import com.itijavafinalprojectteam8.controller.server.GameServer; import com.itijavafinalprojectteam8.interfaces.View; import com.itijavafinalprojectteam8.others.Constants; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import org.json.JSONArray; import org.json.JSONObject; import java.net.URL; import java.util.ResourceBundle; public class GuiController implements Initializable, View { @FXML private ScrollPane scrollpane; @FXML private TextArea logTA; @FXML private Button btnStopServer; @FXML private Button btnStartServer; @FXML private GridPane playersGrid; @Override public void initialize(URL url, ResourceBundle resourceBundle) { GuiLogger.init(this); Props.allPlayersJson.addListener((observableValue, oldValue, newValue) -> { GuiLogger.log("oldValue: " + oldValue); GuiLogger.log("newValue: " + newValue); if (!newValue.equals(oldValue)) { Platform.runLater(() -> updatePlayersView(newValue)); } }); playersGrid.setHgap(10); playersGrid.setVgap(10); } @FXML public void onBtnStartServerClicked(ActionEvent event) { logTA.clear(); toggleStopBtn(); toggleStartBtn(); GameServer.startServer(); } @FXML public void onBtnStopServerClicked(ActionEvent event) { toggleStopBtn(); toggleStartBtn(); GameServer.stopServer(); } /*======================================================================================*/ @Override public void toggleStartBtn() { btnStartServer.setDisable(!btnStartServer.isDisabled()); } @Override public void toggleStopBtn() { btnStopServer.setDisable(!btnStopServer.isDisabled()); } @Override public void displayLog(String text) { Platform.runLater(() -> { logTA.appendText(text + "\n"); scrollpane.setVvalue(1.0); }); } public void updatePlayersView(String jsonString) { playersGrid.getChildren().clear(); JSONArray arr = new JSONArray(jsonString); for (int i = 0; i < arr.length(); i++) { JSONObject jsonobject = arr.getJSONObject(i); String name = jsonobject.optString(Constants.JsonKeys.KEY_USER_NAME); int points = jsonobject.optInt(Constants.JsonKeys.KEY_USER_POINTS); int status = jsonobject.optInt(Constants.JsonKeys.KEY_USER_STATUS); Circle circle = new Circle(200, 200, 8); if (status == Constants.PlayerStatus.OFFLINE) circle.setFill(Color.RED); else circle.setFill(Color.GREEN); Label playerName = new Label(); playerName.setText(name); Label playerPoints = new Label(); playerPoints.setText(String.valueOf(points)); playersGrid.add(circle, 0, i); playersGrid.add(playerName, 1, i); playersGrid.add(playerPoints, 2, i); } } }
java
18
0.642957
94
28.146341
123
starcoderdata
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class TagSyncRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return ['tags' => '']; } public function tagsCollection() { $tagsString = $this->validator->validated()['tags']; $tagsArr = collect(explode(',', trim($tagsString))); $tags = $tagsArr->filter(function ($tag) { return trim($tag); }); return $tags->transform(function ($tag) { return trim($tag); })->unique(); } }
php
17
0.557018
60
19.727273
33
starcoderdata
<?php namespace App\Console; use App\Models\QRCodes; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use App\Http\Controllers\QRCodesController; use SimpleSoftwareIO\QrCode\Facades\QrCode; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->call( function (){ $random_number = $this->generateBarcodeNumber(); echo "testing"; QRCodes::create( [ 'barcode' => $random_number, 'qr_code' => base64_encode(QrCode::format('svg') ->size(250) ->generate($random_number)), ] ); } )->everyMinute(); } function generateBarcodeNumber() { $number = mt_rand(1000000000, 9999999999); // better than rand() // call the same function if the barcode exists already if ($this->barcodeNumberExists($number)) { return $this->generateBarcodeNumber(); } // otherwise, it's valid and can be used return $number; } function barcodeNumberExists($number) { // query the database and return a boolean // for instance, it might look like this in Laravel return QRCodes::where('barcode',$number)->exists(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }
php
27
0.554937
72
25.333333
75
starcoderdata
#ifndef PLOG_TEST_H #define PLOG_TEST_H #include "test.h" TEST(PLogTest, WriteLog) { std::fstream file("/tmp/a/file/that/does/not/exist.txt", std::fstream::in); if (file.is_open()) { // We dont expect to open file FAIL(); } PLOG(INFO) << "This is plog"; std::string expected = BUILD_STR(getDate() << " This is plog: No such file or directory [2]\n"); std::string actual = tail(1); EXPECT_EQ(expected, actual); } #endif // PLOG_TEST_H
c
11
0.607069
100
25.722222
18
starcoderdata
#ifndef __MSG_BUFFER_H__ #define __MSG_BUFFER_H__ #include #include class CMsgBuffer :private boost::noncopyable { public: typedef boost::shared_ptr Ptr; enum { NET_MAXMESSAGE = 8192 }; CMsgBuffer(const char *buffername = "unnamed", void(*ef)(const char *fmt, ...) = 0); virtual ~CMsgBuffer(void); void Clear(void); int GetCurSize(void); int GetMaxSize(void); void *GetData(void); void SetOverflow(bool allowed); void BeginReading(void); int GetReadCount(void); void Push(void); void Pop(void); void WriteByte(int c); void WriteShort(int c); void WriteLong(int c); void WriteFloat(float f); void WriteString(const char *s); void WriteBuf(int iSize, void *buf); void WriteEnd(); int ReadByte(void); int ReadShort(void); int ReadLong(void); float ReadFloat(void); char *ReadString(void); int ReadBuf(int iSize, void *pbuf); void SetTime(float time); float GetTime(); private: void *GetSpace(int length); void Write(const void *data, int length); private: const char *m_pszBufferName; void(*m_pfnErrorFunc)(const char *fmt, ...); int m_nReadCount; int m_nPushedCount; bool m_bPushed; bool m_bBadRead; int m_nMaxSize; int m_nCurSize; bool m_bAllowOverflow; bool m_bOverFlowed; unsigned char m_rgData[NET_MAXMESSAGE]; float m_fRecvTime; }; #endif
c
10
0.676197
85
20.5
70
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use MacsiDigital\Zoom\Facades\Zoom; class ZoomMeetingController extends Controller { public function get_users(Request $request) { } public function all_users(Request $request) { $user = Zoom::user()->all(); } public function meeting_users(Request $request) { $user = Zoom::user()->where(); } public function create_user(Request $request) { $data = array(); $user = Zoom::user()->create([ 'first_name' => ' 'last_name' => ' 'email' => ' 'password' => ' ]); } public function create_webinar(Request $request) { // { // "topic": "Test Webinar", // "type": 5, // "start_time": "2020-09-20T06:59:00Z", // "duration": "60", // "timezone": "America/Los_Angeles", // "password": " // "agenda": "Test Webinar", // "recurrence": { // "type": 1, // "repeat_interval": 1, // "end_date_time": "2020-09-22T06:59:00Z" // }, // "settings": { // "host_video": "true", // "panelists_video": "true", // "practice_session": "true", // "hd_video": "true", // "approval_type": 0, // "registration_type": 2, // "audio": "both", // "auto_recording": "none", // "enforce_login": "false", // "close_registration": "true", // "show_share_button": "true", // "allow_multiple_devices": "false", // "registrants_email_notification": "true" // } // } $webinar = Zoom::user()->find(id)->webinars()->create([]); // $webinar = Zoom::webinar()->make([...]); // $user = Zoom::user()->find(id)->webinars()->save($webinar); } public function add_registrant() { // { // "email": " // "first_name": "Jill", // "last_name": "Chill", // "address": "dsfhkdjsfh st", // "city": "jackson heights", // "country": "US", // "zip": "11371", // "state": "NY", // "phone": "00000000", // "industry": "Food", // "org": "Cooking Org", // "job_title": "Chef", // "purchasing_time_frame": "1-3 months", // "role_in_purchase_process": "Influencer", // "no_of_employees": "10", // "comments": "Looking forward to the Webinar", // "custom_questions": [ // { // "title": "What do you hope to learn from this Webinar?", // "value": "Look forward to learning how you come up with new recipes and what other services you offer." // } // ] // } $webinar = Zoom::webinar()->find($id); /* $registrant = Zoom::panelist()->create([]); $webinar->panelists()->save($panelist); */ $registrant = Zoom::registrant()->create([]); $webinar->registrants()->save($registrant); } }
php
13
0.445266
126
29.727273
110
starcoderdata
def delete(self, index): """Deletes the experiment at the given index from memory and permanent storage. Args: index (:obj:`int`): Index of the experiment to delete. The index is sorted by name and timestamp. """ # delete the experiment folder on disk self.experiments[index].delete() # remove the experminet from the maintained list del self.experiments[index]
python
8
0.589852
79
32.857143
14
inline
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatSize = (props) => ( <SvgIcon {...props}> <path d="M9 4v3h5v12h3V7h5V4H9zm-6 8h3v7h3v-7h3V9H3v3z"/> ); EditorFormatSize = pure(EditorFormatSize); EditorFormatSize.displayName = 'EditorFormatSize'; EditorFormatSize.muiName = 'SvgIcon'; export default EditorFormatSize;
javascript
6
0.746102
61
28.933333
15
starcoderdata
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.cron', name: 'TimeHMS', documentation: ` Models a a time or duration in 24-hour notation. Does not model a date. `, properties: [ { name: 'hour', class: 'IntProperty' }, { name: 'minute', class: 'IntProperty' }, { name: 'second', class: 'IntProperty' } ] });
javascript
7
0.615054
56
20.136364
22
starcoderdata
const initState = { mode: 'day', // day light color: { background: '#FAF9DE', }, style: { fontSize: 20, }, }; function setting(state = initState, action) { switch (action.type) { case 'setting/save': return { ...state, ...action.payload, }; case 'setting/clear': return initState; default: return { ...state, }; } } export default setting;
javascript
8
0.549266
45
16.035714
28
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Requests\PaypalRequest; use App\Payment; use App\PaymentManage; use DB; class PaymentController extends Controller { public function __construct() { $this->middleware('auth'); } function index() { } public function update(PaypalRequest $request, $id) { $pay = Payment::find(1); $pay->clientId = $request->txtClientId; $pay->clientSecret = $request->txtclientSecret; $pay->mode = $request->txtMode; $pay->loglevel = $request->txtLogLevel; $pay->cache = $request->txtCache; $pay->logenable = $request->txtLogEnable; $pay->save(); $pay2 = PaymentManage::find(1); $pay2->status = $request->txtStatus; $pay2->capture_amount = $request->txtAmount; $pay2->save(); $pay3 = PaymentManage::find(2); if($request->txtStatus == 0) { $pay3->status = 1; } else{ $pay3->status = 0; } $pay3->save(); return redirect()->route('paymanager.index'); } public function edit($id) { $edit = DB::table('payment_manage') ->join('payment','payment.payID','=','payment_manage.id') ->select('*') ->where('payment.id','=','1') ->first(); return view('Payment.PaypalPayment',compact('edit')); } }
php
15
0.531679
65
24.114754
61
starcoderdata
# -*- coding: utf-8 -*- """ Created on Sat Sep 12 00:21:05 2020 @author: liang """ N = int(input()) A = [int(x) for x in input().split()] A.sort() A += [-1] dp = [0] + [True]*10**6 def Solve(): if A[0] == 1: if len(A) >= 2 and A[1] == 1: return 0 else: return 1 k = 0 for i in range(1,10**6+1): if i == A[k]: #print("A",i) #kの処理 tmp = A[k] cnt = 0 while k <= N-1 and A[k] == tmp: #print("B",k,tmp) cnt += 1 if cnt == 2: dp[tmp] = False k += 1 #倍数の消去 for j in range(2*i,10**6+1,i): #print("C") dp[j] = False ans = 0 for a in A[:-1]: if dp[a]: ans += 1 return ans ans = Solve() print(ans)
python
14
0.354875
43
19.068182
44
codenet
#!/usr/bin/env node const path = require('path') const fs = require('fs') fs.copyFileSync( path.resolve(__dirname, 'react-ssr-prepass.d.ts'), path.resolve(__dirname, '../dist/react-ssr-prepass.d.ts') ) fs.copyFileSync( path.resolve(__dirname, 'react-ssr-prepass.js.flow'), path.resolve(__dirname, '../dist/react-ssr-prepass.js.flow') ) fs.copyFileSync( path.resolve(__dirname, 'react-ssr-prepass.js.flow'), path.resolve(__dirname, '../dist/react-ssr-prepass.es.js.flow') )
javascript
3
0.690249
65
25.15
20
starcoderdata
private WordBlock[] getWordBlocksForColSplit(ImWord[] tableWords, BoundingBox bounds, float normSpaceWidth) { // get and sort words ImWord[] words = getWordsOverlapping(tableWords, bounds); ImUtils.sortLeftRightTopDown(words); // aggregate words to sequences ArrayList wbs = new ArrayList(); int wbStart = 0; for (int w = 1; w <= words.length; w++) { if ((w == words.length) || this.isColumnGap(words[w-1], words[w], normSpaceWidth)) { ImWord[] wbWords = new ImWord[w - wbStart]; System.arraycopy(words, wbStart, wbWords, 0, wbWords.length); WordBlock wb = new WordBlock(wbWords[0].getPage(), wbWords, true); // System.out.println("Word block: " + wb + " at " + wb.bounds); wbs.add(wb); wbStart = w; } } // finally ... return ((WordBlock[]) wbs.toArray(new WordBlock[wbs.size()])); }
java
13
0.65677
109
35.652174
23
inline
import React from 'react' import styles from './count-sticker.module.scss' const CountSticker = ({children, count}) => { return( <div className={styles.countSticker}> {children} <span className={styles.count}> {count} ) } export default CountSticker
javascript
13
0.562682
48
20.5
16
starcoderdata
import hooks from "./hooks"; /** * 拼接code * * @param {*} type, 类别 * @param {*} content, 内容 * @param {*} alias,别名 * @param {*} matchedStr,匹配文本 * @param {*} greedy, 贪婪模式 */ function Token(type, content, alias, matchedStr, greedy) { this.type = type; this.content = content; this.alias = alias; // Copy of the full string this token was created from this.length = (matchedStr || '').length|0; this.greedy = !!greedy; } Token.stringify = function(o, language) { if (typeof o == 'string') { return o; } if (Array.isArray(o)) { return o.map(function(element) { return Token.stringify(element, language); }).join(''); } var env = { type: o.type, content: Token.stringify(o.content, language), tag: 'span', classes: ['code-token', o.type], attributes: {}, language: language }; if (o.alias) { var aliases = Array.isArray(o.alias) ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } hooks.run('wrap', env); var attributes = Object.keys(env.attributes).map(function(name) { return name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"'; }).join(' '); return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '</' + env.tag + '>'; }; export default Token;
javascript
22
0.600607
147
22.945455
55
starcoderdata
import tensorflow as tf from AttentionPointerWrapperState import * import collections import functools import math import numpy as np from tensorflow.contrib.framework.python.framework import tensor_util from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.layers import base as layers_base from tensorflow.python.layers import core as layers_core from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import clip_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import variable_scope from tensorflow.python.util import nest _zero_state_tensors = rnn_cell_impl._zero_state_tensors class AttentionPointerWrapper(tf.contrib.seq2seq.AttentionWrapper): """Wraps another `RNNCell` with attention. """ def __init__(self, cell, attention_mechanism, attention_layer_size=None, alignment_history=False, cell_input_fn=None, output_attention=True, initial_cell_state=None, pointer=False, name=None): super(AttentionPointerWrapper, self).__init__( cell, attention_mechanism, attention_layer_size=attention_layer_size, alignment_history=alignment_history, cell_input_fn=cell_input_fn, output_attention=output_attention, initial_cell_state=initial_cell_state, name=name) self.pointer = pointer def call(self, inputs, state): """Perform a step of attention-wrapped RNN. - Step 1: Mix the `inputs` and previous step's `attention` output via `cell_input_fn`. - Step 2: Call the wrapped `cell` with this input and its previous state. - Step 3: Score the cell's output with `attention_mechanism`. - Step 4: Calculate the alignments by passing the score through the `normalizer`. - Step 5: Calculate the context vector as the inner product between the alignments and the attention_mechanism's values (memory). - Step 6: Calculate the attention output by concatenating the cell output and context through the attention layer (a linear layer with `attention_layer_size` outputs). Args: inputs: (Possibly nested tuple of) Tensor, the input at this time step. state: An instance of `AttentionWrapperState` containing tensors from the previous time step. Returns: A tuple `(attention_or_cell_output, next_state)`, where: - `attention_or_cell_output` depending on `output_attention`. - `next_state` is an instance of `AttentionWrapperState` containing the state calculated at this time step. Raises: TypeError: If `state` is not an instance of `AttentionWrapperState`. """ if not isinstance(state, AttentionPointerWrapperState): raise TypeError("Expected state to be instance of AttentionWrapperState. " "Received type %s instead." % type(state)) # Step 1: Calculate the true inputs to the cell based on the # previous attention value. cell_inputs = self._cell_input_fn(inputs, state.attention) cell_state = state.cell_state cell_output, next_cell_state = self._cell(cell_inputs, cell_state) cell_batch_size = ( cell_output.shape[0].value or array_ops.shape(cell_output)[0]) error_message = ( "When applying AttentionWrapper %s: " % self.name + "Non-matching batch sizes between the memory " "(encoder output) and the query (decoder output). Are you using " "the BeamSearchDecoder? You may need to tile your memory input via " "the tf.contrib.seq2seq.tile_batch function with argument " "multiple=beam_width.") with ops.control_dependencies( self._batch_size_checks(cell_batch_size, error_message)): cell_output = array_ops.identity( cell_output, name="checked_cell_output") if self._is_multi: previous_attention_state = state.attention_state previous_alignment_history = state.alignment_history else: previous_attention_state = [state.attention_state] previous_alignment_history = [state.alignment_history] all_alignments = [] all_attentions = [] all_attention_states = [] maybe_all_histories = [] for i, attention_mechanism in enumerate(self._attention_mechanisms): attention, alignments, next_attention_state = _compute_attention( attention_mechanism, cell_output, previous_attention_state[i], self._attention_layers[i] if self._attention_layers else None) alignment_history = previous_alignment_history[i].write( state.time, alignments) if self._alignment_history else () all_attention_states.append(next_attention_state) all_alignments.append(alignments) all_attentions.append(attention) maybe_all_histories.append(alignment_history) if self.pointer: num_units = self._cell._num_units Wh = tf.get_variable("Wh", [num_units]) Ws = tf.get_variable("Ws", [num_units]) Wx = tf.get_variable("Wx", shape=inputs.shape) bptr = tf.get_variable("Bptr", shape=()) pgen = tf.sigmoid(tf.reduce_sum(Wh * state.attention, [1]) + tf.reduce_sum(Ws * cell_output, [1]) + tf.reduce_sum(inputs * Wx, [1]) + bptr) pgen_all = state.pgen.write(state.time, pgen) else: pgen_all = () attention = array_ops.concat(all_attentions, 1) next_state = AttentionPointerWrapperState( time=state.time + 1, cell_state=next_cell_state, attention=attention, attention_state=self._item_or_tuple(all_attention_states), alignments=self._item_or_tuple(all_alignments), alignment_history=self._item_or_tuple(maybe_all_histories), pgen =pgen_all ) if self._output_attention: return attention, next_state else: return cell_output, next_state def zero_state(self, batch_size, dtype): """Return an initial (zero) state tuple for this `AttentionWrapper`. **NOTE** Please see the initializer documentation for details of how to call `zero_state` if using an `AttentionWrapper` with a `BeamSearchDecoder`. Args: batch_size: `0D` integer tensor: the batch size. dtype: The internal state data type. Returns: An `AttentionWrapperState` tuple containing zeroed out tensors and, possibly, empty `TensorArray` objects. Raises: ValueError: (or, possibly at runtime, InvalidArgument), if `batch_size` does not match the output size of the encoder passed to the wrapper object at initialization time. """ with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]): if self._initial_cell_state is not None: cell_state = self._initial_cell_state else: cell_state = self._cell.zero_state(batch_size, dtype) error_message = ( "When calling zero_state of AttentionWrapper %s: " % self._base_name + "Non-matching batch sizes between the memory " "(encoder output) and the requested batch size. Are you using " "the BeamSearchDecoder? If so, make sure your encoder output has " "been tiled to beam_width via tf.contrib.seq2seq.tile_batch, and " "the batch_size= argument passed to zero_state is " "batch_size * beam_width.") with ops.control_dependencies( self._batch_size_checks(batch_size, error_message)): cell_state = nest.map_structure( lambda s: array_ops.identity(s, name="checked_cell_state"), cell_state) initial_alignments = [ attention_mechanism.initial_alignments(batch_size, dtype) for attention_mechanism in self._attention_mechanisms] return AttentionPointerWrapperState( cell_state=cell_state, time=array_ops.zeros([], dtype=dtypes.int32), attention=_zero_state_tensors(self._attention_layer_size, batch_size, dtype), alignments=self._item_or_tuple(initial_alignments), attention_state=self._item_or_tuple( attention_mechanism.initial_state(batch_size, dtype) for attention_mechanism in self._attention_mechanisms), alignment_history=self._item_or_tuple( tensor_array_ops.TensorArray( dtype, size=0, dynamic_size=True, element_shape=alignment.shape, clear_after_read=False) if self._alignment_history else () for alignment in initial_alignments), pgen=tensor_array_ops.TensorArray( dtype, size=0, dynamic_size=True, clear_after_read=False) if self.pointer else () ) def _compute_attention(attention_mechanism, cell_output, attention_state, attention_layer): """Computes the attention and alignments for a given attention_mechanism.""" alignments, next_attention_state = attention_mechanism( cell_output, state=attention_state) # Reshape from [batch_size, memory_time] to [batch_size, 1, memory_time] expanded_alignments = array_ops.expand_dims(alignments, 1) # Context is the inner product of alignments and values along the # memory time dimension. # alignments shape is # [batch_size, 1, memory_time] # attention_mechanism.values shape is # [batch_size, memory_time, memory_size] # the batched matmul is over memory_time, so the output shape is # [batch_size, 1, memory_size]. # we then squeeze out the singleton dim. context = math_ops.matmul(expanded_alignments, attention_mechanism.values) context = array_ops.squeeze(context, [1]) if attention_layer is not None: attention = attention_layer(array_ops.concat([cell_output, context], 1)) else: attention = context return attention, alignments, next_attention_state
python
18
0.699721
142
38.841463
246
starcoderdata
'use strict'; var getMxw = require('./utils-mxw'); module.exports = { getMxw: getMxw }
javascript
4
0.62963
36
12.5
8
starcoderdata
import { URLIndex } from "./urlindex.js"; import * as storage from "./storage.js"; import { CID } from "multiformats"; //import { initClient } from "./clientutils.js"; export { URLIndex, storage, CID };
javascript
5
0.669683
48
23.555556
9
starcoderdata
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace GeolocationSample { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private async void Button_Clicked(object sender, EventArgs e) { var result = await App.GeoService.Get(); var last = await App.GeoService.Get2(); lblInfo.Text = result.ToString(); lblInfoLast.Text = last.ToString(); } } }
c#
15
0.625
69
22.407407
27
starcoderdata
const fs = require("fs") const path = require("path") module.exports = ({ cacheFile, ...config }) => { const logger = require("./logger")(config) const filepath = path.resolve(cacheFile) const write = data => { logger.debug("wrinting cache: ", data) return fs.writeFileSync(filepath, JSON.stringify(data)) } const read = () => { logger.debug("reading cache...") return fs.existsSync(filepath) ? JSON.parse(fs.readFileSync(filepath)) : {} } const getLastMessageTime = () => Number(read().lastMessageTime || 0) const setLastMessageTime = time => { const date = new Date(time) write({ lastMessageTime: Number(date) }) } return { getLastMessageTime, setLastMessageTime, } }
javascript
15
0.658031
79
27.592593
27
starcoderdata
public static void main(String[] args) throws Exception { // Create a new factory ComponentFactory factory = new ComponentFactory(); // Retrieve a new instance of shell-example IShellExampleCli example = factory.createShellExample("shell-example", System.in, System.out); // Start the instance in a new thread new Thread((Runnable) example).start(); }
java
8
0.73913
72
40
9
inline
#include #include #include #include #include "zlib.h" #include #include using namespace std; string gzreadline(gzFile gzfp) { stringstream line; char buffer[1]; int len = gzread(gzfp, buffer, 1); while (len == 1 && buffer[0] != '\n') { line << buffer[0]; len = gzread(gzfp, buffer, 1); } return(line.str()); } int main(int argc, char *argv[]) { gzFile fp_gz = gzopen("test_gz.dat", "rb"); string temp_string; double dummy; int urqmd_id, urqmd_iso3, urqmd_charge, parent_id, n_coll, parent_proc_type; double mass, t, x, y, z, E, px, py, pz; string test_line = gzreadline(fp_gz); cout << test_line << endl; test_line = gzreadline(fp_gz); cout << test_line << endl; test_line = gzreadline(fp_gz); cout << test_line << endl; test_line = gzreadline(fp_gz); cout << test_line << endl; //char buffer[sizeof(int)]; //int len = gzread(fp_gz, buffer, sizeof(int)); //int N = strtol(buffer, NULL, 10); //cout << len << " " << N << " " << buffer << endl; //for (int i = 0; i < 8; i++) { // char buffer1[sizeof(int)]; // int len2 = gzread(fp_gz, buffer1, sizeof(int)); // int N1 = strtol(buffer1, NULL, 10); // cout << len2 << " " << N1 << " " << buffer1 << endl; //} //while (!urqmd_file.eof()) { // // get total number of particles // getline(urqmd_file, temp_string); // stringstream temp1(temp_string); // int n_particles[1]; // temp1 >> n_particles[0]; // fwrite(n_particles, sizeof(int), 1, binary_file); // gzwrite(fp_gz, &n_particles, sizeof(int)); // // get some information // int n_info[8]; // getline(urqmd_file, temp_string); // stringstream temp2(temp_string); // for (int i = 0; i < 8; i++) // temp2 >> n_info[i]; // fwrite(n_info, sizeof(int), 8, binary_file); // gzwrite(fp_gz, &n_info, sizeof(int)*8); // for (int i = 0; i < n_particles[0]; i++) { // getline(urqmd_file, temp_string); // stringstream temp3(temp_string); // temp3 >> dummy >> dummy >> dummy >> dummy // >> dummy >> dummy >> dummy >> dummy // >> mass >> urqmd_id >> urqmd_iso3 >> urqmd_charge // >> parent_id >> n_coll >> parent_proc_type // >> t >> x >> y >> z // >> E >> px >> py >> pz; // int array1[6] = {urqmd_id, urqmd_iso3, urqmd_charge, // n_coll, parent_id, parent_proc_type}; // float array2[9] = {mass, t, x, y, z, E, px, py, pz}; // fwrite(array1, sizeof(int), 6, binary_file); // gzwrite(fp_gz, &array1, sizeof(int)*6); // fwrite(array2, sizeof(float), 9, binary_file); // gzwrite(fp_gz, &array2, sizeof(float)*9); // } // getline(urqmd_file, temp_string); //} gzclose(fp_gz); return 0; }
c++
9
0.51117
80
33.988506
87
starcoderdata
#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <map> #include <set> using namespace std; typedef long long ll; int fi[130][130]; int d[130][130]; int xx,yy; int dx[]={0,1,1,0,-1,-1}; int dy[]={1,1,0,-1,-1,0}; int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); while(1){ int t,n; cin >> t >> n; if(t==0&&n==0)break; for(int i=0;i<130;i++){ for(int j=0;j<130;j++){ fi[i][j]=1; d[i][j]=1e9; } } for(int i=0;i<n;i++){ int x,y; cin >> x >> y; x+=60; y+=60; fi[x][y]=0; } cin >> xx >> yy; xx+=60; yy+=60; d[xx][yy]=0; queue<pair<int,int>> q; q.push(make_pair(xx,yy)); while(q.size()){ auto p=q.front(); q.pop(); int x=p.first,y=p.second; for(int i=0;i<6;i++){ int nx=x+dx[i],ny=y+dy[i]; if(0<=nx&&nx<130&&0<=ny&&ny<130){ if(fi[nx][ny]==0)continue; if(d[nx][ny]>d[x][y]+1){ d[nx][ny]=d[x][y]+1; q.push(make_pair(nx,ny)); } } } } int res=0; for(int i=0;i<130;i++){ for(int j=0;j<130;j++){ if(d[i][j]<=t)res++; } } cout << res << endl; } }
c++
19
0.494555
37
17.065574
61
codenet
import java.util.Calendar; import java.util.Date; // 내가 태어나서 오늘까지 몇일이 지났을까? public class W2_8_MyD_DayNOOP { public static void main(String[] args) { //long millis = System.currentTimeMillis(); // 1970년 1월 1일부터 시간 msec //System.out.println("1970년 1월 1일부터 " + millis/1000/24/60/60 + "일 지났습니다."); // 몇일 지났는지 계산하기 //Date d = new Date(); // 오늘 날짜를 가져오는 방법 //System.out.println(d); //Date dd = new Date(d.getTime() + 24*60*60*1000); // 오늘 날짜에서 하루를 더하는 방법 //System.out.println(dd); Calendar today = Calendar.getInstance(); // 오늘 날짜를 객체로 가져오는 방법 Calendar myBirth = Calendar.getInstance(); // 날짜를 임의롤 지정하는 방법 myBirth.set(1994, 9-1, 12); // BTS 리더 RM 생일 (1994년 9월 12일) //System.out.println(today); long dday_millis = today.getTimeInMillis() - myBirth.getTimeInMillis(); printCalendar(myBirth); System.out.print(" 부터 "); printCalendar(today); System.out.print(" 까지 "); System.out.print( dday_millis / 1000 / 24 / 60 / 60 ); System.out.print(" 일 차이가 납니다"); System.out.println(""); } public static void printCalendar(Calendar c) { System.out.print(c.get(Calendar.YEAR) + "년 "); System.out.print(c.get(Calendar.MONTH) + 1 + "월 "); System.out.print(c.get(Calendar.DAY_OF_MONTH) + "일"); } }
java
13
0.659001
93
34.055556
36
starcoderdata
package com.example.springboot.graylog; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * * 参考 * * graylog 官方下载地址:https://www.graylog.org/downloads#open-source * * graylog 官方docker镜像:https://hub.docker.com/r/graylog/graylog/ * * graylog 镜像启动方式:http://docs.graylog.org/en/stable/pages/installation/docker.html * * graylog 启动参数配置:http://docs.graylog.org/en/stable/pages/configuration/server.conf.html * * 注意,启动参数需要加 GRAYLOG_ 前缀 * * 日志收集依赖:https://github.com/osiegmar/logback-gelf */ @SpringBootApplication public class SpringbootGraylogApplication { public static void main(String[] args) { SpringApplication.run(SpringbootGraylogApplication.class, args); } }
java
9
0.75995
88
24.125
32
starcoderdata
import { combineReducers } from 'redux'; import userReducer from './user'; import tasksReducer from './tasks'; const rootReducer = combineReducers({ userState: userReducer, tasksState: tasksReducer, }); export default rootReducer;
javascript
5
0.751799
40
24.272727
11
starcoderdata
/* CMSIS-DAP Interface Firmware * Copyright (c) 2009-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FlashOS.H" // FlashOS Structures #include "mt25ql_flash_lib.h" static const struct qspi_ip6514e_dev_cfg_t QSPI_DEV_CFG = { .base = MUSCA_QSPI_REG_BASE, /* * On Musca-A1, only the 18 first address bits are used for any AHB * address in a request coming to the QSPI Flash controller. * It means that direct accesses are limited to the first 256 KiB of the * Flash memory (if the Remap register is not used) and that the Indirect * Trigger zone needs to be inside the first 256 KiB as well. */ .addr_mask = (1U << 18) - 1, /* 256 KiB minus 1 byte */ }; uint32_t initialized = 0; //struct qspi_ip6514e_dev_t QSPI_DEV = { // &QSPI_DEV_CFG //}; struct qspi_ip6514e_dev_t QSPI_DEV; struct mt25ql_dev_t MT25QL_DEV = { // .controller = &QSPI_DEV, .direct_access_start_addr = MUSCA_QSPI_FLASH_BASE, .baud_rate_div = 4U, /* * 8 MiB flash memory are advertised in the Arm Musca-A Test Chip and Board * Technical Reference Manual. The MT25QL Flash device may however contain * more. */ .size = 0x00800000U, /* 8 MiB */ }; /** * \brief Arm Flash device structure. */ struct arm_flash_dev_t { struct mt25ql_dev_t* dev; /*!< FLASH memory device structure */ }; //static struct arm_flash_dev_t ARM_FLASH0_DEV = { // .dev = &(MT25QL_DEV) //}; static struct arm_flash_dev_t ARM_FLASH0_DEV; /* Mandatory Flash Programming Functions (Called by FlashOS): int Init (unsigned long adr, // Initialize Flash unsigned long clk, unsigned long fnc); int UnInit (unsigned long fnc); // De-initialize Flash int EraseSector (unsigned long adr); // Erase Sector Function int ProgramPage (unsigned long adr, // Program Page Function unsigned long sz, unsigned char *buf); Optional Flash Programming Functions (Called by FlashOS): int BlankCheck (unsigned long adr, // Blank Check unsigned long sz, unsigned char pat); int EraseChip (void); // Erase complete Device unsigned long Verify (unsigned long adr, // Verify Function unsigned long sz, unsigned char *buf); - BlanckCheck is necessary if Flash space is not mapped into CPU memory space - Verify is necessary if Flash space is not mapped into CPU memory space - if EraseChip is not provided than EraseSector for all sectors is called */ /* * Initialize Flash Programming Functions * Parameter: adr: Device Base Address * clk: Clock Frequency (Hz) * fnc: Function Code (1 - Erase, 2 - Program, 3 - Verify) * Return Value: 0 - OK, 1 - Failed */ int Init (unsigned long adr, unsigned long clk, unsigned long fnc) { if(initialized == 0) { /* For PIC the following assignments have to be in a function (run time) */ QSPI_DEV.cfg = &QSPI_DEV_CFG; MT25QL_DEV.controller = &QSPI_DEV; ARM_FLASH0_DEV.dev = &MT25QL_DEV; qspi_ip6514e_enable(ARM_FLASH0_DEV.dev->controller); /* Configure QSPI Flash controller to operate in single SPI mode and * to use fast Flash commands */ if (MT25QL_ERR_NONE != mt25ql_config_mode(ARM_FLASH0_DEV.dev, MT25QL_FUNC_STATE_FAST)) { return 1; } initialized = 1; } return 0; } /* * De-Initialize Flash Programming Functions * Parameter: fnc: Function Code (1 - Erase, 2 - Program, 3 - Verify) * Return Value: 0 - OK, 1 - Failed */ int UnInit (unsigned long fnc) { if(fnc == 0 && initialized == 1) { /* Restores the QSPI Flash controller and MT25QL to default state */ if (MT25QL_ERR_NONE != mt25ql_restore_default_state(ARM_FLASH0_DEV.dev)) { return 1; } initialized = 0; } return 0; } /* * Erase complete Flash Memory * Return Value: 0 - OK, 1 - Failed */ int EraseChip (void) { if (MT25QL_ERR_NONE != mt25ql_erase(ARM_FLASH0_DEV.dev, 0, MT25QL_ERASE_ALL_FLASH)) { return 1; } return 0; } /* * Erase Sector in Flash Memory * Parameter: adr: Sector Address * Return Value: 0 - OK, 1 - Failed */ int EraseSector (unsigned long adr) { adr = (adr & 0x00FFFFFF) - MUSCA_QSPI_FLASH_BASE; if (MT25QL_ERR_NONE != mt25ql_erase(ARM_FLASH0_DEV.dev, adr, MT25QL_ERASE_SECTOR_64K)) { return 1; } return 0; } /* * Program Page in Flash Memory * Parameter: adr: Page Start Address * sz: Page Size * buf: Page Data * Return Value: 0 - OK, 1 - Failed */ int ProgramPage (unsigned long adr, unsigned long sz, unsigned char *buf) { adr = (adr & 0x00FFFFFF) - MUSCA_QSPI_FLASH_BASE; enum mt25ql_error_t err = mt25ql_command_write(ARM_FLASH0_DEV.dev, adr, buf, sz); if (MT25QL_ERR_NONE != err) { return err; } return 0; } /* * Verify Flash Contents * Parameter: adr: Start Address * sz: Size (in bytes) * buf: Data * Return Value: 0 - OK, Failed Address */ unsigned long Verify (unsigned long adr, unsigned long sz, unsigned char *buf) { unsigned char* ptr = (unsigned char*)(adr & 0x00FFFFFF); unsigned int i; unsigned char data[4]; ptr = ptr - MUSCA_QSPI_FLASH_BASE; for (i = 0; i < sz; i = i + 4) { mt25ql_command_read(ARM_FLASH0_DEV.dev, (uint32_t)ptr, (uint8_t*) data, 4); if( data[0] != buf[i + 0] || data[1] != buf[i + 1] || data[2] != buf[i + 2] || data[3] != buf[i + 3] ) { return (unsigned long)(MUSCA_QSPI_FLASH_BASE + ptr + i); } ptr = ptr + 4; } return 0; } /* Blank Check Block in Flash Memory * Parameter: adr: Block Start Address * sz: Block Size (in bytes) * pat: Block Pattern * Return Value: 0 - OK, 1 - Failed */ int BlankCheck (unsigned long adr, unsigned long sz, unsigned char pat) { unsigned char* ptr = (unsigned char*)(adr & 0x00FFFFFF); unsigned int i; unsigned char data[4]; ptr = ptr - MUSCA_QSPI_FLASH_BASE; for (i = 0; i < sz; i = i + 4) { mt25ql_command_read(ARM_FLASH0_DEV.dev, (uint32_t)ptr, data, 4); if( data[0] != pat || data[1] != pat || data[2] != pat || data[3] != pat ) { return (1); } ptr = ptr + 4; } return (0); }
c
13
0.571982
96
30.594937
237
starcoderdata
package com.github.jsonzou.jmockdata.myTest; import com.github.jsonzou.jmockdata.annotation.MockIgnore; import java.util.List; import java.util.Map; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class Person { @MockIgnore private String name; private Integer age; private String hospitalName; private List projectList; private String[] array; private Map hashMap; }
java
5
0.769231
58
22.045455
22
starcoderdata
from fastapi import Query from pydantic.main import BaseModel class HistoryQuery(BaseModel): month: int = Query(default=1, ge=1, le=6) conversation_step_threshold: int = Query(default=10, ge=2) action_fallback: str = Query(default="action_default_fallback") nlu_fallback: str = Query(default=None) sort_by_date: bool = Query(default=True) top_n: int = Query(default=10, ge=1) l_bound: float = Query(default=0, ge=0, lt=1) u_bound: float = Query(default=1, gt=0, le=1) stopword_list: list = Query(default=None)
python
9
0.688496
67
36.666667
15
starcoderdata
from django.contrib import admin from .models import Question, Answer class QuestionAdmin(admin.ModelAdmin): list_display = ['text', 'next_question'] class AnswerAdmin(admin.ModelAdmin): list_display = ['text', 'question', 'is_correct'] admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin)
python
7
0.750685
53
21.8125
16
starcoderdata
#include #include //BUBBLE SORT void Bubble_Sort (int arr[], int n) { int i, j, angka; for (i = 0; i < n; i++){ for (j = 0; j < n-i-1; j++){ if (arr[j] > arr[j+1]){ angka = arr[j]; arr[j] = arr[j+1]; arr[j+1] = angka; } } } } int main() { int array[100]={56,45,23,5,6,8,43,567,32}; Bubble_Sort (array,9); printf("Hasil pengurutan : \n"); for(int i = 0; i < 9; i++){ printf("%d ", array [i]); } printf("\n"); }
c
13
0.389545
46
18.517241
29
starcoderdata
/* * Copyright &copy 2014-2016 NetApp, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen. */ package com.solidfire.element.api; import com.solidfire.gson.Gson; import com.solidfire.core.client.Attributes; import com.solidfire.gson.annotations.SerializedName; import com.solidfire.core.annotation.Since; import com.solidfire.core.javautil.Optional; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Objects; /** * ListKeyServersKmipRequest * Returns the list of KMIP (Key Management Interoperability Protocol) Key Servers which have been created via CreateKeyServerKmip. The list can optionally be filtered by specifying additional parameters. **/ public class ListKeyServersKmipRequest implements Serializable { public static final long serialVersionUID = -3048387590635848717L; @SerializedName("keyProviderID") private Optional keyProviderID; @SerializedName("kmipAssignedProviderIsActive") private Optional kmipAssignedProviderIsActive; @SerializedName("kmipHasProviderAssigned") private Optional kmipHasProviderAssigned; // empty constructor @Since("7.0") public ListKeyServersKmipRequest() {} // parameterized constructor @Since("7.0") public ListKeyServersKmipRequest( Optional keyProviderID, Optional kmipAssignedProviderIsActive, Optional kmipHasProviderAssigned ) { this.keyProviderID = (keyProviderID == null) ? Optional. : keyProviderID; this.kmipAssignedProviderIsActive = (kmipAssignedProviderIsActive == null) ? Optional. : kmipAssignedProviderIsActive; this.kmipHasProviderAssigned = (kmipHasProviderAssigned == null) ? Optional. : kmipHasProviderAssigned; } /** * If omitted, returned KMIP Key Server objects will not be filtered based on whether they're assigned to the specified KMIP Key Provider. * If specified, returned KMIP Key Server objects will be filtered to those assigned to the specified KMIP Key Provider. **/ public Optional getKeyProviderID() { return this.keyProviderID; } public void setKeyProviderID(Optional keyProviderID) { this.keyProviderID = (keyProviderID == null) ? Optional. : keyProviderID; } /** * If omitted, returned KMIP Key Server objects will not be filtered based on whether they're active. * If true, returns only KMIP Key Server objects which are active (providing keys which are currently in use). * If false, returns only KMIP Key Server objects which are inactive (not providing any keys and able to be deleted). **/ public Optional getKmipAssignedProviderIsActive() { return this.kmipAssignedProviderIsActive; } public void setKmipAssignedProviderIsActive(Optional kmipAssignedProviderIsActive) { this.kmipAssignedProviderIsActive = (kmipAssignedProviderIsActive == null) ? Optional. : kmipAssignedProviderIsActive; } /** * If omitted, returned KMIP Key Server objects will not be filtered based on whether they have a KMIP Key Provider assigned. * If true, returns only KMIP Key Server objects which have a KMIP Key Provider assigned. * If false, returns only KMIP Key Server objects which do not have a KMIP Key Provider assigned. **/ public Optional getKmipHasProviderAssigned() { return this.kmipHasProviderAssigned; } public void setKmipHasProviderAssigned(Optional kmipHasProviderAssigned) { this.kmipHasProviderAssigned = (kmipHasProviderAssigned == null) ? Optional. : kmipHasProviderAssigned; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ListKeyServersKmipRequest that = (ListKeyServersKmipRequest) o; return Objects.equals(keyProviderID, that.keyProviderID) && Objects.equals(kmipAssignedProviderIsActive, that.kmipAssignedProviderIsActive) && Objects.equals(kmipHasProviderAssigned, that.kmipHasProviderAssigned); } @Override public int hashCode() { return Objects.hash( keyProviderID,kmipAssignedProviderIsActive,kmipHasProviderAssigned ); } public java.util.Map<String, Object> toMap() { java.util.Map<String, Object> map = new HashMap<>(); map.put("keyProviderID", keyProviderID); map.put("kmipAssignedProviderIsActive", kmipAssignedProviderIsActive); map.put("kmipHasProviderAssigned", kmipHasProviderAssigned); return map; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); Gson gson = new Gson(); sb.append( "{ " ); if(null != keyProviderID && keyProviderID.isPresent()){ sb.append(" keyProviderID : ").append(gson.toJson(keyProviderID)).append(","); } else{ sb.append(" keyProviderID : ").append("null").append(","); } if(null != kmipAssignedProviderIsActive && kmipAssignedProviderIsActive.isPresent()){ sb.append(" kmipAssignedProviderIsActive : ").append(gson.toJson(kmipAssignedProviderIsActive)).append(","); } else{ sb.append(" kmipAssignedProviderIsActive : ").append("null").append(","); } if(null != kmipHasProviderAssigned && kmipHasProviderAssigned.isPresent()){ sb.append(" kmipHasProviderAssigned : ").append(gson.toJson(kmipHasProviderAssigned)).append(","); } else{ sb.append(" kmipHasProviderAssigned : ").append("null").append(","); } sb.append( " }" ); if(sb.lastIndexOf(", }") != -1) sb.deleteCharAt(sb.lastIndexOf(", }")); return sb.toString(); } public static Builder builder() { return new Builder(); } public final Builder asBuilder() { return new Builder().buildFrom(this); } public static class Builder { private Optional keyProviderID; private Optional kmipAssignedProviderIsActive; private Optional kmipHasProviderAssigned; private Builder() { } public ListKeyServersKmipRequest build() { return new ListKeyServersKmipRequest ( this.keyProviderID, this.kmipAssignedProviderIsActive, this.kmipHasProviderAssigned); } private ListKeyServersKmipRequest.Builder buildFrom(final ListKeyServersKmipRequest req) { this.keyProviderID = req.keyProviderID; this.kmipAssignedProviderIsActive = req.kmipAssignedProviderIsActive; this.kmipHasProviderAssigned = req.kmipHasProviderAssigned; return this; } public ListKeyServersKmipRequest.Builder optionalKeyProviderID(final Long keyProviderID) { this.keyProviderID = (keyProviderID == null) ? Optional. : Optional.of(keyProviderID); return this; } public ListKeyServersKmipRequest.Builder optionalKmipAssignedProviderIsActive(final Boolean kmipAssignedProviderIsActive) { this.kmipAssignedProviderIsActive = (kmipAssignedProviderIsActive == null) ? Optional. : Optional.of(kmipAssignedProviderIsActive); return this; } public ListKeyServersKmipRequest.Builder optionalKmipHasProviderAssigned(final Boolean kmipHasProviderAssigned) { this.kmipHasProviderAssigned = (kmipHasProviderAssigned == null) ? Optional. : Optional.of(kmipHasProviderAssigned); return this; } } }
java
13
0.696791
205
42.466667
195
starcoderdata
<?php namespace PHPDaemon\Clients\AMQP\Driver\Exception; use PHPDaemon\Clients\AMQP\Driver\Protocol\Exception\AMQPException; use PHPDaemon\Clients\AMQP\Driver\Protocol\Exception\AMQPExchangeExceptionInterface; /** * Class AMQPExchangeException * @author YOU GLOBAL LIMITED * @package PHPDaemon\Clients\AMQP\Driver\Exception */ class AMQPExchangeException extends AMQPException implements AMQPExchangeExceptionInterface { }
php
6
0.834016
91
29.5
16
starcoderdata
#pragma once #include "message/message.hpp" class Registry { public: virtual void send_to_id(uint64_t id, const Message* msg) = 0; virtual void send_to_index(int index, const Message* msg) = 0; virtual void broadcast(const Message* msg) = 0; }; // Registry
c++
8
0.697761
50
14.764706
17
starcoderdata
void TQ_ReloadPerformanceCounters( IN VOID * pvParam, OUT VOID ** ppvNextParam, OUT DWORD * pcSecsUntilNextRun ) { if (ReloadPerformanceCounters()) { // Failed; reschedule. *pcSecsUntilNextRun = PERFCTR_RELOAD_INTERVAL; } else { // Success -- we're done. *pcSecsUntilNextRun = TASKQ_DONT_RESCHEDULE; // We failed in the past; inform admin of our progress. LogEvent(DS_EVENT_CAT_INTERNAL_CONFIGURATION, DS_EVENT_SEV_ALWAYS, DIRLOG_PERFMON_COUNTER_REG_SUCCESS, NULL, NULL, NULL); } }
c
10
0.543155
63
26.083333
24
inline