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
ex_expr::exp_return_type ExHash2Distrib::pCodeGenerate(Space *space, UInt32 f) { // Get a handle on the operands // AttributesPtr *attrs = getOperand(); PCIList code(space); PCode::preClausePCI(this, code); AML aml(PCIT::MBIN32U, // Target (the partition number) PCIT::MBIN32U, // The hash value PCIT::MBIN32U); // Number of partitions // attr[0] = result // attr[1] = keyValue // attr[2] = numParts OL ols(attrs[0]->getAtp(),attrs[0]->getAtpIndex(),(Int32)attrs[0]->getOffset(), attrs[1]->getAtp(),attrs[1]->getAtpIndex(),(Int32)attrs[1]->getOffset(), attrs[2]->getAtp(),attrs[2]->getAtpIndex(),(Int32)attrs[2]->getOffset()); PCI pci(PCIT::Op_HASH2_DISTRIB, aml, ols); code.append(pci); // Generate post clause PCI's // PCode::postClausePCI(this, code); setPCIList(code.getList()); return ex_expr::EXPR_OK; }
c++
11
0.648
81
28.2
30
inline
#include<cstdio> #include<queue> #include<algorithm> #include<string.h> #include<math.h> #include<set> #include<stack> #include<queue> #include<map> #include<iostream> using namespace std; char s[1100],t[1100]; int main() { double l; scanf("%lf",&l); printf("%.10lf\n",l*l*l/27); }
c++
9
0.681818
29
14.888889
18
codenet
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WritingExporter.Common; using WritingExporter.Common.Models; using WritingExporter.Common.Export; using WritingExporter.Common.Storage; namespace WritingExporter.Common.Test { [TestClass] public class StoryExportTest { public StoryExportTest() { TestUtil.SetupLogging(); } [TestMethod] public void ExportWholeStory() { var storyLoader = new XmlStoryFileStore(); var story = storyLoader.DeserializeStory(TestUtil.GetDataFile(@"SampleStories.1824771-short-stories-by-the-people.xml")); var exporter = new WdcStoryExporterHtmlCollection("StoryOutput"); exporter.ExportStory(story); } } }
c#
17
0.693208
133
28.448276
29
starcoderdata
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #import #import #import @class CKComponent; @class UIView; /** CKComponentDebugController exposes the functionality needed by the lldb helpers to control the debug behavior for components. */ @interface CKComponentDebugController : NSObject + (BOOL)debugMode; /** Setting the debug mode enables the injection of debug configuration into the component. */ + (void)setDebugMode:(BOOL)debugMode; /** Components are an immutable construct. Whenever we make changes to the parameters on which the components depended, the changes won't be reflected in the component hierarchy until we explicitly cause a reflow/update. A reflow essentially rebuilds the component hierarchy and mounts it back on the view. This is particularly used in reflowing the component hierarchy when we set the debug mode. */ + (void)reflowComponents; @end /** Returns an adjusted mount context that inserts a debug view if the viewConfiguration doesn't have a view. */ CK::Component::MountContext CKDebugMountContext(Class componentClass, const CK::Component::MountContext &context, const CKComponentViewConfiguration &viewConfiguration, const CGSize size);
c
6
0.716349
116
35.0625
48
starcoderdata
def fn_enumerate_trace_source_sinks(self, trace_template): """Enumerates the (list of) trace start and end points from template. :param trace_template: dictionary object corresponding to a single trace, from which trace end points are to be extracted :returns: list containing two lists - the first a list of possible start points and the second, a list of possible end points """ # Get the start points. trace_from_string = trace_template['TRACEFROM'] if ' OR ' in trace_from_string: trace_from_string_list = trace_from_string.split(' OR ') else: trace_from_string_list = [trace_from_string] # Get the end points. trace_to_string = trace_template['TRACETO'] if ' OR ' in trace_to_string: trace_to_string_list = trace_to_string.split(' OR ') else: trace_to_string_list = [trace_to_string] return [trace_from_string_list, trace_to_string_list]
python
10
0.610415
77
48.428571
21
inline
//index warna 1 Blockly.Blocks['warna_level1'] = { init: function() { this.appendDummyInput() .appendField("pilih warna ") .appendField(new Blockly.FieldColour("#ffffff"), "warna"); this.setColour(90); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['warna_level1'] = function(block) { var colour_warna = block.getFieldValue('warna'); if (colour_warna==="#ff0000") { var code = "document.getElementById('lingkaran').style.backgroundColor='red';" alert("berhasil");window.location="index2.html"; }else { alert("coba lagi"); } return code; }; //index warna 2 Blockly.Blocks['warna_level2'] = { init: function() { this.appendDummyInput() .appendField("pilih warna ") .appendField(new Blockly.FieldColour("#ffffff"), "warna"); this.setColour(90); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['warna_level2'] = function(block) { var colour_warna = block.getFieldValue('warna'); if (colour_warna==="#ffff66") { var code = "document.getElementById('lingkaran').style.backgroundColor='#ffff66';" alert("berhasil");window.location="index3.html"; }if (colour_warna==="#ffff33") { var code = "document.getElementById('lingkaran').style.backgroundColor='#ffff33';" alert("berhasil");window.location="index3.html"; }if (colour_warna==="#ffff00") { var code = "document.getElementById('lingkaran').style.backgroundColor='#ffff00';" alert("berhasil");window.location="index3.html"; }else { alert("coba lagi"); } return code; }; //index warna 3 Blockly.Blocks['warna_level3'] = { init: function() { this.appendDummyInput() .appendField("pilih warna ") .appendField(new Blockly.FieldColour("#ffffff"), "warna"); this.setColour(90); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['warna_level3'] = function(block) { var colour_warna = block.getFieldValue('warna'); if (colour_warna==="#33ff33") { var code = "document.getElementById('lingkaran').style.backgroundColor='#33ff33';" alert("berhasil");window.location="index_lampu.html"; }if (colour_warna==="#33cc00") { var code = "document.getElementById('lingkaran').style.backgroundColor='#33cc00';" alert("berhasil");window.location="index_lampu.html"; }if (colour_warna==="#009900") { var code = "document.getElementById('lingkaran').style.backgroundColor='#009900';" alert("berhasil");window.location="index_lampu.html"; } return code; }; //index warna lampu Blockly.Blocks['laper'] = { init: function() { this.appendDummyInput() .appendField("lampu pertama") .appendField(new Blockly.FieldColour("#ffffff"), "pertama"); this.setColour(120); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['laper'] = function(block) { var colour_light = block.getFieldValue('pertama'); if (colour_light==="#ff0000") { var code = "document.getElementById('merah').style.backgroundColor='#ff0000';" } return code; }; Blockly.Blocks['lake'] = { init: function() { this.appendDummyInput() .appendField("lampu kedua") .appendField(new Blockly.FieldColour("#ffffff"), "kedua"); this.setColour(120); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['lake'] = function(block) { var colour_light = block.getFieldValue('kedua'); if (colour_light==="#ffff66") { var code = "document.getElementById('kuning').style.backgroundColor='#ffff66';" }if (colour_light==="#ffff33") { var code = "document.getElementById('kuning').style.backgroundColor='#ffff33';" }if (colour_light==="#ffff00") { var code = "document.getElementById('kuning').style.backgroundColor='#ffff00';" } return code; }; Blockly.Blocks['lati'] = { init: function() { this.appendDummyInput() .appendField("lampu ketiga") .appendField(new Blockly.FieldColour("#ffffff"), "ketiga"); this.setColour(120); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['lati'] = function(block) { var colour_light = block.getFieldValue('ketiga'); if (colour_light==="#33ff33") { var code = "document.getElementById('hijau').style.backgroundColor='#33ff33';" }if (colour_light==="#33cc00") { var code = "document.getElementById('hijau').style.backgroundColor='#33cc00';" }if (colour_light==="#009900") { var code = "document.getElementById('hijau').style.backgroundColor='#009900';" } return code; }; //jalan_level1 Blockly.Blocks['maju'] = { init: function() { this.appendDummyInput() .appendField("Jalan") .appendField(new Blockly.FieldTextInput("maju"), "maju"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(230); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['maju'] = function(block) { var text_depan = block.getFieldValue('maju'); var y=document.getElementById('charID').offsetLeft; y= y +10; document.getElementById('charID').style.left= y + "px"; return code; }; Blockly.Blocks['kanan'] = { init: function() { this.appendDummyInput() .appendField("Jalan") .appendField(new Blockly.FieldTextInput("kanan"), "kanan"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(230); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['kanan'] = function(block) { var text_bawah = block.getFieldValue('kanan'); var x=document.getElementById('charID').offsetTop; x= x -100; document.getElementById('charID').style.top= x + "px"; return code; }; Blockly.Blocks['kiri'] = { init: function() { this.appendDummyInput() .appendField("Jalan") .appendField(new Blockly.FieldTextInput("kiri"), "kiri"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(230); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.JavaScript['kiri'] = function(block) { var text_bawah = block.getFieldValue('kiri'); var x=document.getElementById('charID').offsetTop; x= x -200; document.getElementById('charID').style.top= x + "px"; return code; };
javascript
13
0.65473
86
28.883178
214
starcoderdata
@Test public void putTaskState() { byte[] value = new byte[0]; expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class))) .andStubReturn(value); final Capture<Callback> callbackCapture = newCapture(); kafkaBasedLog.send(eq("status-task-conn-0"), eq(value), capture(callbackCapture)); expectLastCall() .andAnswer(() -> { callbackCapture.getValue().onCompletion(null, null); return null; }); replayAll(); TaskStatus status = new TaskStatus(TASK, TaskStatus.State.RUNNING, WORKER_ID, 0); store.put(status); // state is not visible until read back from the log assertNull(store.get(TASK)); verifyAll(); }
java
12
0.584838
109
35.173913
23
inline
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // LoyaltyProgramRewardTier Describes a loyalty program reward tier. // // swagger:model LoyaltyProgramRewardTier type LoyaltyProgramRewardTier struct { // The timestamp when the reward tier was created, in RFC 3339 format. // Required: true CreatedAt *string `json:"created_at"` // Provides details about the reward tier definition. // DEPRECATED at version 2020-12-16. Replaced by the `pricing_rule_reference` field. // Required: true Definition *LoyaltyProgramRewardDefinition `json:"definition"` // The Square-assigned ID of the reward tier. // Required: true // Max Length: 36 // Min Length: 1 ID *string `json:"id"` // The name of the reward tier. // Required: true // Min Length: 1 Name *string `json:"name"` // The points exchanged for the reward tier. // Required: true // Minimum: 1 Points *int64 `json:"points"` // A reference to the specific version of a `PRICING_RULE` catalog object that contains information about the reward tier discount. // // Use `object_id` and `catalog_version` with the `RetrieveCatalogObject` endpoint // to get discount details. Make sure to set `include_related_objects` to true in the request to retrieve all catalog objects // that define the discount. For more information, see [Get discount details for the reward](https://developer.squareup.com/docs/docs/loyalty-api/overview#get-discount-details). PricingRuleReference *CatalogObjectReference `json:"pricing_rule_reference,omitempty"` } // Validate validates this loyalty program reward tier func (m *LoyaltyProgramRewardTier) Validate(formats strfmt.Registry) error { var res []error if err := m.validateCreatedAt(formats); err != nil { res = append(res, err) } if err := m.validateDefinition(formats); err != nil { res = append(res, err) } if err := m.validateID(formats); err != nil { res = append(res, err) } if err := m.validateName(formats); err != nil { res = append(res, err) } if err := m.validatePoints(formats); err != nil { res = append(res, err) } if err := m.validatePricingRuleReference(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *LoyaltyProgramRewardTier) validateCreatedAt(formats strfmt.Registry) error { if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { return err } return nil } func (m *LoyaltyProgramRewardTier) validateDefinition(formats strfmt.Registry) error { if err := validate.Required("definition", "body", m.Definition); err != nil { return err } if m.Definition != nil { if err := m.Definition.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("definition") } return err } } return nil } func (m *LoyaltyProgramRewardTier) validateID(formats strfmt.Registry) error { if err := validate.Required("id", "body", m.ID); err != nil { return err } if err := validate.MinLength("id", "body", *m.ID, 1); err != nil { return err } if err := validate.MaxLength("id", "body", *m.ID, 36); err != nil { return err } return nil } func (m *LoyaltyProgramRewardTier) validateName(formats strfmt.Registry) error { if err := validate.Required("name", "body", m.Name); err != nil { return err } if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { return err } return nil } func (m *LoyaltyProgramRewardTier) validatePoints(formats strfmt.Registry) error { if err := validate.Required("points", "body", m.Points); err != nil { return err } if err := validate.MinimumInt("points", "body", *m.Points, 1, false); err != nil { return err } return nil } func (m *LoyaltyProgramRewardTier) validatePricingRuleReference(formats strfmt.Registry) error { if swag.IsZero(m.PricingRuleReference) { // not required return nil } if m.PricingRuleReference != nil { if err := m.PricingRuleReference.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("pricing_rule_reference") } return err } } return nil } // ContextValidate validate this loyalty program reward tier based on the context it is used func (m *LoyaltyProgramRewardTier) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateDefinition(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidatePricingRuleReference(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *LoyaltyProgramRewardTier) contextValidateDefinition(ctx context.Context, formats strfmt.Registry) error { if m.Definition != nil { if err := m.Definition.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("definition") } return err } } return nil } func (m *LoyaltyProgramRewardTier) contextValidatePricingRuleReference(ctx context.Context, formats strfmt.Registry) error { if m.PricingRuleReference != nil { if err := m.PricingRuleReference.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("pricing_rule_reference") } return err } } return nil } // MarshalBinary interface implementation func (m *LoyaltyProgramRewardTier) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *LoyaltyProgramRewardTier) UnmarshalBinary(b []byte) error { var res LoyaltyProgramRewardTier if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
go
14
0.702508
178
24.634454
238
starcoderdata
def testRollBack(self): conn = self.getConnection() crsr = conn.cursor() assert not crsr.connection.autocommit, 'Unexpected beginning condition' self.helpCreateAndPopulateTableTemp(crsr) crsr.connection.commit() # commit the first bunch crsr.execute("INSERT INTO xx_%s (fldData) VALUES(100)" % config.tmp) selectSql = "SELECT fldData FROM xx_%s WHERE fldData=100" % config.tmp crsr.execute(selectSql) rs = crsr.fetchall() assert len(rs) == 1 self.conn.rollback() crsr.execute(selectSql) assert crsr.fetchone() == None, 'cursor.fetchone should return None if a query retrieves no rows' crsr.execute('SELECT fldData from xx_%s' % config.tmp) rs = crsr.fetchall() assert len(rs) == 9, 'the original records should still be present' self.helpRollbackTblTemp()
python
8
0.646532
105
43.75
20
inline
#!/usr/bin/env node var program = require('commander') , replayer = require('./replayer'); program .version('1.0.0') .usage('[options] <log file>') .arguments(' .option('-o, --output [file]', 'result file', './result.log') .option('-r, --host [host]', 'host', 'localhost') .option('-t, --throttle [delay]', 'throttle (actual time/throttle)', 1) .option('-s, --skip [count]', 'skip the first [count] inital rows', 0) .option('-i, --include-static', 'include requests to static resources') .action(function(file, options) { options.includeStatic = !!options.includeStatic; console.log('log file = %s', file); console.log('output = %s', options.output); console.log('host = %s', options.host); console.log('throttle = %s', options.throttle); console.log('skip = %s', options.skip); console.log('static = %s', options.includeStatic); replayer.start(file, options.output, options.host, options.throttle, options.skip, options.includeStatic); }).parse(process.argv); if (program.args.length === 0) program.help();
javascript
23
0.635445
110
35.333333
30
starcoderdata
protected override void PreRender() { base.PreRender(); // Get all the renderable objects. var renderables = GetCameraVisibleRenderables(); // Create the predicate that checks if a given renderable is visible. isVisibleToCameraPredicate = null; // if null, then every renderable is visible. if (!(Camera is NullCamera)) { var hashSet = (HashSet<RenderableObject>)renderables; isVisibleToCameraPredicate = obj => hashSet.Contains(obj); } }
c#
13
0.582192
92
38
15
inline
<?php class NixFifty_AutoCloseThreads_XenForo_Model_Thread extends XFCP_NixFifty_AutoCloseThreads_XenForo_Model_Thread { public function prepareThreadFetchOptions(array $fetchOptions) { $joinOptions = parent::prepareThreadFetchOptions($fetchOptions); $selectFields = $joinOptions['selectFields']; $joinTables = $joinOptions['joinTables']; $orderClause = $joinOptions['orderClause']; if (!empty($fetchOptions['nfAutoClose'])) { $selectFields .= ", ( SELECT COUNT(auto_closed.thread_id) FROM xf_nf_auto_closed as auto_closed WHERE auto_closed.thread_id = thread.thread_id) AS nf_auto_close "; } return [ 'selectFields' => $selectFields, 'joinTables' => $joinTables, 'orderClause' => $orderClause ]; } }
php
13
0.670426
80
27.535714
28
starcoderdata
<?php declare(strict_types=1); /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace Rabbit\DB; use Rabbit\Base\Helper\StringHelper; class ColumnSchemaBuilder { const CATEGORY_PK = 'pk'; const CATEGORY_STRING = 'string'; const CATEGORY_NUMERIC = 'numeric'; const CATEGORY_TIME = 'time'; const CATEGORY_OTHER = 'other'; public array $categoryMap = [ Schema::TYPE_PK => self::CATEGORY_PK, Schema::TYPE_UPK => self::CATEGORY_PK, Schema::TYPE_BIGPK => self::CATEGORY_PK, Schema::TYPE_UBIGPK => self::CATEGORY_PK, Schema::TYPE_CHAR => self::CATEGORY_STRING, Schema::TYPE_STRING => self::CATEGORY_STRING, Schema::TYPE_TEXT => self::CATEGORY_STRING, Schema::TYPE_TINYINT => self::CATEGORY_NUMERIC, Schema::TYPE_SMALLINT => self::CATEGORY_NUMERIC, Schema::TYPE_INTEGER => self::CATEGORY_NUMERIC, Schema::TYPE_BIGINT => self::CATEGORY_NUMERIC, Schema::TYPE_FLOAT => self::CATEGORY_NUMERIC, Schema::TYPE_DOUBLE => self::CATEGORY_NUMERIC, Schema::TYPE_DECIMAL => self::CATEGORY_NUMERIC, Schema::TYPE_DATETIME => self::CATEGORY_TIME, Schema::TYPE_TIMESTAMP => self::CATEGORY_TIME, Schema::TYPE_TIME => self::CATEGORY_TIME, Schema::TYPE_DATE => self::CATEGORY_TIME, Schema::TYPE_BINARY => self::CATEGORY_OTHER, Schema::TYPE_BOOLEAN => self::CATEGORY_NUMERIC, Schema::TYPE_MONEY => self::CATEGORY_NUMERIC, ]; public ?Connection $db; public string $comment; protected string $type; protected int|string|array $length; protected ?bool $isNotNull; protected bool $isUnique = false; protected string $check; protected ExpressionInterface|PdoValue|Query|string|bool|array|int|float|null $default; protected $append; protected bool $isUnsigned = false; protected string $after; protected bool $isFirst; public function __construct(string $type, int|string|array $length = null, Connection $db = null) { $this->type = $type; $this->length = $length; $this->db = $db; } public function notNull(): self { $this->isNotNull = true; return $this; } public function unique(): self { $this->isUnique = true; return $this; } public function check(string $check): self { $this->check = $check; return $this; } public function defaultValue(ExpressionInterface|PdoValue|Query|string|bool|array|int|float|null $default): self { if ($default === null) { $this->null(); } $this->default = $default; return $this; } public function null(): self { $this->isNotNull = false; return $this; } public function comment(string $comment): self { $this->comment = $comment; return $this; } public function unsigned(): self { switch ($this->type) { case Schema::TYPE_PK: $this->type = Schema::TYPE_UPK; break; case Schema::TYPE_BIGPK: $this->type = Schema::TYPE_UBIGPK; break; } $this->isUnsigned = true; return $this; } public function after(string $after): self { $this->after = $after; return $this; } public function first(): self { $this->isFirst = true; return $this; } public function defaultExpression(string $default): self { $this->default = new Expression($default); return $this; } public function append(string $sql): self { $this->append = $sql; return $this; } public function __toString() { switch ($this->getTypeCategory()) { case self::CATEGORY_PK: $format = '{type}{check}{comment}{append}'; break; default: $format = '{type}{length}{notnull}{unique}{default}{check}{comment}{append}'; } return $this->buildCompleteString($format); } protected function getTypeCategory(): ?string { return isset($this->categoryMap[$this->type]) ? $this->categoryMap[$this->type] : null; } protected function buildCompleteString(string $format): string { $placeholderValues = [ '{type}' => $this->type, '{length}' => $this->buildLengthString(), '{unsigned}' => $this->buildUnsignedString(), '{notnull}' => $this->buildNotNullString(), '{unique}' => $this->buildUniqueString(), '{default}' => $this->buildDefaultString(), '{check}' => $this->buildCheckString(), '{comment}' => $this->buildCommentString(), '{pos}' => $this->isFirst ? $this->buildFirstString() : $this->buildAfterString(), '{append}' => $this->buildAppendString(), ]; return strtr($format, $placeholderValues); } protected function buildLengthString(): string { if ($this->length === null || $this->length === []) { return ''; } if (is_array($this->length)) { $this->length = implode(',', $this->length); } return "({$this->length})"; } protected function buildUnsignedString(): string { return ''; } protected function buildNotNullString(): string { if ($this->isNotNull === true) { return ' NOT NULL'; } elseif ($this->isNotNull === false) { return ' NULL'; } return ''; } protected function buildUniqueString(): string { return $this->isUnique ? ' UNIQUE' : ''; } protected function buildDefaultString(): string { if ($this->default === null) { return $this->isNotNull === false ? ' DEFAULT NULL' : ''; } $string = ' DEFAULT '; switch (gettype($this->default)) { case 'object': case 'integer': $string .= (string)$this->default; break; case 'double': // ensure type cast always has . as decimal separator in all locales $string .= StringHelper::floatToString($this->default); break; case 'boolean': $string .= $this->default ? 'TRUE' : 'FALSE'; break; default: $string .= "'{$this->default}'"; } return $string; } protected function buildCheckString(): string { return $this->check !== null ? " CHECK ({$this->check})" : ''; } protected function buildCommentString(): string { return ''; } protected function buildFirstString(): string { return ''; } protected function buildAfterString(): string { return ''; } protected function buildAppendString(): string { return $this->append !== null ? ' ' . $this->append : ''; } }
php
15
0.547011
116
25.531136
273
starcoderdata
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem.ui; import java.util.List; import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil; import org.eclipse.birt.chart.reportitem.api.ChartItemUtil; import org.eclipse.birt.chart.reportitem.ui.actions.FlipAxisAction; import org.eclipse.birt.chart.reportitem.ui.actions.OpenChartTaskAction; import org.eclipse.birt.chart.reportitem.ui.actions.ShowAxisAction; import org.eclipse.birt.chart.reportitem.ui.i18n.Messages; import org.eclipse.birt.chart.ui.util.ChartUIConstants; import org.eclipse.birt.chart.ui.util.UIHelper; import org.eclipse.birt.report.designer.ui.extensions.IMenuBuilder; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; /** * Chart menu extension for designer. */ public class ChartMenuBuilder implements IMenuBuilder { /* (non-Javadoc) * @see org.eclipse.birt.report.designer.ui.extensions.IMenuBuilder#buildMenu(org.eclipse.jface.action.IMenuManager, java.util.List) */ public void buildMenu( IMenuManager menu, List selectedList ) { if ( selectedList != null && selectedList.size( ) == 1 && ChartItemUtil.isChartHandle( selectedList.get( 0 ) ) ) { ExtendedItemHandle handle = (ExtendedItemHandle) selectedList.get( 0 ); Separator separator = new Separator( "group.chart" ); //$NON-NLS-1$ if ( menu.getItems( ).length > 0 ) { menu.insertBefore( menu.getItems( )[0].getId( ), separator ); } else { menu.add( separator ); } menu.appendToGroup( separator.getId( ), new OpenChartTaskAction( handle, "org.eclipse.birt.chart.ui.swt.wizard.TaskSelectType", //$NON-NLS-1$ Messages.getString( "OpenChartTaskAction.Text.SelectChartType" ),//$NON-NLS-1$ UIHelper.getImage( ChartUIConstants.IMAGE_TASK_TYPE ), true ) ); menu.appendToGroup( separator.getId( ), new OpenChartTaskAction( handle, "org.eclipse.birt.chart.ui.swt.wizard.TaskSelectData", //$NON-NLS-1$ Messages.getString( "OpenChartTaskAction.Text.SelectData" ), //$NON-NLS-1$ UIHelper.getImage( ChartUIConstants.IMAGE_TASK_DATA ), false ) ); menu.appendToGroup( separator.getId( ), new OpenChartTaskAction( handle, "org.eclipse.birt.chart.ui.swt.wizard.TaskFormatChart", //$NON-NLS-1$ Messages.getString( "OpenChartTaskAction.Text.FormatChart" ),//$NON-NLS-1$ UIHelper.getImage( ChartUIConstants.IMAGE_TASK_FORMAT ), false ) ); if ( ChartCubeUtil.isPlotChart( handle ) || ChartCubeUtil.isAxisChart( handle ) ) { menu.appendToGroup( separator.getId( ), new FlipAxisAction( handle ) ); menu.appendToGroup( separator.getId( ), new ShowAxisAction( handle ) ); } } } }
java
16
0.69086
133
37.045455
88
starcoderdata
""" Script principal do projeto Voice Unlocker responsável por coordenar o recebimento de novos áudios a serem validados e a execução do modelo preditivo treinado previamente de modo a apresentar um resultado ao executor do código. ------------------------------------------------------ SUMÁRIO ------------------------------------------------------ 1. Configuração inicial 1.1 Importação de bibliotecas 1.2 Instanciando objetos de log 2. Definição de variáveis do projeto 3. Definição de função com as regras de validação """ # Autor: # Data de Criação: 04/04/2021 """ ------------------------------------------------------ -------------- 1. CONFIGURAÇÃO INICIAL --------------- 1.1 Importação de bibliotecas ------------------------------------------------------ """ # Bibliotecas python import os import pandas as pd import joblib import logging from datetime import datetime import time import librosa from warnings import filterwarnings filterwarnings('ignore') # Third-party e self-made from ml.prep import * from pycomp.log.log_config import log_config """ ------------------------------------------------------ -------------- 1. CONFIGURAÇÃO INICIAL --------------- 1.2 Instanciando objetos de log ------------------------------------------------------ """ # Definindo objeto de log logger = logging.getLogger(__file__) logger = log_config(logger) """ ------------------------------------------------------ -------- 2. DEFINIÇÃO DE VARIÁVEIS DO PROJETO -------- ------------------------------------------------------ """ # Definindo variáveis de diretórios PROJECT_PATH = '/home/paninit/workspaces/voice-unlocker' PREDICTIONS_PATH = os.path.join(PROJECT_PATH, 'predictions') TARGET_PATH = os.path.join(PREDICTIONS_PATH, 'audios') RESULTS_PATH = os.path.join(PREDICTIONS_PATH, 'results') RESULTS_FILE = 'audio_verification_log.csv' # Definindo variáveis estruturantes de regras AUDIO_EXT = '.mp3' MOST_RECENT = True DROP_AUDIOS = True # Extraindo a quantidade de arquivos válidos na pasta alvo VALID_FILES = [file for file in os.listdir(TARGET_PATH) if os.path.splitext(file)[-1] == AUDIO_EXT] QTD_FILES = len(VALID_FILES) # Definindo variáveis para extração de artefatos PIPELINE_PATH = os.path.join(PROJECT_PATH, 'pipelines') PIPELINE_NAME = 'audio_fe_pipeline.pkl' MODEL_PATH = os.path.join(PROJECT_PATH, 'model') MODEL_NAME = 'lgbm_clf.pkl' # Definindo variáveis de leitura e predição de áudios SAMPLE_RATE = 22050 SIGNAL_COL = 'signal' SAVE_RESULTS = True """ ------------------------------------------------------ ---------- 3. REGRAS DE VALIDAÇÃO DE ÁUDIOS ---------- ------------------------------------------------------ """ if QTD_FILES == 0: # Nenhum áudio válido presente no diretório alvo logger.warning(f'Nenhum arquivo {AUDIO_EXT} encontrado no diretório. Verificar extensão do áudio disponibilizado.') exit() elif QTD_FILES > 1: # Mais de um áudio válido presente no diretório alvo logger.warning(f'Foram encontrados {QTD_FILES} arquivos {AUDIO_EXT} no diretório. Necessário validar um áudio por vez.') if MOST_RECENT: logger.debug(f'Considerando o áudio mais recente presente no diretório.') try: # Extraindo data de criação dos múltiplos áudios ctimes = [os.path.getctime(os.path.join(TARGET_PATH, file)) for file in VALID_FILES] audio_ctimes = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ct)) for ct in ctimes] # Indexando áudio mais recente idx_max_ctime = audio_ctimes.index(max(audio_ctimes)) audio_file = VALID_FILES[idx_max_ctime] except Exception as e: logger.error(f'Erro ao extrair o áudio mais recente. Exception: {e}') exit() else: exit() else: # Nenhuma regra de invalidação selecionada: referenciando áudio válido audio_file = VALID_FILES[0] logger.info(f'Regras de validação aplicadas. Áudio considerado: {audio_file}') """ ------------------------------------------------------ ------ 4. RESPOSTA A IDENTIFICAÇÃO DE LOCUTORES ------ 4.1 Importando artefatos ------------------------------------------------------ """ # Lendo pipeline de preparação e modelo treinado pipeline = joblib.load(os.path.join(PIPELINE_PATH, PIPELINE_NAME)) model = joblib.load(os.path.join(MODEL_PATH, MODEL_NAME)) """ ------------------------------------------------------ ------ 4. RESPOSTA A IDENTIFICAÇÃO DE LOCUTORES ------ 4.2 Lendo, preparando e realizando predições ------------------------------------------------------ """ # Lendo sinal de áudio selecionado t0 = time.time() logger.debug(f'Lendo sinal de áudio via librosa e transformando em DataFrame') try: audio = [librosa.load(os.path.join(TARGET_PATH, audio_file), sr=SAMPLE_RATE)[0]] audio_df = pd.DataFrame([audio]) audio_df.columns = [SIGNAL_COL] except Exception as e: logger.error(f'Erro ao ler ou transformar áudio. Exception: {e}') exit() # Aplicando pipeline no áudio selecionado logger.debug(f'Aplicando pipeline de preparação no áudio lido') try: audio_prep = pipeline.fit_transform(audio_df) audio_prep.drop(SIGNAL_COL, axis=1, inplace=True) except Exception as e: logger.error(f'Erro ao aplicar pipeline de preparação. Exception: {e}') exit() # Realizando predições logger.debug(f'Realizando predições no áudio selecionado') try: y_pred = model.predict(audio_prep) except Exception as e: logger.error(f'Erro ao realizar predição. Exception: {e}') exit() t1 = time.time() """ ------------------------------------------------------ ------------- 5. COORDENANDO RESULTADOS -------------- ------------------------------------------------------ """ if SAVE_RESULTS: logger.debug('Armazenando resultados') try: df_results = pd.DataFrame({}) df_results['audio_file'] = [audio_file] df_results['prediction'] = ['Locutor ' + str(y_pred[0])] df_results['exec_time'] = round((t1 - t0), 3) df_results['datetime'] = datetime.now() # Criando diretório de resultados, caso inexistente if not os.path.isdir(RESULTS_PATH): os.makedirs(RESULTS_PATH) # Lendo arquivo de resultados, caso já existente if RESULTS_FILE not in os.listdir(RESULTS_PATH): df_results.to_csv(os.path.join(RESULTS_PATH, RESULTS_FILE), index=False) else: old_results = pd.read_csv(os.path.join(RESULTS_PATH, RESULTS_FILE)) df_results = old_results.append(df_results) df_results.to_csv(os.path.join(RESULTS_PATH, RESULTS_FILE), index=False) except Exception as e: logger.error(f'Erro ao salvar os resultados. Exception: {e}') # Eliminando áudios if DROP_AUDIOS: logger.debug(f'Eliminando áudios no diretório alvo') try: for file in os.listdir(TARGET_PATH): os.remove(os.path.join(TARGET_PATH, file)) except Exception as e: logger.error(f'Erro ao eliminar áudios. Exception: {e}') logger.info('Fim do processamento')
python
16
0.591963
124
32.575472
212
starcoderdata
package org.collectionspace.services.nuxeo.listener; import java.io.Serializable; import java.util.Map; import org.collectionspace.services.config.tenant.EventListenerConfig; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventListener; public interface CSEventListener extends EventListener { /** * Register ourself as an event listener for the named repository -the repo name corresponds to a specific tenant. * @param respositoryName - The name of the Nuxeo repository which links us to a CollectionSpace tenant. * @param eventListenerConfig - Tenant bindings config for our listener. * @return */ boolean register(String respositoryName, EventListenerConfig eventListenerConfig); /** * Determines if we are a registered event listener for the given event. * @param event * @return */ boolean isRegistered(Event event); /** * Returns event listener related params that we're supplied in the tenant bindings. * @param event * @return */ Map<String, String> getParams(Event event); /** * Set's a property in a DocumetModel's transient data context. * * @param docModel * @param key * @param value */ void setDocModelContextProperty(DocumentModel docModel, String key, Serializable value); /** * Clears a property from a DocumentModel's transient data context. * @param docModel * @param key */ void clearDocModelContextProperty(DocumentModel docModel, String key); /** * Returns the name of the event listener as defined during registration -see register() method. * @return */ String getName(String repositoryName); }
java
7
0.74925
115
29.309091
55
starcoderdata
using System; using Crash.Core.Collections; namespace Crash.Editor.Engine.Model { using Myself = TextPos; /// /// エディタ上の位置を表す。 /// public readonly struct TextPos : IEquatable IComparable { private readonly (int lineIndex, int charIndex) _value; public static readonly TextPos Empty; /// public int LineIndex => _value.lineIndex; /// public int CharIndex => _value.charIndex; public TextPos(int lineIndex, int charIndex) { _value = (lineIndex, charIndex); } public void Deconstruct(out int lineIndex, out int charIndex) { (lineIndex, charIndex) = _value; } /// /// /// public TextPos GetNextPos(IReadOnlyTextDocument doc) { return (this == GetEndPos(doc)) ? this : (CharIndex < doc.Lines[LineIndex].Length) ? new TextPos(LineIndex, CharIndex + 1) : new TextPos(LineIndex + 1, 0); } /// /// /// public TextPos GetPrevPos(IReadOnlyTextDocument doc) { return (this == GetTopPos()) ? this : (CharIndex > 0) ? new TextPos(LineIndex, CharIndex - 1) : new TextPos(LineIndex - 1, doc.Lines[LineIndex - 1].Length); } /// /// /// public static TextPos GetTopPos() { return Empty; } /// /// /// public static TextPos GetEndPos(IReadOnlyTextDocument doc) { var lastIndex = doc.Lines.LastIndex(); return new TextPos(lastIndex, doc.Lines[lastIndex].Length); } #region 等値比較 public override int GetHashCode() => _value.GetHashCode(); public override bool Equals(object? obj) => obj is Myself other && Equals(other); public bool Equals(Myself other) => _value.Equals(other._value); public static bool operator ==(Myself left, Myself right) => left.Equals(right); public static bool operator !=(Myself left, Myself right) => !left.Equals(right); #endregion #region 大小比較 public int CompareTo(Myself other) => _value.CompareTo(other._value); public static bool operator >(Myself left, Myself right) => left.CompareTo(right) > 0; public static bool operator <(Myself left, Myself right) => left.CompareTo(right) < 0; public static bool operator >=(Myself left, Myself right) => left.CompareTo(right) >= 0; public static bool operator <=(Myself left, Myself right) => left.CompareTo(right) <= 0; #endregion } }
c#
18
0.572826
99
32.290698
86
starcoderdata
namespace Machete.X12.Tests.TestSchema { public interface LayoutCondition3Issue : X12Layout { Segment InterchangeControlHeader { get; } Segment FunctionalGroupHeader { get; } Segment TransactionSetHeader { get; } Segment BusinessContactInformation { get; } SegmentList TechnicalContactInformation { get; } Segment PayerWebsite { get; } Segment TransactionSetTrailer { get; } Segment FunctionalGroupTrailer { get; } Segment InterchangeControlTrailer { get; } } }
c#
8
0.626886
68
29.416667
24
starcoderdata
<?php namespace Configurator; class ConfiguratorData { private $environmentList; private $config = array(); private $configDefault = array(); private $configEnvironment = array(); private $configOverride = array(); public function __construct($environmentList) { $this->environmentList = $environmentList; } public function addData(array $data) { if (array_key_exists('default', $data) === true) { $this->addConfigDefault($data['default']); } foreach ($this->environmentList as $environment) { if (array_key_exists($environment, $data) === true) { $this->addConfigEnvironment($data[$environment]); } } if (array_key_exists('override', $data) === true) { $this->addConfigOverride($data['override']); } } public function addConfigDefault($data) { $this->configDefault = array_merge($this->configDefault, $data); } public function addConfigEnvironment($data) { $this->configEnvironment = array_merge($this->configEnvironment, $data); } public function addConfigOverride($data) { $this->configOverride = array_merge($this->configOverride, $data); } /** * Adds a constant with it's current value. This is useful for parsing the same settings * used on the current machine to a new machine e.g. when machine A is being used as the puppet * master for machine B, and you want machine B to use the same API key as machine A. * * @param $constantName * @throws \Exception */ public function addConstant($constantName) { if (defined($constantName) === false) { throw new ConfiguratorException("Constant [$constantName] is not available, cannot configurate."); } $this->config[$constantName] = constant($constantName); } /** * Adds a name value pair to the config. * @param $name * @param $value */ public function addConfigValue($name, $value) { $this->config[$name] = $value; } /** * @return array */ public function getConfig() { $config = $this->config; $config = array_merge($config, $this->configDefault); $config = array_merge($config, $this->configEnvironment); $config = array_merge($config, $this->configOverride); return $config; } }
php
15
0.586914
110
25.989362
94
starcoderdata
/* * Copyright 1999-2006 University of Chicago * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file globus_symboltable.h * @brief Lightweight Chaining Symboltable */ #ifndef GLOBUS_SYMBOLTABLE_H #define GLOBUS_SYMBOLTABLE_H #include "globus_hashtable.h" #ifdef __cplusplus extern "C" { #endif struct globus_symboltable_s; typedef struct globus_symboltable_s * globus_symboltable_t; extern int globus_symboltable_init( globus_symboltable_t * table, globus_hashtable_hash_func_t hash_func, globus_hashtable_keyeq_func_t keyeq_func); extern void * globus_symboltable_lookup (globus_symboltable_t *table, void *symbol); extern int globus_symboltable_insert (globus_symboltable_t *table, void *symbol, void *datum); extern void * globus_symboltable_remove (globus_symboltable_t *table, void *symbol); extern int globus_symboltable_create_scope (globus_symboltable_t *table); extern int globus_symboltable_remove_scope (globus_symboltable_t *table); extern int globus_symboltable_destroy (globus_symboltable_t *table); #ifdef __cplusplus } #endif #endif /* GLOBUS_SYMBOLTABLE_H */
c
11
0.692744
75
24.941176
68
starcoderdata
#include #include bool inside(point sq[4], point p){ map<int, int> cnt; for(int i=0; i<4; ++i){ int j = (i+1)%4; int cw = get sq[j]-p)); cnt[cw]++; } return cnt[1] and !cnt[-1] or cnt[-1] and !cnt[1]; } int32_t main(){ desync(); point a[4], b[4]; for(int i=0; i<4; ++i) cin >> a[i].x >> a[i].y; for(int i=0; i<4; ++i) cin >> b[i].x >> b[i].y; bool ans = false; for(int i=0; i<4; ++i){ int j = (i+1)%4; segment sa(a[i], a[j]); for(int k=0; k<4; ++k){ int l=(k+1)%4; segment sb(b[k], b[l]); ans |= intersect(sa, sb); } ans |= inside(a, b[i]); ans |= inside(b, a[i]); } cout << (ans? "YES":"NO") << endl; return 0; }
c++
14
0.448608
55
23.578947
38
starcoderdata
function (message) { // if the console is defined then log the message if (typeof (console) !== "undefined") { if (console.warn) { console.warn(message); } } }
javascript
11
0.613636
51
21.125
8
inline
function main(bucketName = 'my-bucket', fileName = 'test.txt') { // [START storage_configure_retries] /** * TODO(developer): Uncomment the following lines before running the sample. */ // The ID of your GCS bucket // const bucketName = 'your-unique-bucket-name'; // The ID of your GCS file // const fileName = 'your-file-name'; // Imports the Google Cloud client library const {Storage} = require('@google-cloud/storage'); // Creates a client const storage = new Storage({ retryOptions: { // If this is false, requests will not retry and the parameters // below will not affect retry behavior. autoRetry: true, // The multiplier by which to increase the delay time between the // completion of failed requests, and the initiation of the subsequent // retrying request. retryDelayMultiplier: 3, // The total time between an initial request getting sent and its timeout. // After timeout, an error will be returned regardless of any retry attempts // made during this time period. totalTimeout: 500, // The maximum delay time between requests. When this value is reached, // retryDelayMultiplier will no longer be used to increase delay time. maxRetryDelay: 60, // The maximum number of automatic retries attempted before returning // the error. maxRetries: 5, // Will respect other retry settings and attempt to always retry // conditionally idempotent operations, regardless of precondition idempotencyStrategy: IdempotencyStrategy.RetryAlways, }, }); console.log( 'Functions are customized to be retried according to the following parameters:' ); console.log(`Auto Retry: ${storage.retryOptions.autoRetry}`); console.log( `Retry delay multiplier: ${storage.retryOptions.retryDelayMultiplier}` ); console.log(`Total timeout: ${storage.retryOptions.totalTimeout}`); console.log(`Maximum retry delay: ${storage.retryOptions.maxRetryDelay}`); console.log(`Maximum retries: ${storage.retryOptions.maxRetries}`); console.log( `Idempotency strategy: ${storage.retryOptions.idempotencyStrategy}` ); async function deleteFileWithCustomizedRetrySetting() { await storage.bucket(bucketName).file(fileName).delete(); console.log(`File ${fileName} deleted with a customized retry strategy.`); } deleteFileWithCustomizedRetrySetting(); // [END storage_configure_retries] }
javascript
13
0.708671
83
39.47541
61
inline
//TypeChecks import isClass from 'JSUI/Source/1.0.0/TypeChecks/isClass'; import isUClass from 'JSUI/Source/1.0.0/TypeChecks/isUClass'; //Utilities import exports from 'Parcello/exports'; export default function getHandledType(types, u){ let type = typeof u; if (type === 'function') { type = (isUClass(u) ? 'uclass' : type); } if (type === 'object') { type = (isClass(u) ? 'class' : type); } let subtypes = types[type]; if (!subtypes) { return type; } for (let name in subtypes) { let subtype = subtypes[name]; if (subtype(u)) { return name; } } return type; }; exports(getHandledType).as('JSUI/Source/1.0.0/Utilities/TypeChecks/getHandledType');
javascript
9
0.684347
90
21.735294
34
starcoderdata
import { h } from 'preact' import { computeDateFormat, computeDate, computeTime } from 'utils' import style from './styles.scss' const viewStrings = locale.cp.overview.uploads.upload // eslint-disable-line no-undef export default function UploadData ({ data }) { return ( <div class={`${style.data} flex flex-cross-center flex-sa`}> <div class={`${style.dataSpec} flex flex-dc`}> {data.id} {data.extension} <div class={`${style.dataDate} flex flex-dc`} title={computeDateFormat(data.createdAt)}> {computeDate(data.createdAt)}<br />{computeTime(data.createdAt)} ) }
javascript
13
0.669556
116
37.458333
24
starcoderdata
<?php namespace App\Http\Controllers\order; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Cart; use App\model\product; use App\model\order; use App\model\invoice; use App\model\vendor; use Session; class orderController extends Controller { public function place_order() { $cart = Cart::content(); return view('Client.placeorder.placeorder',[ 'cart' => $cart, ]); } public function confirm_order(Request $request) { $order = new order(); $order->payment_method = $request->payment_method; $order->customer_id = Session::get('client_id'); $order->total_cost = Session::get('orderTotal'); $order->delivery_location = $request->shipping_address; $order->coupon = $request->coupon; $order->transaction_id = $request->transaction_id; $order->status = $request->status; $order->save(); $cartproduct = Cart::content(); foreach($cartproduct as $v_cartpro){ $pInfo=product::find($v_cartpro->id); $invoice = new invoice(); $invoice->vendor_id=$pInfo->vendor->id; $invoice->order_id = $order->id; $invoice->product_id = $v_cartpro->id; $invoice->product_unite_price = $v_cartpro->price; $invoice->product_quantity = $v_cartpro->qty; $invoice->save(); } Cart::destroy(); return view('Client.placeorder.confirm_order'); } }
php
14
0.568327
63
29.115385
52
starcoderdata
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using IISLogParser; namespace IISLogViewer { public partial class frmMain : Form { private string _logFile; private LogParser _parser; public frmMain() { InitializeComponent(); } private void UpdateProgress(object sender, int position, int count) { progress.Maximum = count; progress.Value = position; Application.DoEvents(); Cursor.Current = Cursors.WaitCursor; } private void ParseLogFile() { Cursor.Current = Cursors.WaitCursor; progress.Visible = true; _parser = new LogParser(); _parser.ParseLog(_logFile, UpdateProgress); DataTable table = _parser.GridList; grid.DataSource = table; lblCount.Text = String.Format("Count: {0:n0}", table.Rows.Count); grid.Columns[grid.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Cursor.Current = Cursors.Default; progress.Visible = false; } private void ResetFields() { lblCount.Text = "Count:"; progress.Visible = false; grid.DataSource = null; } private void OpenFile() { DateTime start = DateTime.Now; if (openFileDlg.ShowDialog(this) == DialogResult.OK) { ResetFields(); _logFile = openFileDlg.FileName; txtPath.Text = _logFile; ParseLogFile(); } TimeSpan time = DateTime.Now - start; lblCount.Text += " - (" + time.Duration().ToString() + ")"; } private void btnGo_Click(object sender, EventArgs e) { OpenFile(); } private void mnuOpen_Click(object sender, EventArgs e) { OpenFile(); } private void mnuEditDistinct_Click(object sender, EventArgs e) { if (_parser != null) { frmDistinct frm = new frmDistinct(); frm.Parser = _parser; frm.ShowDialog(this); frm.Dispose(); } } } }
c#
15
0.623161
92
21.902174
92
starcoderdata
/* ========================================================= * RequestMethods.java * * Author: kmchugh * Created: 29-May-2008, 12:17:26 * * Description * -------------------------------------------------------- * General Class Description. * * Change Log * -------------------------------------------------------- * Init.Date Ref. Description * -------------------------------------------------------- * * =======================================================*/ package Goliath.Web.Constants; /** * Class Description. * For example: * * Example usage * * * @see Related Class * @version 1.0 29-May-2008 * @author kmchugh **/ public class RequestMethod extends Goliath.DynamicEnum { /** * Creates a new instance of a RequestMethods Object * * @param tcValue The value for the string format type * @throws Goliath.Exceptions.InvalidParameterException */ protected RequestMethod(String tcValue) { super(tcValue); } private static RequestMethod g_oGet; public static RequestMethod GET() { if (g_oGet == null) { g_oGet = createEnumeration(RequestMethod.class, "GET", (java.lang.Object[])null); } return g_oGet; } private static RequestMethod g_oPost; public static RequestMethod POST() { if (g_oPost == null) { g_oPost = createEnumeration(RequestMethod.class, "POST", (java.lang.Object[])null); } return g_oPost; } private static RequestMethod g_oDelete; public static RequestMethod DELETE() { if (g_oDelete == null) { g_oDelete = createEnumeration(RequestMethod.class, "DELETE", (java.lang.Object[])null); } return g_oDelete; } private static RequestMethod g_oHead; public static RequestMethod HEAD() { if (g_oHead == null) { g_oHead = createEnumeration(RequestMethod.class, "HEAD", (java.lang.Object[])null); } return g_oHead; } private static RequestMethod g_oUnknown; public static RequestMethod UNKNOWN() { if (g_oUnknown == null) { g_oUnknown = createEnumeration(RequestMethod.class, "UNKNOWN", (java.lang.Object[])null); } return g_oUnknown; } private static RequestMethod g_oPut; public static RequestMethod PUT() { if (g_oPut == null) { g_oPut = createEnumeration(RequestMethod.class, "PUT", (java.lang.Object[])null); } return g_oPut; } private static RequestMethod g_oOptions; public static RequestMethod OPTIONS() { if (g_oOptions == null) { g_oOptions = createEnumeration(RequestMethod.class, "OPTIONS", (java.lang.Object[])null); } return g_oOptions; } private static RequestMethod g_oTrace; public static RequestMethod TRACE() { if (g_oTrace == null) { g_oTrace = createEnumeration(RequestMethod.class, "TRACE", (java.lang.Object[])null); } return g_oTrace; } private static RequestMethod g_oConnect; public static RequestMethod CONNECT() { if (g_oConnect == null) { g_oConnect = createEnumeration(RequestMethod.class, "CONNECT", (java.lang.Object[])null); } return g_oConnect; } }
java
15
0.527628
101
24.948529
136
starcoderdata
<?php /** * Copyright (c) 2020. * Under Mit License * php version 7.2 * * link https://github.com/allanmcarvalho/cakephp-data-renderer * author */ namespace DataTables\Test\TestCase\Table\Option\Callback; use Cake\Core\Configure; use Cake\Error\FatalErrorException; use Cake\TestSuite\TestCase; use DataTables\Plugin; use DataTables\Table\Option\CallBack\MainCallBack; use InvalidArgumentException; use TestApp\Application; /** * Class MainCallBackTest * * @author * @license MIT License https://github.com/allanmcarvalho/cakephp-datatables/blob/master/LICENSE * @link https://github.com/allanmcarvalho/cakephp-datatables */ class MainCallBackTest extends TestCase { /** * setUp method * * @return void */ public function setUp(): void { parent::setUp(); $plugin = new Plugin(); $plugin->bootstrap(new Application('')); Configure::write('DataTables.resources.templates', DATA_TABLES_TESTS . 'test_app' . DS . 'templates' . DS . 'data_tables'); } /** * tearDown method * * @return void */ public function tearDown(): void { parent::tearDown(); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testWithFile() { MainCallBack::destroyAllInstances(); $createdCellCallback = MainCallBack::getInstance('createdCell', 'Categories', 'main'); $this->assertNotEmpty($createdCellCallback->render()); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testWithBody() { MainCallBack::destroyAllInstances(); $createdCellCallback = MainCallBack::getInstance('createdCell', 'Categories', 'main'); $this->assertNotEmpty($createdCellCallback->render('abc')); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testWithCache() { MainCallBack::destroyAllInstances(); Configure::write('debug', false); $createdCellCallback = MainCallBack::getInstance('createdCell', 'Categories', 'main'); $this->assertNotEmpty($createdCellCallback->render('abc')); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testAppTemplateNotFound() { MainCallBack::destroyAllInstances(); $this->expectException(FatalErrorException::class); MainCallBack::getInstance('abc', 'Categories', 'main')->render(); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testPluginTemplateNotFound() { MainCallBack::destroyAllInstances(); $this->expectException(FatalErrorException::class); MainCallBack::getInstance('abc', 'Categories', 'main')->render('abc'); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testInvalidBodyOrParams1() { MainCallBack::destroyAllInstances(); $this->expectException(InvalidArgumentException::class); MainCallBack::getInstance('createdCell', 'Categories', 'main')->render(3); } /** * @return void * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function testInvalidBodyOrParams2() { MainCallBack::destroyAllInstances(); $this->expectException(InvalidArgumentException::class); MainCallBack::getInstance('createdCell', 'Categories', 'main')->render(true); } }
php
15
0.708457
125
26.213235
136
starcoderdata
<?php namespace App\Models\Tenant; use App\Models\BaseModel; class ProductImage extends BaseModel { protected $fillable = [ 'image', 'image_type', 'original_image_name', 'view', 'crop_coordinates', 'web_url', 'path', 'active', 'comments', 'date_added' ]; }
php
9
0.628472
38
12.136364
22
starcoderdata
/* Rhino-Require is Public Domain The author or authors of this code dedicate any and all copyright interest in this code to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this code under copyright law. */ (function(global) { var require = global.require = function(id) { if (typeof arguments[0] !== 'string') throw 'USAGE: require(moduleId)'; var moduleContent = '', moduleUrl; moduleUrl = require.resolve(id); moduleContent = ''; var file = new java.io.File(moduleUrl); try { var scanner = new java.util.Scanner(file).useDelimiter("\\Z"); moduleContent = String( scanner.next() ); } catch(e) { throw 'Unable to read file at: '+moduleUrl+', '+e; } if (moduleContent) { try { var f = new Function('require', 'exports', 'module', '__dirname', moduleContent), exports = require.cache[moduleUrl] || {}, module = { id: id, uri: moduleUrl, exports: exports }; require._root.unshift(toDir(moduleUrl)); (function(__dirname) { /*debug*///var lineno=1;print('\n== '+moduleUrl+' ===============\n1'+moduleContent.replace(/(\n)/g, function(m, i){return '\n'+(++lineno);})); f.call({}, require, exports, module, __dirname); })(require._root[0]); require._root.shift(); } catch(e) { throw 'Unable to require source code from "' + moduleUrl + '": ' + e.toSource(); } exports = module.exports || exports; require.cache[id] = exports; } else { throw 'The requested module cannot be returned: no content for id: "' + id + '" in paths: ' + require.paths.join(', '); } return exports; } require._root = [__dirname]; // the dir of the script that is calling require() require.paths = []; require.cache = {}; // cache module exports. Like: {id: exported} var SLASH = Packages.java.io.File.separator; /** Given a module id, try to find the path to the associated module. */ require.resolve = function(id) { var parts = id.match(/^(\.\/|\/)?(.+)$/), isRelative = false, isAbsolute = false, isInModule = false, basename = id, url = ''; if (parts) { isRelative = parts[1] === './'; isAbsolute = parts[1] === '/'; isInModule = !(isRelative || isAbsolute); basename = parts[2]; } if (typeof basename === 'undefined') { throw new Error('Malformed module identifier: '+id); } if (isAbsolute) { rootedId = id; } else if (isRelative) { var root = require._root[0], rootedId = root + '/' + basename; } if (rootedId) { if ( url = loadAsFile(rootedId) ) { return url; } else if ( url = loadAsDir(rootedId) ) { return url; } } else if (isInModule) { var url, paths = require.paths; for (var i = 0, len = paths.length; i < len; i++) { rootedId = paths[i] + '/' + basename; if ( url = loadAsFile(rootedId) ) { return url; } else if ( url = loadAsDir(rootedId) ) { return url; } } if (url = findInNodemodules(require._root[0], basename, 'rhino_modules')) { return url; } if (url = findInNodemodules(require._root[0], basename, 'node_modules')) { return url; } } throw new Error('Module not found: '+id); } function loadAsFile(id) { if ( isFile(id) ) { return id; } if ( isFile(id + '.js') ) { return id + '.js'; } } function loadAsDir(id) { // look for the "main" property of the package.json file if ( isFile(id + '/' + 'package.json') ) { var packageJson = readFileSync(id + '/' + 'package.json', 'utf-8'); eval( 'packageJson = '+ packageJson); if (packageJson.hasOwnProperty('main')) { var main = deDotPath(id + '/' + packageJson.main); return require.resolve(main); } } if ( isFile(id + '/' + 'index.js') ) { return id + '/' + 'index.js'; } } function findInNodemodules(root, id, moduleFolderName) { var dirs = root.split('/'), dir = '', rootedId; while (dirs.length) { dir = dirs.join('/'); rootedId = dir + '/' + moduleFolderName + '/' + id; if ( url = loadAsFile(rootedId) ) { return url; } else if ( url = loadAsDir(rootedId) ) { return url; } dirs.pop(); } } /** Given a path, return the base directory of that path. @example toDir('/foo/bar/somefile.js'); => '/foo/bar' */ function toDir(path) { var file = new java.io.File(path); if (file.isDirectory()) { return path; } var parts = path.split('/'); parts.pop(); return parts.join('/'); } /** Returns true if the given path exists and is a file. */ function isFile(path) { var file = new java.io.File(path); if (file.isFile()) { return true; } return false; } /** Returns true if the given path exists and is a directory. */ function isDir(path) { var file = new java.io.File(path); if (file.isDirectory()) { return true; } return false; } /** Resolve dots in filepaths. */ function deDotPath(path) { return String(path) .replace(/(\/|\\)[^\/\\]+\/\.\.(\/|\\)/g, '/') .replace(/(\/|\\)\.(\/|\\|$)/g, '/'); } function readFileSync(filename, encoding, callback) { if (typeof arguments[1] === 'function') { encoding = null; callback = arguments[1]; } encoding = encoding || java.lang.System.getProperty('file.encoding'); try { var content = new java.util.Scanner( new java.io.File(filename), encoding ).useDelimiter("\\Z"); return String( content.next() ); } catch (e) { return ''; } } })(this);
javascript
24
0.474251
167
31.193694
222
starcoderdata
<?php declare(strict_types=1); namespace AstrobinWs\Services; use AstrobinWs\AbstractWebService; use AstrobinWs\Exceptions\WsException; use AstrobinWs\Exceptions\WsResponseException; use AstrobinWs\Filters\UserFilters; use AstrobinWs\Response\AstrobinResponse; use AstrobinWs\Response\User; /** * Class GetUser * @package AstrobinWs\Services */ class GetUser extends AbstractWebService implements WsInterface { private const END_POINT = 'userprofile'; /** * @inheritDoc */ protected function getEndPoint(): string { return self::END_POINT; } /** * @inheritDoc */ protected function getObjectEntity(): ?string { return User::class; } /** * @inheritDoc */ protected function getCollectionEntity(): ?string { return null; } /** * Get user by id * * @param string|null $id * * @return AstrobinResponse|null * @throws WsException * @throws WsResponseException * @throws \JsonException * @throws \ReflectionException */ public function getById(?string $id): ?AstrobinResponse { $response = $this->get($id, null); return $this->buildResponse($response); } /** * Get user by username * * @param string $username * @param int $limit * * @return AstrobinResponse|null * @throws WsException * @throws WsResponseException * @throws \JsonException * @throws \ReflectionException */ public function getByUsername(string $username, int $limit): ?AstrobinResponse { if (empty($username)) { return null; } if (parent::LIMIT_MAX < $limit) { return null; } $response = $this->get(null, [UserFilters::USERNAME_FILTER => $username, [UserFilters::LIMIT => $limit]]); return $this->buildResponse($response); } }
php
15
0.612087
114
20.511111
90
starcoderdata
import styled from 'styled-components'; import { light } from './Theme'; const Nav = styled.nav` width: 100%; padding: 0.7rem 0; position: fixed; top: 4.8rem; left: 0; z-index: 200; background: ${(props) => props.theme.bgAdd}; box-shadow: 0 3px 6px 0 rgba(104, 104, 104, 0.5); opacity: ${(props) => (props.hide ? '0' : '1.0')}; transition: opacity 0.2s linear; @media screen and (min-width: 40rem) { width: 50%; top: 1rem; left: 47%; box-shadow: none; opacity: 1; } `; Nav.defaultProps = { theme: light, hide: true, }; export default Nav;
javascript
10
0.598985
52
18.7
30
starcoderdata
package com.example.experiment_automata; import com.example.experiment_automata.backend.questions.Question; import com.example.experiment_automata.backend.questions.QuestionManager; import com.example.experiment_automata.backend.questions.Reply; import org.junit.After; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; public class QuestionManagerTest { private QuestionManager questionManager; private ArrayList questions; private ArrayList replies; private String question; private UUID userId; private UUID experimentId; private UUID questionId; private String reply; private UUID replyId; @BeforeEach public void runningSetup() { QuestionManager.enableTestMode(); QuestionManager.resetInstance(); questionManager = QuestionManager.getInstance(); questions = new ArrayList<>(); replies = new ArrayList<>(); question = "Question"; userId = UUID.randomUUID(); experimentId = UUID.randomUUID(); questionId = UUID.randomUUID(); Question q = new Question(question, userId, experimentId, questionId); questions.add(q); questionManager.addQuestion(experimentId, q); reply = "Reply"; replyId = UUID.randomUUID(); Reply r = new Reply(reply, questionId, userId, replyId); replies.add(r); questionManager.addReply(questionId, r); } @Test public void testAddQuestion() { assertEquals(questions.get(0), questionManager.getQuestion(questionId)); Question newQuestion = new Question(question, userId, experimentId, UUID.randomUUID()); try { questionManager.getQuestion(newQuestion.getQuestionId()); fail("Should not have found the question"); } catch (IllegalArgumentException ignored) {} questionManager.addQuestion(experimentId, newQuestion); assertEquals(newQuestion, questionManager.getQuestion(newQuestion.getQuestionId())); } @Test public void testAddReply() { assertEquals(replies.get(0), questionManager.getQuestionReply(questionId).get(0)); Reply newReply = new Reply("New reply", questionId, userId, UUID.randomUUID()); assertEquals(1, questionManager.getQuestionReply(questionId).size()); questionManager.addReply(questionId, newReply); assertEquals(2, questionManager.getQuestionReply(questionId).size()); Reply duplicateReply = new Reply(reply, questionId, userId, replyId); questionManager.addReply(questionId, duplicateReply); assertEquals(2, questionManager.getQuestionReply(questionId).size()); } @Test public void testGetQuestion() { assertEquals(questions.get(0), questionManager.getQuestion(questionId)); assertThrows(IllegalArgumentException.class, () -> questionManager.getQuestion(UUID.randomUUID())); } @Test public void testGetTotalQuestions() { assertEquals(1, questionManager.getTotalQuestions(experimentId)); Question newQuestion = new Question(question, userId, experimentId, UUID.randomUUID()); assertEquals(1, questionManager.getTotalQuestions(experimentId)); questionManager.addQuestion(newQuestion.getExperimentId(), newQuestion); assertEquals(2, questionManager.getTotalQuestions(experimentId)); assertEquals(-1, questionManager.getTotalQuestions(UUID.randomUUID())); } @Test public void testGetExperimentQuestions() { assertEquals(1, questionManager.getExperimentQuestions(experimentId).size()); assertEquals(questions.get(0), questionManager.getExperimentQuestions(experimentId).get(0)); Question newQuestion = new Question(question, userId, experimentId, UUID.randomUUID()); assertEquals(1, questionManager.getExperimentQuestions(experimentId).size()); questionManager.addQuestion(newQuestion.getExperimentId(), newQuestion); assertEquals(2, questionManager.getExperimentQuestions(experimentId).size()); assertTrue(questionManager.getExperimentQuestions(experimentId).contains(newQuestion), "Error, does not contain newQuestion"); assertThrows(IllegalArgumentException.class, () -> questionManager.getExperimentQuestions(UUID.randomUUID())); } @Test public void testGetQuestionReply() { assertEquals(1, questionManager.getQuestionReply(questionId).size()); assertEquals(replies.get(0), questionManager.getQuestionReply(questionId).get(0)); UUID newReplyUUID = UUID.randomUUID(); Reply newReply = new Reply("New reply", questionId, userId, newReplyUUID); assertEquals(1, questionManager.getQuestionReply(questionId).size()); questionManager.addReply(questionId, newReply); assertEquals(2, questionManager.getQuestionReply(questionId).size()); assertTrue(questionManager.getQuestionReply(questionId).contains(newReply), "Error, could not find new reply"); UUID newQuestionUUID = UUID.randomUUID(); Question otherQuestion = new Question("Other Question", userId, experimentId, newQuestionUUID); Reply otherReply = new Reply("Other reply", newQuestionUUID, userId, UUID.randomUUID()); assertEquals(0, questionManager.getQuestionReply(newQuestionUUID).size()); questionManager.addQuestion(experimentId, otherQuestion); questionManager.addReply(newQuestionUUID, otherReply); assertEquals(otherReply, questionManager.getQuestionReply(newQuestionUUID).get(0)); assertEquals(2, questionManager.getQuestionReply(questionId).size()); } @Test public void testGetAllQuestions() { assertEquals(1, questionManager.getAllQuestions().iterator().next().size()); Question newQuestion = new Question("New Question", userId, experimentId, UUID.randomUUID()); questionManager.addQuestion(experimentId, newQuestion); assertEquals(2, questionManager.getAllQuestions().iterator().next().size()); assertTrue(questionManager.getAllQuestions().iterator().next().contains(questions.get(0)), "Does not contain original item"); assertTrue(questionManager.getAllQuestions().iterator().next().contains(newQuestion), "Does not contain new item"); } @After public void finish() { QuestionManager.disableTestMode(); } }
java
11
0.725554
134
48.057971
138
starcoderdata
using ProviderBase.Data.Entities; using KeyType = ProviderBase.Data.Entities.DataProviderKeyType; using FieldAction = ProviderBase.Data.Entities.DataProviderResultFieldAction; namespace ProviderBase.Framework.Entities { [DataProviderTable("MediaFileType_T")] public enum MediaFileType { Unassigned = 0, Image = 1, Video = 2 } [DataProviderTable("MediaType_T")] public enum MediaType { Unassigned = 0, Progress = 1, CharacterClass = 2, CharacterClassSpec = 3, ProgressDetail = 4, ClassRoleRecruitment = 5, CharacterRace = 6, CharacterFaction = 7, CharacterUser = 8, CustomFieldItem = 9, CharacterSpell = 10, ProgressItem = 11 } [DataProviderTable("Media_T")] public class Media { [DataProviderResultField("MediaID", KeyType.PrimaryKey, FieldAction.Select, FieldAction.Where)] public int MediaID { get; set; } [DataProviderResultField("MediaTypeID", KeyType.ForeignKey, FieldAction.Select, FieldAction.Insert, FieldAction.Update)] public MediaType MediaTypeID { get; set; } [DataProviderResultField("Title", FieldAction.Select, FieldAction.Insert, FieldAction.Update)] public string Title { get; set; } [DataProviderResultField("MediaLocation", FieldAction.Select, FieldAction.Insert, FieldAction.Update)] public string MediaLocation { get; set; } [DataProviderResultField("MediaName", FieldAction.Select, FieldAction.Insert, FieldAction.Update)] public string MediaName { get; set; } [DataProviderResultField("MediaFileTypeID", KeyType.ForeignKey, FieldAction.Select, FieldAction.Insert, FieldAction.Update)] public MediaFileType MediaFileTypeID { get; set; } public string MediaFullName { get { return this.MediaLocation + this.MediaName; } } [DataProviderResultField("MediaAltText", FieldAction.Select, FieldAction.Insert, FieldAction.Update)] public string MediaAltText { get; set; } public Media() { this.MediaID = 0; this.MediaTypeID = MediaType.Unassigned; this.Title = ""; this.MediaLocation = ""; this.MediaName = ""; this.MediaFileTypeID = MediaFileType.Unassigned; this.MediaAltText = ""; } } }
c#
13
0.639873
132
31.636364
77
starcoderdata
const apiUrl = 'https://www.googleapis.com/webfonts/v1/webfonts?' const fontUrl = '//fonts.googleapis.com/css?' const defaultFields = { category: false, files: false, family: true, lastModified: false, subsets: false, variants: false, version: false } const defaultSubsets = { latin: false, latinExtended: false, sinhala: false, greek: false, hebrew: false, vietnamese: false, cyrillic: false, cyrillicExtended: false, devanagari: false, arabic: false, khmer: false, tamil: false, greekExtended: false, thai: false, bengali: false, gujarati: false, oriya: false, malayalam: false, gurmukhi: false, kannada: false, telugu: false, myanmar: false } const defaultVariants = { thin: false, thinItalic: false, extraLight: false, extraLightItalic: false, light: false, lightItalic: false, regular: false, italic: false, medium: false, mediumItalic: false, semiBold: false, semiBoldItalic: false, bold: false, boldItalic: false, extraBold: false, extraBoldItalic: false, black: false, blackItalic: false } const variant = { thin: { value: 100, name: 'Thin' }, thinItalic: { value: 100, italic: true, name: 'Thin Italic' }, extraLight: { value: 200, name: 'Extra Light' }, extraLightItalic: { value: 200, italic: true, name: 'Extra Light Italic' }, light: { value: 300, name: 'Light' }, lightItalic: { value: 300, italic: true, name: 'Light Italic' }, regular: { value: 400, alias: 'regular', name: 'Regular' }, italic: { value: 400, italic: true, alias: 'italic', name: 'Italic' }, medium: { value: 500, name: 'Medium' }, mediumItalic: { value: 500, italic: true, name: 'Medium Italic' }, semiBold: { value: 600, name: 'Semi Bold' }, semiBoldItalic: { value: 600, italic: true, name: 'Semi Bold Italic' }, bold: { value: 700, name: 'Bold' }, boldItalic: { value: 700, italic: true, name: 'Bold Italic' }, extraBold: { value: 800, name: 'Extra Bold' }, extraBoldItalic: { value: 800, italic: true, name: 'Extra Bold Italic' }, black: { value: 900, name: 'Black' }, blackItalic: { value: 900, italic: true, name: 'Black Italic' } } const sortBy = { ALPHA: 'alpha', DATE: 'date', SYLE: 'style', TRENDING: 'trending', POPULAR: 'popularity' } const categories = { ALL: '', SERIF: 'serif', SANS_SERIF: 'sans-serif', DISPLAY: 'display', HANDWRITING: 'handwriting', MONOSPACE: 'monospace' } module.exports = { apiUrl, fontUrl, defaultFields, defaultSubsets, defaultVariants, categories, variant, sortBy }
javascript
8
0.607969
65
15.343023
172
starcoderdata
package life.catalogue.dw.jersey.filter; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.HttpMethod; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.util.Collection; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Filter that updates Cache-Control http headers to allow caching of responses belonging to static released datasets. * The following headers are added or replaced if they existed: */ public class CacheControlResponseFilter implements ContainerResponseFilter { private static final Logger LOG = LoggerFactory.getLogger(CacheControlResponseFilter.class); private static final long MAX_AGE = TimeUnit.HOURS.toSeconds(24); // age in seconds private static final String CACHE24 = "public, max-age=" + MAX_AGE + ", s-maxage=" + MAX_AGE; private static final Pattern DATASET_PATH = Pattern.compile("dataset/(\\d+)"); private static final Pattern STATIC_PATH = Pattern.compile("^(vocab|openapi|version)"); private static final Set METHODS = Set.of(HttpMethod.GET, HttpMethod.HEAD); private final IntSet releases = new IntOpenHashSet(); @Override public void filter(ContainerRequestContext req, ContainerResponseContext resp) throws IOException { if (req.getMethod() != null && METHODS.contains(req.getMethod())) { if (STATIC_PATH.matcher(req.getUriInfo().getPath()).find()) { allowCaching(resp); return; } Matcher m = DATASET_PATH.matcher(req.getUriInfo().getPath()); if (m.find()) { // parsing cannot fail, we have a pattern int datasetKey = Integer.parseInt(m.group(1)); if (releases.contains(datasetKey)) { // its a release, we can cache it! allowCaching(resp); return; } } } preventCaching(resp); } public boolean add(int key) { LOG.info("Added release {}", key); return releases.add(key); } public boolean addAll(@NotNull Collection<? extends Integer> keys) { LOG.info("Added {} release keys", keys.size()); return releases.addAll(keys); } private void allowCaching(ContainerResponseContext resp){ resp.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, CACHE24); } private void preventCaching(ContainerResponseContext resp){ resp.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, "must-revalidate,no-cache,no-store"); } public void addRelease(int datasetKey){ add(datasetKey); } }
java
15
0.726056
118
35.883117
77
starcoderdata
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [ InstanceSerializer( item, context={ 'request': self.context.get('request') } ).data for item in atmo_user.instance_set.filter( only_current(), source__provider__active=True, projects=None ) ] def get_user_volumes(self, atmo_user): return [ VolumeSerializer( item, context={ 'request': self.context.get('request') } ).data for item in atmo_user.volume_set().filter( *only_current_source(), instance_source__provider__active=True, projects=None ) ] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
python
16
0.601056
76
33
39
starcoderdata
namespace MainProject.UserInterface.Static { partial class CowPriceChartForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint1 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint2 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint3 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint4 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint5 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint6 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint7 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint8 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint9 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint10 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint11 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint12 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint13 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint14 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint15 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint16 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint17 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint18 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint19 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint20 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint21 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint22 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint23 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint24 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.Series series3 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint25 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint26 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint27 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint28 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint29 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint30 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint31 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint32 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint33 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint34 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint35 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint36 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.Series series4 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint37 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint38 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint39 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint40 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint41 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint42 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint43 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint44 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint45 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint46 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint47 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint48 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D); this.CowPriceChart = new System.Windows.Forms.DataVisualization.Charting.Chart(); ((System.ComponentModel.ISupportInitialize)(this.CowPriceChart)).BeginInit(); this.SuspendLayout(); // // CowPriceChart // this.CowPriceChart.BackColor = System.Drawing.Color.WhiteSmoke; chartArea1.AlignmentOrientation = ((System.Windows.Forms.DataVisualization.Charting.AreaAlignmentOrientations)((System.Windows.Forms.DataVisualization.Charting.AreaAlignmentOrientations.Vertical | System.Windows.Forms.DataVisualization.Charting.AreaAlignmentOrientations.Horizontal))); chartArea1.AxisX.IsMarksNextToAxis = false; chartArea1.AxisX.LineColor = System.Drawing.Color.DarkBlue; chartArea1.AxisX.ScaleView.MinSizeType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Days; chartArea1.AxisX.ScaleView.SmallScrollMinSizeType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Milliseconds; chartArea1.AxisX.Title = "เดือน"; chartArea1.AxisX.TitleFont = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); chartArea1.AxisY.Interval = 1000D; chartArea1.AxisY.ScaleBreakStyle.BreakLineStyle = System.Windows.Forms.DataVisualization.Charting.BreakLineStyle.Straight; chartArea1.AxisY.ScaleBreakStyle.Enabled = true; chartArea1.AxisY.ScaleBreakStyle.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.DashDotDot; chartArea1.AxisY.ScaleBreakStyle.LineWidth = 2; chartArea1.AxisY.ScaleView.MinSizeType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Days; chartArea1.AxisY.Title = "ราคา (บาท)"; chartArea1.AxisY.TitleFont = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); chartArea1.BackColor = System.Drawing.Color.LightSteelBlue; chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom; chartArea1.BorderColor = System.Drawing.Color.Blue; chartArea1.CursorY.SelectionColor = System.Drawing.Color.DarkRed; chartArea1.Name = "ChartArea1"; this.CowPriceChart.ChartAreas.Add(chartArea1); this.CowPriceChart.Dock = System.Windows.Forms.DockStyle.Fill; legend1.Name = "Legend1"; this.CowPriceChart.Legends.Add(legend1); this.CowPriceChart.Location = new System.Drawing.Point(0, 0); this.CowPriceChart.Name = "CowPriceChart"; this.CowPriceChart.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Bright; series1.BorderWidth = 2; series1.ChartArea = "ChartArea1"; series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; series1.Color = System.Drawing.Color.Red; series1.EmptyPointStyle.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.DashDot; series1.EmptyPointStyle.BorderWidth = 2; series1.EmptyPointStyle.Color = System.Drawing.Color.Red; series1.LabelBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); series1.LabelBorderColor = System.Drawing.Color.Red; series1.LabelForeColor = System.Drawing.Color.Red; series1.Legend = "Legend1"; series1.MarkerSize = 10; series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Square; series1.Name = "ข้อมูล 1"; series1.Points.Add(dataPoint1); series1.Points.Add(dataPoint2); series1.Points.Add(dataPoint3); series1.Points.Add(dataPoint4); series1.Points.Add(dataPoint5); series1.Points.Add(dataPoint6); series1.Points.Add(dataPoint7); series1.Points.Add(dataPoint8); series1.Points.Add(dataPoint9); series1.Points.Add(dataPoint10); series1.Points.Add(dataPoint11); series1.Points.Add(dataPoint12); series2.BorderWidth = 2; series2.ChartArea = "ChartArea1"; series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; series2.Color = System.Drawing.Color.Yellow; series2.EmptyPointStyle.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.DashDot; series2.EmptyPointStyle.BorderWidth = 2; series2.EmptyPointStyle.Color = System.Drawing.Color.Yellow; series2.LabelBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); series2.LabelBorderColor = System.Drawing.Color.Olive; series2.LabelForeColor = System.Drawing.Color.Olive; series2.Legend = "Legend1"; series2.MarkerSize = 10; series2.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Square; series2.Name = "ข้อมูล 2"; series2.Points.Add(dataPoint13); series2.Points.Add(dataPoint14); series2.Points.Add(dataPoint15); series2.Points.Add(dataPoint16); series2.Points.Add(dataPoint17); series2.Points.Add(dataPoint18); series2.Points.Add(dataPoint19); series2.Points.Add(dataPoint20); series2.Points.Add(dataPoint21); series2.Points.Add(dataPoint22); series2.Points.Add(dataPoint23); series2.Points.Add(dataPoint24); series3.BorderWidth = 2; series3.ChartArea = "ChartArea1"; series3.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; series3.Color = System.Drawing.Color.Lime; series3.EmptyPointStyle.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.DashDot; series3.EmptyPointStyle.BorderWidth = 2; series3.EmptyPointStyle.Color = System.Drawing.Color.Lime; series3.LabelBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); series3.LabelBorderColor = System.Drawing.Color.Green; series3.LabelForeColor = System.Drawing.Color.Green; series3.Legend = "Legend1"; series3.MarkerSize = 10; series3.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Triangle; series3.Name = "ข้อมูล 3"; series3.Points.Add(dataPoint25); series3.Points.Add(dataPoint26); series3.Points.Add(dataPoint27); series3.Points.Add(dataPoint28); series3.Points.Add(dataPoint29); series3.Points.Add(dataPoint30); series3.Points.Add(dataPoint31); series3.Points.Add(dataPoint32); series3.Points.Add(dataPoint33); series3.Points.Add(dataPoint34); series3.Points.Add(dataPoint35); series3.Points.Add(dataPoint36); series4.BorderWidth = 2; series4.ChartArea = "ChartArea1"; series4.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; series4.Color = System.Drawing.Color.Blue; series4.EmptyPointStyle.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.DashDot; series4.EmptyPointStyle.BorderWidth = 2; series4.EmptyPointStyle.Color = System.Drawing.Color.Blue; series4.LabelBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); series4.LabelBorderColor = System.Drawing.Color.Navy; series4.LabelForeColor = System.Drawing.Color.Navy; series4.Legend = "Legend1"; series4.MarkerSize = 10; series4.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Diamond; series4.Name = "ข้อมูล 4"; series4.Points.Add(dataPoint37); series4.Points.Add(dataPoint38); series4.Points.Add(dataPoint39); series4.Points.Add(dataPoint40); series4.Points.Add(dataPoint41); series4.Points.Add(dataPoint42); series4.Points.Add(dataPoint43); series4.Points.Add(dataPoint44); series4.Points.Add(dataPoint45); series4.Points.Add(dataPoint46); series4.Points.Add(dataPoint47); series4.Points.Add(dataPoint48); this.CowPriceChart.Series.Add(series1); this.CowPriceChart.Series.Add(series2); this.CowPriceChart.Series.Add(series3); this.CowPriceChart.Series.Add(series4); this.CowPriceChart.Size = new System.Drawing.Size(784, 561); this.CowPriceChart.TabIndex = 2; this.CowPriceChart.Text = "CowPriceChart"; // // CowPriceChartForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(784, 561); this.Controls.Add(this.CowPriceChart); this.MinimumSize = new System.Drawing.Size(800, 600); this.Name = "CowPriceChartForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "กราฟแสดงราคาชื้อ-ขายโค"; this.Load += new System.EventHandler(this.CowPriceChartForm_Load); ((System.ComponentModel.ISupportInitialize)(this.CowPriceChart)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataVisualization.Charting.Chart CowPriceChart; } }
c#
17
0.708081
297
76.297619
252
starcoderdata
NS_IMETHODIMP nsStorageStream::GetOutputStream(PRInt32 aStartingOffset, nsIOutputStream * *aOutputStream) { NS_ENSURE_ARG(aOutputStream); if (mWriteInProgress) return NS_ERROR_NOT_AVAILABLE; nsresult rv = Seek(aStartingOffset); if (NS_FAILED(rv)) return rv; // Enlarge the last segment in the buffer so that it is the same size as // all the other segments in the buffer. (It may have been realloc'ed // smaller in the Close() method.) if (mLastSegmentNum >= 0) mSegmentedBuffer->ReallocLastSegment(mSegmentSize); // Need to re-Seek, since realloc might have changed segment base pointer rv = Seek(aStartingOffset); if (NS_FAILED(rv)) return rv; NS_ADDREF(this); *aOutputStream = NS_STATIC_CAST(nsIOutputStream*, this); mWriteInProgress = PR_TRUE; return NS_OK; }
c++
9
0.670843
77
32.807692
26
inline
def get_emails_stat_by_campaigns(self, emails): """ Get campaigns statistic for list of emails @param emails: list of emails ['test_1@test_1.com', ..., 'test_n@test_n.com'] @return: dictionary with response message """ logger.info("Function call: get_emails_stat_by_campaigns") if not emails: self.__handle_error("Empty emails") try: emails = json.dumps(emails) except: logger.debug("Emails: {}".format(emails)) return self.__handle_error("Emails list can't be converted by JSON library") return self.__handle_result(self.__send_request('emails/campaigns', 'POST', {'emails': emails}))
python
12
0.603399
104
46.133333
15
inline
const express = require("express"); const router = express.Router(); const mongoose = require("mongoose"); const bcrypt = require("bcryptjs"); require("../models/Job"); const Job = mongoose.model("Jobs"); const { ensureAuthentication } = require("../helpers/Auth"); // Get Cookie Session router.get("/", (req, res) => { res.send(req.session); console.log(req.session); }); // Get ALl Jobs router.get("/:id", ensureAuthentication, (req, res) => { Job.find({ stylist: req.params.id }) .sort({ date: -1 }) // 1 is acsending .then(jobs => { var jobsJson = jobs; res.json(jobsJson); console.log(jobs); }); }); // Edit Job Status router.put("/update/:id", ensureAuthentication, (req, res) => { if (!req.body.status) { res.send("Failed status update."); } else { Job.findOne({ _id: req.params.id }).then(job => { if (!job) { res.send("Did not find job posting."); console.log("Did not find the job posting."); } else { job.status = req.body.status; // Update appoitment date job.save(); res.json(job); console.log("Edited Job Posting"); } }); } }); // Update Job Form router.put("/update/:id", ensureAuthentication, (req, res) => { Job.findOne({ _id: req.params.id }).then(job => { job.message = req.body.message; // Update appoitment date job.save(); res.json(job); console.log("Edited Job Posting"); }); }); // Delete Form router.delete("/delete/:id", ensureAuthentication, (req, res) => { Job.deleteOne({ _id: req.params.id }).then(() => { res.send("Deleted"); console.log("Deleted Post"); }); }); // Post Job Form router.post("/postJob/:id", ensureAuthentication, (req, res) => { let errors = []; if (!req.body.stylist) { errors.push({ text: "Please add a title" }); } if (!req.body.appointment) { errors.push({ text: "Please add a appointment" }); } if (errors.length > 0) { console.log(`Fill in the following fields ${errors}`); } else { const newJob = { name: req.body.name, stylist: req.body.stylist, user: req.params.id, message: req.body.message, appointment: req.body.appointment, status: false }; new Job(newJob).save().then(job => { res.send(job); console.log("Completed Job"); }); } }); module.exports = router;
javascript
14
0.585656
66
23.158416
101
starcoderdata
func TestSlice_HasDefault(t *testing.T) { tests := []struct { input interface{} def []interface{} expect []interface{} }{ // supported value, def is not used, def != expect {[]int{1, 2, 3}, []interface{}{"a", "b"}, []interface{}{1, 2, 3}}, {testing.T{}, []interface{}{1, 2, 3}, nil}, // unsupported value, def == expect {int(123), []interface{}{"hello"}, []interface{}{"hello"}}, {uint16(123), nil, nil}, {func() {}, []interface{}{}, []interface{}{}}, } for i, tt := range tests { msg := fmt.Sprintf("i = %d, input[%+v], def[%+v], expect[%+v]", i, tt.input, tt.def, tt.expect) v := cvt.Slice(tt.input, tt.def) assertEqual(t, tt.expect, v, "[NonE] "+msg) } }
go
14
0.553957
97
29.26087
23
inline
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package com.netflix.conductor.tests.utils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskExecLog; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.dao.IndexDAO; /** * @author Viren * */ public class MockIndexDAO implements IndexDAO { @Override public void setup() { } @Override public void indexWorkflow(Workflow workflow) { } @Override public CompletableFuture asyncIndexWorkflow(Workflow workflow) { return null; } @Override public SearchResult searchWorkflows(String query, String freeText, int start, int count, List sort) { return new SearchResult<>(0, new ArrayList<>()); } @Override public SearchResult searchTasks(String query, String freeText, int start, int count, List sort) { return new SearchResult<>(0, new ArrayList<>()); } @Override public void removeWorkflow(String workflowId) { } @Override public CompletableFuture asyncRemoveWorkflow(String workflowId) { return null; } @Override public void updateWorkflow(String workflowInstanceId, String[] key, Object[] value) { } @Override public CompletableFuture asyncUpdateWorkflow(String workflowInstanceId, String[] keys, Object[] values) { return null; } @Override public void indexTask(Task task) { } @Override public CompletableFuture asyncIndexTask(Task task) { return null; } @Override public void addTaskExecutionLogs(List logs) { } @Override public CompletableFuture asyncAddTaskExecutionLogs(List logs) { return null; } @Override public void addEventExecution(EventExecution eventExecution) { } @Override public List getEventExecutions(String event) { return null; } @Override public CompletableFuture asyncAddEventExecution(EventExecution eventExecution) { return null; } @Override public void addMessage(String queue, Message msg) { } @Override public CompletableFuture asyncAddMessage(String queue, Message message) { return null; } @Override public List getMessages(String queue) { return null; } @Override public String get(String workflowInstanceId, String key) { return null; } @Override public List getTaskExecutionLogs(String taskId) { return null; } @Override public List searchArchivableWorkflows(String indexName, long archiveTtlDays) { return null; } @Override public List searchRecentRunningWorkflows(int lastModifiedHoursAgoFrom, int lastModifiedHoursAgoTo) { return null; } }
java
11
0.756696
118
22.490066
151
starcoderdata
private void normalizeInstance(Instance inst, int offset) throws Exception { if (m_avgDocLength <= 0) { throw new Exception("Average document length is not set!"); } double docLength = 0; // compute length of document vector for (int i = 0; i < inst.numValues(); i++) { if (inst.index(i) >= offset && inst.index(i) != m_outputFormat.classIndex()) { docLength += inst.valueSparse(i) * inst.valueSparse(i); } } docLength = Math.sqrt(docLength); // normalized document vector for (int i = 0; i < inst.numValues(); i++) { if (inst.index(i) >= offset && inst.index(i) != m_outputFormat.classIndex()) { double val = inst.valueSparse(i) * m_avgDocLength / docLength; inst.setValueSparse(i, val); if (val == 0) { System.err.println("setting value " + inst.index(i) + " to zero."); i--; } } } }
java
16
0.566239
77
31.310345
29
inline
<table class="table table-striped table-bordered zero-configuration"> Image at <?php foreach ($getusers as $users) { ?> <tr id="dataid<?php echo e($users->id); ?>"> echo e($users->id); ?> src='<?php echo asset("public/images/profile/".$users->profile_image); ?>' style="width: 100px;"> echo e($users->name); ?> echo e($users->email); ?> echo e($users->mobile); ?> echo e($users->created_at); ?> <?php if($users->is_available == '1'): ?> <a class="badge badge-info px-2" onclick="StatusUpdate('<?php echo e($users->id); ?>','2')" style="color: #fff;">Block <?php else: ?> <a class="badge badge-primary px-2" onclick="StatusUpdate('<?php echo e($users->id); ?>','1')" style="color: #fff;">Unblock <?php endif; ?> <?php } ?> /**PATH D:\new-xampp\htdocs\app\resources\views/theme/userstable.blade.php ENDPATH**/ ?>
php
12
0.480418
147
40.432432
37
starcoderdata
package com.microsoft.azure.mobile.distribute; import android.annotation.SuppressLint; import android.content.ContentResolver; import android.content.Context; import android.os.Build; import android.provider.Settings; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.util.Arrays; import static com.microsoft.azure.mobile.distribute.InstallerUtils.INSTALL_NON_MARKET_APPS_ENABLED; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; @SuppressLint("InlinedApi") @SuppressWarnings("deprecation") @RunWith(PowerMockRunner.class) @PrepareForTest({Build.class, Settings.Global.class, Settings.Secure.class}) public class UnknownSourcesDetectionTest { private static void mockApiLevel(int apiLevel) { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", apiLevel); } @Before public void setUp() { mockStatic(Settings.Global.class); mockStatic(Settings.Secure.class); } @Test public void unknownSourcesEnabledViaSystemSecure() { when(Settings.Secure.getString(any(ContentResolver.class), eq(Settings.Secure.INSTALL_NON_MARKET_APPS))).thenReturn(INSTALL_NON_MARKET_APPS_ENABLED); when(Settings.Global.getString(any(ContentResolver.class), eq(Settings.Global.INSTALL_NON_MARKET_APPS))).thenReturn(null); for (int apiLevel = Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; apiLevel < Build.VERSION_CODES.JELLY_BEAN_MR1; apiLevel++) { mockApiLevel(apiLevel); assertTrue(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } for (int apiLevel = Build.VERSION_CODES.JELLY_BEAN_MR1; apiLevel < Build.VERSION_CODES.LOLLIPOP; apiLevel++) { mockApiLevel(apiLevel); assertFalse(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } for (int apiLevel = Build.VERSION_CODES.LOLLIPOP; apiLevel <= Build.VERSION_CODES.N_MR1; apiLevel++) { mockApiLevel(apiLevel); assertTrue(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } } @Test public void unknownSourcesEnabledViaSystemGlobal() { when(Settings.Global.getString(any(ContentResolver.class), eq(Settings.Global.INSTALL_NON_MARKET_APPS))).thenReturn(INSTALL_NON_MARKET_APPS_ENABLED); when(Settings.Secure.getString(any(ContentResolver.class), eq(Settings.Secure.INSTALL_NON_MARKET_APPS))).thenReturn(null); for (int apiLevel = Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; apiLevel < Build.VERSION_CODES.JELLY_BEAN_MR1; apiLevel++) { mockApiLevel(apiLevel); assertFalse(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } for (int apiLevel = Build.VERSION_CODES.JELLY_BEAN_MR1; apiLevel < Build.VERSION_CODES.LOLLIPOP; apiLevel++) { mockApiLevel(apiLevel); assertTrue(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } for (int apiLevel = Build.VERSION_CODES.LOLLIPOP; apiLevel <= Build.VERSION_CODES.N_MR1; apiLevel++) { mockApiLevel(apiLevel); assertFalse(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } } @Test public void disabledAndInvalidValues() { for (String value : Arrays.asList(null, "", "0", "on", "true", "TRUE")) { when(Settings.Global.getString(any(ContentResolver.class), eq(Settings.Global.INSTALL_NON_MARKET_APPS))).thenReturn(value); when(Settings.Secure.getString(any(ContentResolver.class), eq(Settings.Secure.INSTALL_NON_MARKET_APPS))).thenReturn(value); for (int apiLevel = Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; apiLevel <= Build.VERSION_CODES.N_MR1; apiLevel++) { mockApiLevel(apiLevel); assertFalse(InstallerUtils.isUnknownSourcesEnabled(mock(Context.class))); } } } }
java
17
0.720435
157
47.011111
90
starcoderdata
package cn.cerc.jdb.other; import java.util.HashMap; import java.util.Map; import java.util.Set; import cn.cerc.jdb.core.DataSet; import cn.cerc.jdb.core.Record; public class CountRecord { private DataSet dataSet; private Map<String, Integer> groups = new HashMap<>(); public CountRecord(DataSet dataSet) { this.dataSet = dataSet; } public CountRecord run(CountRecordInterface count) { for (Record rs : dataSet) { String group = count.getGroup(rs); Integer value = groups.get(group); if (value == null) groups.put(group, 1); else groups.put(group, value + 1); } return this; } public int getCount(String group) { Integer value = groups.get(group); return value == null ? 0 : value; } public Set getGroups() { return groups.keySet(); } }
java
12
0.592672
58
23.421053
38
starcoderdata
private bool TryProcessFirstNameNodeForThisItemAccess(FirstNameNode node, NameLookupInfo lookupInfo, out DType nodeType, out FirstNameInfo info) { if (_nameResolver.CurrentEntity.IsControl) { // Check to see if we only want to include ThisItem in specific // properties of this Control if (_nameResolver.CurrentEntity.EntityScope.TryGetEntity(_nameResolver.CurrentEntity.EntityName, out IExternalControl nodeAssociatedControl) && nodeAssociatedControl.Template.IncludesThisItemInSpecificProperty) { IExternalControlProperty nodeAssociatedProperty; if (nodeAssociatedControl.Template.TryGetProperty(_nameResolver.CurrentProperty, out nodeAssociatedProperty) && !nodeAssociatedProperty.ShouldIncludeThisItemInFormula) { nodeType = null; info = null; return false; } } } // Check to see if ThisItem is used in a DottedNameNode and if there is a data control // accessible from this rule. DName dataControlName = default; if (node.Parent is DottedNameNode && _nameResolver.LookupDataControl(node.Ident.Name, out NameLookupInfo dataControlLookupInfo, out dataControlName)) { // Get the property name being accessed by the parent dotted name. DName rightName = ((DottedNameNode)node.Parent).Right.Name; Contracts.AssertValid(rightName); Contracts.Assert(dataControlLookupInfo.Type.IsControl); // Check to see if the dotted name is accessing a property of the data control. if (((IExternalControlType)dataControlLookupInfo.Type).ControlTemplate.HasOutput(rightName)) { // Set the result type to the data control type. nodeType = dataControlLookupInfo.Type; info = FirstNameInfo.Create(node, lookupInfo, dataControlName, true); return true; } } nodeType = lookupInfo.Type; info = FirstNameInfo.Create(node, lookupInfo, dataControlName, false); return true; }
c#
15
0.566798
191
56.522727
44
inline
void global_setup_counters(const char *events) { int ret = perf_setup_list_events(events, &globFds, (int *)&numEvents); if (ret || !numEvents) errx(1, "could not initialize events: %s", pfm_strerror(ret)); for (uint32_t i = 0; i < numEvents; i++) { globFds[i].hw.disabled = 0; globFds[i].hw.enable_on_exec = 1; globFds[i].hw.wakeup_events = !!i; // 0 for i=0; 1 otherwise globFds[i].hw.sample_type = PERF_SAMPLE_READ; globFds[i].hw.sample_period = (i == 0) ? phaseLen : (1L << 62); // pinned should only be specified for group leader globFds[i].hw.pinned = (i == 0) ? 1 : 0; } }
c++
11
0.615509
72
40.333333
15
inline
/* Memory handling */ #include #define CHECK_MEM(var, what) do { \ if (!var) { \ fprintf(stderr, "%s:%d: %s : Out of memory\n", \ __func__, __LINE__, what); \ exit(1); \ } \ } while (0) #define ALLOC(var, num, what) do { \ var = calloc(num, sizeof(*(var))); \ CHECK_MEM(var, what); \ } while (0) #define REALLOC(var, num, what) do { \ var = realloc(var, (num)*sizeof(*var)); \ CHECK_MEM(var, what); \ } while (0)
c
5
0.5625
50
20.090909
22
starcoderdata
using System; using System.Linq.Expressions; using System.Reflection; using System.Security.Claims; using System.Threading.Tasks; using FakeItEasy; using FluentAssertions; using Microsoft.Owin; using Microsoft.Owin.Security; using Xunit; namespace Dalion.HttpMessageSigning.Verification.Owin { public class SignedHttpRequestAuthenticationHandlerTests { private readonly SignedHttpRequestAuthenticationOptions _options; private readonly OwinRequest _request; private readonly OwinResponse _response; private readonly SignedHttpRequestAuthenticationHandler _sut; public SignedHttpRequestAuthenticationHandlerTests() { _sut = new SignedHttpRequestAuthenticationHandler(); _options = new SignedHttpRequestAuthenticationOptions { Realm = "UnitTests", Scheme = "TestScheme", RequestSignatureVerifier = A.Fake }; _request = new OwinRequest { Host = new HostString("unittest.com:9000") }; _response = new OwinResponse(); var owinContext = A.Fake A.CallTo(() => owinContext.Request).Returns(_request); A.CallTo(() => owinContext.Response).Returns(_response); var init = _sut.GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); init.Invoke(_sut, new object[] {_options, owinContext}); } public class AuthenticateCoreAsync : SignedHttpRequestAuthenticationHandlerTests { private readonly Func _method; public AuthenticateCoreAsync() { var method = _sut.GetType().GetMethod(nameof(AuthenticateCoreAsync), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _method = () => (Task method.Invoke(_sut, Array.Empty } [Fact] public async Task WhenRequestDoesNotContainAuthorizationHeader_ReturnsNull() { _request.Headers.Remove("Authorization"); var actual = await _method(); actual.Should().BeNull(); } [Fact] public async Task WhenRequestDoesNotContainValidAuthorizationHeader_ReturnsNull() { _request.Headers["Authorization"] = "{nonsense}"; var actual = await _method(); actual.Should().BeNull(); } [Fact] public async Task WhenRequestDoesNotContainAuthorizationHeaderOfExpectedScheme_ReturnsNull() { _request.Headers["Authorization"] = "Basic abc123"; var actual = await _method(); actual.Should().BeNull(); } [Fact] public async Task WhenSignatureVerificationSucceeds_ReturnsAuthenticationTicket() { _request.Headers["Authorization"] = "TestScheme abc123"; var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] {new Claim("name", "john.doe")})); var successResult = new RequestSignatureVerificationResultSuccess( new Client( "c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), RequestTargetEscaping.RFC3986), new HttpRequestForVerification(), principal); A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature( A A .Returns(successResult); var actual = await _method(); actual.Should().BeEquivalentTo(new AuthenticationTicket(principal.Identity as ClaimsIdentity, new AuthenticationProperties())); } [Fact] public async Task WhenSignatureVerificationSucceeds_InvokesConfiguredCallback() { _request.Headers["Authorization"] = "TestScheme abc123"; var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] {new Claim("name", "john.doe")})); var successResult = new RequestSignatureVerificationResultSuccess( new Client( "c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), RequestTargetEscaping.RFC3986), new HttpRequestForVerification(), principal); A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature( A A .Returns(successResult); RequestSignatureVerificationResult resultFromCallback = null; _options.OnIdentityVerified = (request, success) => { resultFromCallback = success; return Task.CompletedTask; }; await _method(); resultFromCallback.Should().Be(successResult); } [Fact] public async Task WhenSignatureVerificationFails_ReturnsNull() { _request.Headers["Authorization"] = "TestScheme abc123"; var failureResult = new RequestSignatureVerificationResultFailure( new Client( "c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), RequestTargetEscaping.RFC3986), new HttpRequestForVerification(), SignatureVerificationFailure.HeaderMissing("A header is missing.", null)); A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature( A A .Returns(failureResult); var actual = await _method(); actual.Should().BeNull(); } [Fact] public async Task WhenSignatureVerificationFails_InvokesConfiguredCallback() { _request.Headers["Authorization"] = "TestScheme abc123"; var failureResult = new RequestSignatureVerificationResultFailure( new Client( "c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), RequestTargetEscaping.RFC3986), new HttpRequestForVerification(), SignatureVerificationFailure.HeaderMissing("A header is missing.", null)); A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature( A A .Returns(failureResult); RequestSignatureVerificationResult resultFromCallback = null; _options.OnIdentityVerificationFailed = (request, failure) => { resultFromCallback = failure; return Task.CompletedTask; }; await _method(); resultFromCallback.Should().Be(failureResult); } internal Expression<Func<IOwinRequest, bool>> ConvertedRequest => r => r.Host == new HostString("unittest.com:9000"); } public class ApplyResponseChallengeAsync : SignedHttpRequestAuthenticationHandlerTests { private readonly Func _method; public ApplyResponseChallengeAsync() { var method = _sut.GetType().GetMethod(nameof(ApplyResponseChallengeAsync), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _method = () => (Task) method.Invoke(_sut, Array.Empty } [Fact] public async Task WhenResponseIsNot401_DoesNotChangeWWWAuthenticateHeader() { _response.StatusCode = 200; await _method(); _response.Headers.Should().BeEmpty(); } [Fact] public async Task WhenResponseIs401_SetsWWWAuthenticateHeader() { _response.StatusCode = 401; await _method(); _response.Headers.Should().ContainKey("WWW-Authenticate"); _response.Headers["WWW-Authenticate"].Should().BeEquivalentTo("TestScheme realm=\"UnitTests\""); } [Fact] public async Task WhenResponseIs401_AndAHeaderIsAlreadyPresent_AppendsWWWAuthenticateHeader() { _response.StatusCode = 401; _response.Headers.Add("WWW-Authenticate", new[] {"Bearer"}); await _method(); _response.Headers.Should().ContainKey("WWW-Authenticate"); _response.Headers["WWW-Authenticate"].Should().BeEquivalentTo("Bearer, TestScheme realm=\"UnitTests\""); } } } }
c#
25
0.56938
161
43.608108
222
starcoderdata
bool FileLoaderThread::initialize(DbPartition* partition, DbFile* fileAccess, std::deque<DbPartitionInfo*>* inFileLoaderQue, pthread_mutex_t* fileLoaderQueueMutex, pthread_cond_t* condLoad, pthread_mutex_t* condLoadMutex, bool* loadFile, uint32_t totalPartitions, uint32_t partitionInterval, const char *dbUserName, const char *dbPasswd, const char *dbName) { mPartition = partition; mFileAccess = fileAccess; mFileLoaderQue = inFileLoaderQue; mFileLoaderQueueMutex = fileLoaderQueueMutex; mCondLoad = condLoad; mCondLoadMutex = condLoadMutex; mLoadFile = loadFile; mTotalPartitions = totalPartitions; mPartitionInterval = partitionInterval; // connect to mysql if (mMysqlClient.connect("localhost",dbUserName, dbPasswd, dbName)) { LOG_ERROR(mLogId,"initialize: Failure trying to connect to mysql."); return false; } // becomeThread does pthread create and calls run() if (becomeThread() != 0) { // log error LOG_ERROR(mLogId,"initialize: Failure from becomeThread()."); return false; } return true; }
c++
10
0.633094
161
35.969697
33
inline
package com.mrmq.poker.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.ByteString; import com.mrmq.poker.common.proto.Heartbeat.HeartbeatMessage; import com.mrmq.poker.common.proto.PokerServiceProto.EndGameEvent; import com.mrmq.poker.common.proto.Rpc.RpcMessage; import com.mrmq.poker.db.entity.PkUser; import com.mrmq.poker.manager.PokerMananger; import com.mrmq.poker.service.Session; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; public class PokerSession implements Session { private static Logger log = LoggerFactory.getLogger(PokerSession.class); private String id; private boolean authenticated; private Channel channel; private PkUser user; public PokerSession(String id, Channel channel) { this.id = id; this.channel = channel; } public String id() { return id; } public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } public boolean isAuthenticated() { return authenticated; } @Override public boolean isAlive() { return channel != null && channel.isActive(); } @Override public PkUser getUser() { return user; } @Override public void setUser(PkUser player) { this.user = player; } @Override public boolean send(RpcMessage msg) { if(channel != null && channel.isActive()) { if(!HeartbeatMessage.getDescriptor().getName().equals(msg.getPayloadClass())) log.info("Response to player: {}, msg:\n{}", (user != null ? user.getLogin() : toString()), msg); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(); frame.content().writeBytes(msg.toByteArray()); ChannelFuture future = channel.writeAndFlush(frame); return future.isDone(); } else { log.warn("Channel not connected. Can not response to player: {}, msg:\n{}", user, msg); return false; } } @Override public boolean send(String payloadClass, ByteString payloadData) { //Create rpc RpcMessage.Builder rpc = PokerMananger.createRpcMessage(); rpc.setPayloadClass(payloadClass); rpc.setPayloadData(payloadData); return send(rpc.build()); } @Override public boolean release() { authenticated = false; if(user != null) PokerMananger.removeSessionByUser(user.getLogin()); return false; } @Override public String toString() { return "PokerSession [id=" + id + ", authenticated=" + authenticated + "]"; } }
java
15
0.727564
101
24.742268
97
starcoderdata
import operator from typing import Any, Dict, List, Set, Union, Tuple from sqlalchemy import and_, or_, literal_column, func from sqlalchemy.orm.session import Session from sqlalchemy.sql.elements import BinaryExpression from sqlalchemy.sql.selectable import Alias from vardb.datamodel import annotation OPERATORS = { "==": operator.eq, ">=": operator.ge, "<=": operator.le, ">": operator.gt, "<": operator.lt, } HGMD_TAGS = set([None, "FP", "DM", "DFP", "R", "DP", "DM?"]) CLINVAR_CLINSIG_GROUPS = { "pathogenic": [ "pathogenic", "likely pathogenic", "pathologic", "suspected pathogenic", "likely pathogenic - adrenal bilateral pheochromocy", "likely pathogenic - adrenal pheochromocytoma", "probable-pathogenic", "probably pathogenic", "pathogenic variant for bardet-biedl syndrome", ], "uncertain": ["uncertain", "variant of unknown significance", "uncertain significance"], "benign": [ "benign", "suspected benign", "probable-non-pathogenic", "probably not pathogenic", "likely benign", ], } CLINVAR_NUM_STARS = { "no assertion criteria provided": 0, "no assertion provided": 0, "criteria provided, conflicting interpretations": 1, "criteria provided, single submitter": 1, "criteria provided, multiple submitters, no conflicts": 2, "reviewed by expert panel": 3, "practice guideline": 4, } # Ensure everything is lowercase CLINVAR_CLINSIG_GROUPS = { k.lower(): [x.lower() for x in v] for k, v in CLINVAR_CLINSIG_GROUPS.items() } class ExternalFilter(object): def __init__(self, session: Session, config: Dict[str, Any]) -> None: self.session = session self.config = config def _build_clinvar_filters( self, clinsig_counts: Alias, combinations: List[Tuple[str, str, Union[str, int]]] ) -> List[BinaryExpression]: """ Combinations is given as a list of lists, like [["benign", ">", 5], # More than 5 benign submissions ["pathogenic", "==", 0], # No pathogenic submissions ["benign", ">", "uncertain"]] # More benign than uncertain submissions """ def get_filter_count(v: Union[str, int]): if isinstance(v, str): assert v in ["benign", "pathogenic", "uncertain"] return getattr(clinsig_counts.c, v) else: assert isinstance(v, (int, float)) return v filters = [] for c in combinations: clinsig, op, count = c[0], OPERATORS[c[1]], get_filter_count(c[2]) filters.append(op(getattr(clinsig_counts.c, clinsig), count)) return filters def _filter_clinvar(self, allele_ids: List[int], clinvar_config: Dict[str, Any]) -> Set[int]: # Use this to evaluate the number of stars star_op, num_stars = clinvar_config.get("num_stars", (">=", 0)) star_op = OPERATORS[star_op] # Extract clinical_significance_status that matches the num_stars criteria # The clinical_significance_status to stars mapping is given in the config filter_signifiance_descr = [ k for k, v in list(CLINVAR_NUM_STARS.items()) if star_op(v, num_stars) ] combinations = clinvar_config.get("combinations", []) # Expand clinvar submissions, where clinical_significance_status satisfies clinvar_entries = ( self.session.query( annotation.Annotation.allele_id, literal_column( "jsonb_array_elements(annotations->'external'->'CLINVAR'->'items')" ).label("entry"), ) .filter( annotation.Annotation.allele_id.in_(allele_ids), annotation.Annotation.date_superceeded.is_(None), annotation.Annotation.annotations.op("->")("external") .op("->")("CLINVAR") .op("->>")("variant_description") .in_(filter_signifiance_descr), ) .subquery() ) # Extract clinical significance for all SCVs clinvar_clinsigs = ( self.session.query( clinvar_entries.c.allele_id, clinvar_entries.c.entry.op("->>")("clinical_significance_descr").label("clinsig"), ) .filter(clinvar_entries.c.entry.op("->>")("rcv").op("ILIKE")("SCV%")) .subquery() ) def count_matches(category): return func.count(clinvar_clinsigs.c.clinsig).filter( func.lower(clinvar_clinsigs.c.clinsig).in_(CLINVAR_CLINSIG_GROUPS[category]) ) # Count the number of Pathogenic/Likely pathogenic, Uncertain significance, and Benign/Likely benign # Note: This does not match any clinsig with e.g. Drug response or similar clinsig_counts = ( self.session.query( clinvar_clinsigs.c.allele_id, *[count_matches(category).label(category) for category in CLINVAR_CLINSIG_GROUPS] ) .group_by(clinvar_clinsigs.c.allele_id) .order_by(clinvar_clinsigs.c.allele_id) .subquery() ) filters = self._build_clinvar_filters(clinsig_counts, combinations) # Extract allele ids that matches the config rules filtered_allele_ids = self.session.query(clinsig_counts.c.allele_id).filter(and_(*filters)) inverse = clinvar_config.get("inverse", False) if inverse: return set(allele_ids) - set([a[0] for a in filtered_allele_ids]) else: return set([a[0] for a in filtered_allele_ids]) def _filter_hgmd(self, allele_ids: List[int], hgmd_config: Dict[str, Any]) -> Set[int]: hgmd_tags = hgmd_config["tags"] assert hgmd_tags, "No tags provided to hgmd filter, even though config is defined" assert ( not set(hgmd_tags) - HGMD_TAGS ), "Invalid tag(s) to filter on in {}. Available tags are {}.".format(hgmd_tags, HGMD_TAGS) # Need to separate check for specific tag and check for no HGMD data (tag is None) filters = [] if None in hgmd_tags: hgmd_tags.pop(hgmd_tags.index(None)) filters.append( annotation.Annotation.annotations.op("->")("external") .op("->")("HGMD") .op("->>")("tag") .is_(None) ) if hgmd_tags: filters.append( annotation.Annotation.annotations.op("->")("external") .op("->")("HGMD") .op("->>")("tag") .in_(hgmd_tags) ) filtered_allele_ids = self.session.query(annotation.Annotation.allele_id).filter( annotation.Annotation.date_superceeded.is_(None), annotation.Annotation.allele_id.in_(allele_ids), or_(*filters), ) inverse = hgmd_config.get("inverse", False) if inverse: return set(allele_ids) - set([a[0] for a in filtered_allele_ids]) else: return set([a[0] for a in filtered_allele_ids]) def filter_alleles( self, gp_allele_ids: Dict[Tuple[str, str], List[int]], filter_config: Dict[str, Any] ) -> Dict[Tuple[str, str], Set[int]]: """ Filter alleles on external annotations. Supported external databases are clinvar and hgmd. Filters only alleles which satisify *both* clinvar and hgmd configurations. If only one of clinvar or hgmd is specified, filters on this alone. filter_config is specified like { "clinvar": { "combinations": [ ["benign", ">", 5], # More than 5 benign submissions ["pathogenic", "==", 0], # No pathogenic submissions ["benign", ">", "uncertain"] # More benign than uncertain submissions ], "num_stars": [">=", 2] # Only include variants with 2 or more stars }, "hgmd": { "tags": [None], # Not in HGMD } } """ result: Dict[Tuple[str, str], Set[int]] = dict() for gp_key, allele_ids in gp_allele_ids.items(): if not allele_ids: result[gp_key] = set() continue clinvar_config = filter_config.get("clinvar") if clinvar_config: clinvar_filtered_allele_ids = self._filter_clinvar(allele_ids, clinvar_config) hgmd_config = filter_config.get("hgmd") if hgmd_config: hgmd_filtered_allele_ids = self._filter_hgmd(allele_ids, hgmd_config) # Union hgmd filtered and clinvar filtered if both have been run, otherwise return the result of the run one if clinvar_config and hgmd_config: result[gp_key] = clinvar_filtered_allele_ids & hgmd_filtered_allele_ids elif clinvar_config: result[gp_key] = clinvar_filtered_allele_ids elif hgmd_config: result[gp_key] = hgmd_filtered_allele_ids else: result[gp_key] = set() return result
python
25
0.570241
120
36.678715
249
starcoderdata
package org.xbib.elasticsearch.rest.action.river.execute; import org.elasticsearch.client.Client; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.action.support.RestBuilderListener; import org.xbib.elasticsearch.action.river.jdbc.execute.RiverExecuteAction; import org.xbib.elasticsearch.action.river.jdbc.execute.RiverExecuteRequest; import org.xbib.elasticsearch.action.river.jdbc.execute.RiverExecuteResponse; import static org.elasticsearch.rest.RestStatus.OK; /** * Run a river. The river can be executed once with such a call. Example: * * curl -XPOST 'localhost:9200/_river/my_jdbc_river/_execute' */ public class RestRiverExecuteAction extends BaseRestHandler { @Inject public RestRiverExecuteAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(RestRequest.Method.POST, "/_river/jdbc/{riverName}/_execute", this); } @Override public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { String riverName = request.param("riverName"); String riverType = "jdbc"; RiverExecuteRequest riverExecuteRequest = new RiverExecuteRequest() .setRiverName(riverName) .setRiverType(riverType); client.admin().cluster().execute(RiverExecuteAction.INSTANCE, riverExecuteRequest, new RestBuilderListener { @Override public RestResponse buildResponse(RiverExecuteResponse riverExecuteResponse, XContentBuilder builder) throws Exception { boolean isExecuted = false; for (int i = 0; i < riverExecuteResponse.isExecuted().length; i++) { isExecuted = isExecuted || riverExecuteResponse.isExecuted()[i]; } builder.field("executed", isExecuted); return new BytesRestResponse(OK, builder); } }); } }
java
20
0.734167
147
44.283019
53
starcoderdata
void FMM::MarchAlg( struct Vertex *temp_V, /* vertices coordinates 1..Vnum */ int temp_Vnum, double *srcval){ V = temp_V; /* Save the array of vertexes in the V array. */ Vnum = temp_Vnum; /* Save the number of vertexes in the array V. */ InitMarch(srcval, Vnum); /* CAllTUpdateNeighbours for every vertex when it becomes the smallest vertex in the heap. Exit the loop when there are no more sources which are not alive */ while (heap->N != 0){ CallTUpdateNeighbors(heap->a[1].v, 0); heap->remove_top(); } }
c++
11
0.619211
72
25.545455
22
inline
package org.folio.calendar.exception; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import lombok.Getter; import lombok.NonNull; import lombok.ToString; import org.folio.calendar.domain.dto.Error; import org.folio.calendar.domain.dto.ErrorCode; import org.folio.calendar.domain.dto.ErrorResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; /** * Abstract calendar exception, to be implemented by more concrete exceptions thrown from our application. * {@link org.folio.calendar.exception.NonspecificCalendarException NonspecificCalendarException} should be used for otherwise unknown errors (e.g. generic Exception or Spring-related exceptions). */ @ToString(callSuper = true) public abstract class AbstractCalendarException extends RuntimeException { /** Constant */ public static final HttpStatus DEFAULT_STATUS_CODE = HttpStatus.BAD_REQUEST; @Getter protected final ErrorCode errorCode; @Getter protected final HttpStatus statusCode; @Getter @NonNull protected final ExceptionParameters parameters; /** * Create an AbstractCalendarException with the given HTTP status code, error * code, message, and format. * * @param cause The exception which caused this (may be null) * @param parameters The parameters causing the exception * @param statusCode The Spring HTTP status code ({@link org.springframework.http.HttpStatus HttpStatus}) * @param errorCode An error code as described in the ErrorResponse API type * @param message A string for the error message */ protected AbstractCalendarException( Throwable cause, ExceptionParameters parameters, HttpStatus statusCode, ErrorCode errorCode, String message ) { super(message, cause); if (parameters == null) { parameters = new ExceptionParameters(); } this.parameters = parameters; this.errorCode = errorCode; this.statusCode = statusCode; } /** * Create a standardized error response for the rest API * * @return An ErrorResponse for API return */ protected ErrorResponse getErrorResponse() { ErrorResponse.ErrorResponseBuilder responseBuilder = ErrorResponse.builder(); responseBuilder = responseBuilder.timestamp(Instant.now()); responseBuilder = responseBuilder.status(this.getStatusCode().value()); // Can only have one exception at a time Error.ErrorBuilder errorBuilder = Error.builder(); errorBuilder = errorBuilder.code(this.getErrorCode()); errorBuilder = errorBuilder.message(this.getMessage()); for (StackTraceElement frame : this.getStackTrace()) { errorBuilder = errorBuilder.traceItem(frame.toString()); } if (this.getCause() != null) { errorBuilder = errorBuilder.traceItem("----------------- CAUSED BY -----------------"); errorBuilder = errorBuilder.traceItem(this.getCause().getMessage()); for (StackTraceElement frame : this.getCause().getStackTrace()) { errorBuilder = errorBuilder.traceItem(frame.toString()); } } Map<String, Object> errorParameters = new HashMap<>(); for (Entry<String, Object> parameter : this.getParameters().getMap().entrySet()) { errorParameters.put(parameter.getKey(), parameter.getValue()); } errorBuilder = errorBuilder.parameters(errorParameters); responseBuilder.error(errorBuilder.build()); return responseBuilder.build(); } /** * Get a ResponseEntity to be returned to the API * * @return {@link org.springframework.http.ResponseEntity} with {@link org.folio.calendar.domain.dto.ErrorResponse} body. */ public ResponseEntity getErrorResponseEntity() { return new ResponseEntity<>(this.getErrorResponse(), this.getStatusCode()); } }
java
15
0.730282
196
35.828571
105
starcoderdata
using Newtonsoft.Json; using System; namespace RedFolder.ActivityTracker.Models.Pluralsight { public class CompletedCourse: BaseCourse { [JsonProperty("contentId")] public string CourseId { get; set; } [JsonProperty("slug")] public string CourseName { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("authors")] public Author[] Authors { get; set; } [JsonProperty("level")] public string Level; [JsonProperty("timeCompleted")] public DateTime TimeCompleted { get; set; } public override string Id => CourseId; public override bool IsWithinRange(DateTime start, DateTime end) { return TimeCompleted >= start && TimeCompleted <= end; } } }
c#
11
0.611312
72
27.655172
29
starcoderdata
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | https://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'login'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; // Rotas referentes a empresa (Controle Administrador) $route['controle'] = "admin/controle"; $route['controle/cadempresa'] = "admin/controle/pagina_cadastro"; $route['editar_empresa'] = "admin/controle/editar_empresa"; $route['excluir_empresa'] = "admin/controle/excluir_empresa"; $route['empresa_edit'] = "admin/controle/empresa_editar"; $route['cadastrar_empresa'] = "admin/controle/cadastrar_empresa"; $route['alt_empresa'] = "admin/controle/altera_dadosempresa"; $route["verifica_empresa"] = "admin/controle/verifica_empresa"; //Rota de alteração de senha (Controller Usuario.php) $route["alterar_senha"] = "usuario/alterar_senha"; // Rotas referentes ao login $route['login_auth'] = "login/login"; $route['logout'] = "login/logout"; // Rotas referentes aos usuarios $route['cad_usuario'] = "usuario/cadastro_usuario"; $route['editar_usuario'] = "home/editar_usuario"; $route['edit_usuario'] = "usuario/editar_usuario"; $route['excluir_usuario'] = "usuario/excluir_usuario"; $route['verifica_usuario'] = "usuario/verifica_user"; $route['download_arquivo/(:num)'] = "usuario/download_arquivo/$1"; $route['download_file/(:num)'] = "usuario/download_file/$1"; // Rotas do referentes aos cargos $route['cad_cargo'] = "cargos/cadastrar_cargo"; $route['editar_cargo'] = "cargos/editar_cargo_pagina"; $route['edit_cargo'] = "cargos/editar_cargo"; $route['excluir_cargo'] = "cargos/excluir_cargo"; // Rotas referentes aos Horarios $route['cad_horario'] = "horarios/cadastrar_horario"; $route['editar_horario'] = "horarios/editar_horario_pagina"; $route['edit_horario'] = "horarios/editar_horario"; $route['excluir_horario'] = "horarios/excluir_horario"; // Rotas referentes aos Feriados $route['cad_feriado'] = "feriados/cadastrar_feriados"; $route['editar_feriado'] = "feriados/editar_feriados_pagina"; $route['edit_feriado'] = "feriados/editar_feriados"; $route['excluir_feriado'] = "feriados/excluir_feriados"; // Rotas referentes aos arquivos da pasta controller conf $route["grupodocumentos"] = "conf/grupos"; $route["grupodocumentos_cad"] = "conf/grupos/cadastro"; $route["cad_grupo"] = "conf/grupos/cadastrar_grupo"; $route["editar_grupo"] = "conf/grupos/editar_grupo_pagina"; $route["edit_grupos"] = "conf/grupos/editar_grupo"; $route["excluir_grupo"] = "conf/grupos/excluir_grupo"; $route["etapas"] = "conf/etapas"; $route["etapas_cad"] = "conf/etapas/cadastro"; $route["cad_etapa"] = "conf/etapas/cadastrar_etapas"; $route["editar_etapa"] = "conf/etapas/editar_etapas_pagina"; $route["edit_etapas"] = "conf/etapas/editar_etapas"; $route["excluir_etapa"] = "conf/etapas/excluir_etapas"; $route['documentos'] = "conf/documento"; $route["documentos_cad"] = "conf/documento/cadastro"; $route["cad_documento"] = "conf/documento/cadastrar_documentos"; $route["editar_documento"] = "conf/documento/editar_documentos_pagina"; $route["edit_documentos"] = "conf/documento/editar_documentos"; $route["excluir_documento"] = "conf/documento/excluir_documento"; $route["ausencia_ferias"] = "home/ausencia_ferias"; $route["ausencia_ferias_cad"] = "home/ausencia_ferias_cadastro"; $route["ausencia"] = "conf/ausencia"; $route["ausencia_cad"] = "conf/ausencia/cadastro"; $route["cad_ausencia"] = "conf/ausencia/cadastrar_ausencia"; $route["editar_ausencia"] = "conf/ausencia/editar_ausencia_pagina"; $route["edit_ausencia"] = "conf/ausencia/editar_ausencia"; $route["excluir_ausencia"] = "conf/ausencia/excluir_ausencia"; $route["ferias"] = "conf/ferias"; $route["ferias_cad"] = "conf/ferias/cadastro"; $route["cad_ferias"] = "conf/ferias/cadastrar_ferias"; $route["editar_ferias"] = "conf/ferias/editar_ferias_pagina"; $route["edit_ferias"] = "conf/ferias/editar_ferias"; $route["excluir_ferias"] = "conf/ferias/excluir_ferias"; $route["competencia"] = "conf/competencia"; $route["competencia_cad"] = "conf/competencia/cadastro"; $route["tipo_comp/(:any)"] = "conf/competencia/tipo_competencia/$1"; $route["cad_competencia"] = "conf/competencia/cadastrar"; $route["erros"] = "conf/erros"; $route["erros_cad"] = "conf/erros/pagina_cadastro"; $route["cad_erros"] = "conf/erros/cadastrar"; $route["editar_erro"] = "conf/erros/editar_erro_pagina"; $route["edit_erro"] = "conf/erros/editar_erro"; $route["excluir_erro"] = "conf/erros/excluir_erro"; $route["erro_documento"] = "conf/Erros/erro_documento"; $route["etapa_json/(:any)"] = "conf/Etapas/etapas_documento_json/$1"; $route["erro_documento_cad"] = "conf/Erros/erro_documento_cad"; $route["vizualizar_erros/(:any)"] = "conf/Erros/visualizar_erros_documento/$1"; //Rotas referentes a pasta documentos $route["novo_documento"] = "documentos/Documento"; $route["find_doc/(:num)"] = "documentos/Documento/busca_documentos/$1"; $route["find_steps/(:num)"] = "documentos/Documento/busca_etapas/$1"; $route["find_deadline/(:num)"] = "documentos/Documento/buscar_prazosDocumento/$1"; $route["cad_novo_doc"] = "documentos/Documento/cadastrar_novo_documento"; $route["verifica_protocolo"] = "documentos/Documento/verifica_protocolo"; $route["meusdocumentos"] = "documentos/Documento/meus_documentos"; $route["get_time"] = "documentos/Documento/get_time"; $route["grava_acao"] = "documentos/Documento/grava_acao"; $route["proxima_etapa/(:any)"] = "documentos/Transferencia/transfere_etapa/$1"; $route["meus_documentos/(:any)"] = "documentos/Documento/meus_documentos_msg/$1"; $route["finalizar_documento/(:any)"] = "documentos/Finalizar/finalizado/$1"; $route["etapa_aterior/(:any)"] = "documentos/Transferencia/retorna_etapa/$1"; $route["editar_documento/(:any)"] = "documentos/Documento/editar_documento/$1"; $route["edit_novo_doc"] = "documentos/Documento/editar_novo_documento"; $route["historico_documento/(:any)"] = "documentos/Documento/historico_documento/$1"; $route["historico/(:any)"] = "documentos/Documento/historico/$1"; //$route["suspender/(:any)"] = "documentos/Transferencia/suspender_documento/$1"; $route["suspender"] = "documentos/Transferencia/suspender_documento"; $route["cancelar_documento"] = "documentos/Documento/cancelar_documento"; $route["andamento"] = "documentos/Relatorios"; $route["erro"] = "documentos/Relatorios/documentos_com_erro"; $route["cancelados"] = "documentos/Relatorios/documentos_cancelados"; $route["suspenso"] = "documentos/Relatorios/documentos_suspensos"; $route["get_time_suspenso"] = "documentos/Documento/get_time_suspenso"; //$route["reverte_suspensao/(:any)"] = "documentos/Relatorios/reverte_suspensao/$1"; $route["reverte_suspensao"] = "documentos/Relatorios/reverte_suspensao"; $route["observacao_cad"] = "documentos/Documento/cadastrar_observacao"; $route["ver_observacao/(:any)"] = "documentos/Documento/ver_observacao/$1"; $route["pendentes"] = "documentos/Relatorios/documentos_pendentes"; $route["get_time_pendente"] = "documentos/Documento/get_time_pendente"; $route["transferencia"] = "documentos/Relatorios/tranferencia_documento"; $route["transfere_para"] = "documentos/Relatorios/transfere_para"; $route["nao_iniciados"] = "documentos/Relatorios/nao_iniciados"; //Rotas referentes a pasta relatorios $route["finalizados"] = "relatorios/Relatorios/finalizados"; $route["imprimir_finalizados/(:num)"] = "relatorios/imprimir/imprimir_finalizados/$1"; $route["tempo_medio"] = "relatorios/relatorios/tempo_medio"; $route["tempo_mensal"] = "relatorios/relatorios/tempo_mensal"; $route["tempo_cargos"] = "relatorios/relatorios/tempo_cargo"; $route["relatorio_tempo/(:num)"] = "relatorios/imprimir/imprimir_tempo_medio/$1"; $route["relatorio_tmensal/(:num)/(:any)"] = "relatorios/imprimir/imprimir_tempo_medio_mensal/$1/$2"; $route["relatorio_tcargo/(:num)"] = "relatorios/imprimir/imprimir_tempo_medio_cargo/$1"; $route["produtividade_individual"] = "relatorios/relatorios/produtividade_individual"; $route["produtividade_grupo"] = "relatorios/relatorios/produtividade_grupo"; $route["relatorio_produtividade/(:num)"] = "relatorios/imprimir/produtividade_relatorio/$1"; $route["prazos_documentos"] = "relatorios/relatorios/listar_prazos"; $route["em_atraso/(:num)"] = "relatorios/imprimir/imprimir_fora_prazo/$1"; $route["imprimir_historico/(:num)"] = "relatorios/imprimir/imprimir_historico/$1"; //Rotas referentes a impressão por filtros $route["imprimir_por_grupo/(:num)"] = "relatorios/imprimir/filtro_por_grupo/$1"; $route["imprimir_por_documento/(:num)"] = "relatorios/imprimir/filtro_por_documento/$1"; $route["relatorio_tempo_grupo/(:num)"] = "relatorios/imprimir/filtro_tempo_grupo/$1"; $route["relatorio_tempo_documento/(:num)"] = "relatorios/imprimir/filtro_tempo_documentos/$1";
php
7
0.630405
102
56.760976
205
starcoderdata
""" This saves figures showing the results of various clustering algorithms, including AutoGMM, agglomerative clustering, k-means, naive GM (using single or mutiple inits), on the double-cigar dataset. It outputs the two subplots of Figure 7 in the paper. """ #%% import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from joblib import Parallel, delayed import pandas as pd import seaborn as sns from sklearn.metrics import adjusted_rand_score from sklearn.cluster import KMeans, AgglomerativeClustering from sklearn.mixture import GaussianMixture import sys sys.path.append("/code") from autogmm import AutoGMMCluster sns.set_context("talk") #%% def AGM(X, y, n_clusters_range, n_init): agmm = AutoGMMCluster( max_components=n_clusters_range[-1], min_components=n_clusters_range[0], kmeans_n_init=n_init, init_params="kmeans", ) pred = agmm.fit_predict(X, y) return agmm.model_, agmm.ari_, pred def KM(X, y, n_clusters_range, n_init): ari_km = -1 for n_clus in np.unique(n_clusters_range): kmeans = KMeans(n_clusters=n_clus, n_init=n_init) pred_km = kmeans.fit_predict(X) ari_ = adjusted_rand_score(pred_km, y) if ari_ > ari_km: ari_km = ari_ best_model = kmeans return best_model, ari_km, best_model.predict(X) def Agg(X, y, n_clusters_range): af = ["euclidean", "manhattan", "cosine"] li = ["ward", "complete", "single", "average"] ari_ag = -1 for af_ in af: for li_ in li: if li_ == "ward" and af_ != "euclidean": continue else: for n_clus in np.unique(n_clusters_range): agg = AgglomerativeClustering( n_clusters=n_clus, affinity=af_, linkage=li_ ) pred_ag = agg.fit_predict(X) ari_ = adjusted_rand_score(pred_ag, y) if ari_ > ari_ag: ari_ag = ari_ best_model = agg best_pred = pred_ag return best_model, ari_ag, best_pred def naive_GMM(X, y, n_components_range, n_init, init_params="kmeans"): lowest_bic = np.infty cv_types = ["spherical", "tied", "diag", "full"] for cv_type in cv_types: for n_components in np.unique(n_components_range): gmm = GaussianMixture( n_components=n_components, covariance_type=cv_type, n_init=n_init, init_params=init_params, ) gmm.fit(X) bic_ = gmm.bic(X) if bic_ < lowest_bic: lowest_bic = bic_ best_gmm = gmm pred = best_gmm.predict(X) return best_gmm, adjusted_rand_score(pred, y), pred def exp(X, y, n_clusters_range, n_init=10): agm, ari_agm, pred_agm = AGM(X, y, n_clusters_range, n_init) gm, ari_gm, pred_gm = naive_GMM(X, y, n_clusters_range, 1) gm_m, ari_gm_multi, pred_gm_multi = naive_GMM(X, y, n_clusters_range, n_init) km, ari_km, pred_km = KM(X, y, n_clusters_range, n_init) ag, ari_ag, pred_ag = Agg(X, y, n_clusters_range) aris = [ari_agm, ari_gm, ari_gm_multi, ari_km, ari_ag] preds = [pred_agm, pred_gm, pred_gm_multi, pred_km, pred_ag] models = [agm, gm, gm_m, km, ag] return aris, preds, models #%% # plot predictions on single cigar dataset by various clustering algorithms np.random.seed(32) cov_1 = 1 cov_2 = 200 n = 100 mu_ = 3 mu1 = [-mu_, 0] mu2 = [mu_, 0] cov1 = np.array([[cov_1, 0], [0, cov_2]]) cov2 = np.array([[cov_1, 0], [0, cov_2]]) X1 = np.random.multivariate_normal(mu1, cov1, n) X2 = np.random.multivariate_normal(mu2, cov2, n) X = np.concatenate((X1, X2)) y = np.repeat([0, 1], int(len(X) / 2)) aris, preds, _ = exp(X, y, range(2, 6)) algs = ["AutoGMM", "Naive GM", "Naive GM (multi init)", "K-Means", "Agglomerative"] fig = plt.figure(figsize=(16, 4.5)) fig.subplots_adjust(top=0.8) c_list = ["red", "green", "blue", "orange", "purple", "yellow", "gray"] for i in range(len(algs)): ax = plt.subplot(1, 5, i + 1) max_c = np.max(preds[i]) plt.scatter( X[:, 0], X[:, 1], c=preds[i], s=10, cmap=colors.ListedColormap(c_list[: max_c + 1]), ) plt.title(algs[i]) plt.xticks(fontsize=18) plt.yticks(fontsize=18) if i == 2: plt.xlabel("First Dimension", fontsize=22) elif i == 0: plt.ylabel("Second Dimension", fontsize=22) if i != 0: ax.set(yticklabels=[]) plt.text( 0.97, 0.92, ("%.2f" % aris[i]).lstrip("0"), transform=plt.gca().transAxes, size=15, horizontalalignment="right", ) fig.suptitle("Synthetic Double-Cigar Dataset", y=0.93, fontsize=22, fontweight="bold") plt.savefig("/results/cigar_pred.png", bbox_inches="tight", dpi=300) #%% # make boxplot of ARIs for cigar datasets np.random.seed(1) rep = 100 cov_1 = 1 cov_2 = 200 n = 100 mu_ = 3 mu1 = [-mu_, 0] mu2 = [mu_, 0] def _run(): cov1 = np.array([[cov_1, 0], [0, cov_2]]) cov2 = np.array([[cov_1, 0], [0, cov_2]]) X1 = np.random.multivariate_normal(mu1, cov1, n) X2 = np.random.multivariate_normal(mu2, cov2, n) X = np.concatenate((X1, X2)) y = np.repeat([0, 1], int(len(X) / 2)) aris, _, _ = exp(X, y, range(2, 6), 10) return aris aris_all_ellip = Parallel(n_jobs=35, verbose=1)(delayed(_run)() for _ in range(rep)) df = pd.DataFrame(aris_all_ellip) df.columns = [ "AutoGMM", "Naive GM", "Naive GM\n(multi init)", "K-Means", "Agglomerative", ] df = pd.melt(df, value_vars=df.columns, value_name="ARI", var_name="Algorithm") fig, ax = plt.subplots(1, figsize=(12, 6)) sns.swarmplot(data=df, x="Algorithm", y="ARI", ax=ax, size=3) sns.boxplot( data=df, x="Algorithm", y="ARI", ax=ax, boxprops=dict(alpha=0.25), whis=np.inf, notch=True, width=0.1, ) ax.set_title("ARIs for Different Clustering Algorithms", fontsize=20, fontweight="bold") ax.set_xlabel("") ax.set_ylabel("ARI", fontsize=20) ax.set_xticklabels(ax.get_xticklabels(), fontsize=20) plt.savefig("/results/cigar_aris_boxplot.png", bbox_inches="tight", dpi=300) plt.show()
python
17
0.586004
88
29.158654
208
starcoderdata
package org.apache.batik.gvt; import org.apache.batik.gvt.event.GraphicsNodeChangeListener; import org.apache.batik.gvt.event.GraphicsNodeKeyListener; import org.apache.batik.gvt.event.GraphicsNodeMouseListener; import org.apache.batik.gvt.event.SelectionListener; public interface Selector extends GraphicsNodeMouseListener, GraphicsNodeKeyListener, GraphicsNodeChangeListener { Object getSelection(); boolean isEmpty(); void addSelectionListener(SelectionListener var1); void removeSelectionListener(SelectionListener var1); }
java
7
0.835165
114
33.125
16
starcoderdata
package com.liyulin.demo.mall.product.service.rpc; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.liyulin.demo.common.business.dto.BaseDto; import com.liyulin.demo.common.business.dto.Resp; import com.liyulin.demo.common.business.util.RespUtil; import com.liyulin.demo.mall.product.biz.rpc.ProductInfoRpcBiz; import com.liyulin.demo.mall.product.enums.ProductReturnCodeEnum; import com.liyulin.demo.rpc.product.request.rpc.QryProductByIdReqBody; import com.liyulin.demo.rpc.product.request.rpc.QryProductByIdsReqBody; import com.liyulin.demo.rpc.product.request.rpc.UpdateStockReqBody; import com.liyulin.demo.rpc.product.response.rpc.QryProductByIdRespBody; import com.liyulin.demo.rpc.product.response.rpc.QryProductByIdsRespBody; /** * 商品信息rpc service * * @author liyulin * @date 2019年3月29日下午11:52:13 */ @Service public class ProductInfoRpcService { @Autowired private ProductInfoRpcBiz productRpcBiz; /** * 根据id查询商品信息 * * @param reqBody * @return */ public QryProductByIdRespBody qryProductById(QryProductByIdReqBody reqBody) { return productRpcBiz.qryProductById(reqBody); } /** * 根据ids查询商品信息 * * @param reqBody * @return */ public QryProductByIdsRespBody qryProductByIds(QryProductByIdsReqBody reqBody) { return productRpcBiz.qryProductByIds(reqBody); } /** * 扣减库存 * * @param list * @return */ @Transactional public Resp updateStock(List list) { boolean success = productRpcBiz.updateStock(list); return success ? RespUtil.success() : RespUtil.error(ProductReturnCodeEnum.STOCK_NOT_ENOUGH); } }
java
10
0.784904
95
26.123077
65
starcoderdata
<?php namespace CFDIReaderTests\SchemasValidator; use CFDIReader\SchemasValidator\SchemasValidator; use PHPUnit\Framework\TestCase; use XmlResourceRetriever\XsdRetriever; class SchemasValidatorTest extends TestCase { public function testDefaultConstructor() { $validator = new SchemasValidator(); $this->assertFalse($validator->hasRetriever()); } public function testDefaultConstructorWithArguments() { $retriever = new XsdRetriever(__DIR__); $validator = new SchemasValidator($retriever); $this->assertSame($retriever, $validator->getRetriever()); $this->assertTrue($validator->hasRetriever()); } public function testGetRetrieverThrowALogicExceptionWhenNoRetrieverHasBeenSet() { $validator = new SchemasValidator(); $this->expectException(\LogicException::class); $validator->getRetriever(); } public function testValidateWithRetrieverUnset() { $validator = new SchemasValidator(); $validator->validate(' $this->assertTrue(true, 'This method should not raise any exception'); } }
php
12
0.706755
83
30.947368
38
starcoderdata
<?PHP /* Copyright 2005-2018, Lime Technology * Copyright 2012-2018, Bergware International. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. */ ?> <? // Define root path $docroot = $_SERVER['DOCUMENT_ROOT']; require_once "$docroot/webGui/include/Helpers.php"; require_once "$docroot/webGui/include/PageBuilder.php"; // Get the webGui configuration preferences extract(parse_plugin_cfg('dynamix',true)); // Read emhttp status $var = (array)parse_ini_file('state/var.ini'); $sec = (array)parse_ini_file('state/sec.ini',true); $devs = (array)parse_ini_file('state/devs.ini',true); $disks = (array)parse_ini_file('state/disks.ini',true); $users = (array)parse_ini_file('state/users.ini',true); $shares = (array)parse_ini_file('state/shares.ini',true); $sec_nfs = (array)parse_ini_file('state/sec_nfs.ini',true); $sec_afp = (array)parse_ini_file('state/sec_afp.ini',true); // Read network settings extract(parse_ini_file('state/network.ini',true)); // Merge SMART settings require_once "$docroot/webGui/include/CustomMerge.php"; // Build webGui pages first, then plugins pages $site = []; build_pages('webGui/*.page'); foreach (glob('plugins/*', GLOB_ONLYDIR) as $plugin) { if ($plugin != 'plugins/dynamix') build_pages("$plugin/*.page"); } // get variables $name = $_GET['name']; $dir = $_GET['dir']; $path = substr(explode('?', $_SERVER['REQUEST_URI'])[0], 1); // The current "task" is the first element of the path $task = strtok($path, '/'); // Here's the page we're rendering $myPage = $site[basename($path)]; $pageroot = $docroot.'/'.dirname($myPage['file']); $update = true; // set for legacy // Giddyup require_once "$docroot/webGui/include/DefaultPageLayout.php"; ?>
php
12
0.697239
77
31.709677
62
starcoderdata
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_INPUT_STUDENT_WITH_QUALIFICATION; import static seedu.address.logic.commands.CommandTestUtil.GENDER_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.GENDER_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.INVALID_GENDER_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_NAME_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_PHONE_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_PREAMBLE; import static seedu.address.logic.commands.CommandTestUtil.INVALID_QUALIFICATION_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_REMARK_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_TAG_DESC; import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.PHONE_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.PHONE_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.QUALIFICATION_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.REMARK_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.REMARK_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_PM; import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_PM_TP; import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_TP; import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_UNCAPITALIZED; import static seedu.address.logic.commands.CommandTestUtil.VALID_GENDER_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_GENDER_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_QUALIFICATION_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_STUDENT_LETTER; import static seedu.address.logic.commands.CommandTestUtil.VALID_STUDENT_TYPE; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_PM; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_TP; import static seedu.address.logic.commands.CommandTestUtil.VALID_TUTOR_LETTER; import static seedu.address.logic.commands.CommandTestUtil.VALID_TUTOR_TYPE; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import static seedu.address.testutil.TypicalPersons.AMY; import static seedu.address.testutil.TypicalPersons.BOB; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.AddCommand; import seedu.address.model.person.Gender; import seedu.address.model.person.Name; import seedu.address.model.person.Person; import seedu.address.model.person.Phone; import seedu.address.model.person.Qualification; import seedu.address.model.person.Remark; import seedu.address.model.person.Student; import seedu.address.model.person.Tutor; import seedu.address.model.tag.Tag; import seedu.address.testutil.StudentBuilder; import seedu.address.testutil.TutorBuilder; public class AddCommandParserTest { private AddCommandParser parser = new AddCommandParser(); @Test public void parse_allStudentFieldsPresent_success() { Student expectedStudent = new StudentBuilder(AMY).withTag(VALID_TAG_PM).build(); // multiple names - last name accepted assertParseSuccess(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM, new AddCommand(expectedStudent, VALID_STUDENT_TYPE)); // multiple phones - last phone accepted assertParseSuccess(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM, new AddCommand(expectedStudent, VALID_STUDENT_TYPE)); // multiple genders - last gender accepted assertParseSuccess(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM, new AddCommand(expectedStudent, VALID_STUDENT_TYPE)); // multiple remarks - last remark accepted assertParseSuccess(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_BOB + REMARK_DESC_AMY + TAG_DESC_PM, new AddCommand(expectedStudent, VALID_STUDENT_TYPE)); // one tag - accepted Student expectedStudentOneTag = new StudentBuilder(AMY).withTag(VALID_TAG_TP).build(); assertParseSuccess(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_TP, new AddCommand(expectedStudentOneTag, VALID_STUDENT_TYPE)); // multiple tag prefixes - tags in latest tag prefix accepted Student expectedStudentMultipleTagPrefix = new StudentBuilder(AMY).withTag(VALID_TAG_TP).build(); assertParseSuccess(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM + TAG_DESC_TP, new AddCommand(expectedStudentMultipleTagPrefix, VALID_STUDENT_TYPE)); } @Test public void parse_allTutorFieldsPresent_success() { Tutor expectedTutor = new TutorBuilder(BOB).withTags(VALID_TAG_TP).build(); // multiple names - last name accepted assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_AMY + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_TP, new AddCommand(expectedTutor, VALID_TUTOR_TYPE)); // multiple phones - last phone accepted assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_AMY + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_TP, new AddCommand(expectedTutor, VALID_TUTOR_TYPE)); // multiple genders - last gender accepted assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_AMY + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_TP, new AddCommand(expectedTutor, VALID_TUTOR_TYPE)); // multiple remarks - last remark accepted assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_AMY + REMARK_DESC_BOB + TAG_DESC_TP, new AddCommand(expectedTutor, VALID_TUTOR_TYPE)); //Check that tags are case-insensitive assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_UNCAPITALIZED, new AddCommand(expectedTutor, VALID_TUTOR_TYPE)); // multiple tag prefixes - tags in latest tag prefix accepted Person expectedTutorMultipleTagPrefixes = new TutorBuilder(BOB).withTags(VALID_TAG_TP).build(); assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM + TAG_DESC_TP, new AddCommand(expectedTutorMultipleTagPrefixes, VALID_TUTOR_TYPE)); // multiple tag arguments - all arguments for tag prefix accepted Person expectedTutorMultipleTags = new TutorBuilder(BOB).withTags(VALID_TAG_TP, VALID_TAG_PM) .build(); assertParseSuccess(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM_TP, new AddCommand(expectedTutorMultipleTags, VALID_TUTOR_TYPE)); } @Test public void parse_compulsoryStudentFieldMissing_failure() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); // missing name prefix assertParseFailure(parser, VALID_STUDENT_LETTER + " " + VALID_NAME_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + TAG_DESC_PM, expectedMessage); // missing phone prefix assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + VALID_PHONE_AMY + GENDER_DESC_AMY + TAG_DESC_PM, expectedMessage); // missing gender prefix assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + VALID_GENDER_AMY + TAG_DESC_PM, expectedMessage); // missing tag prefix assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + VALID_TAG_PM, expectedMessage); // all prefixes missing assertParseFailure(parser, VALID_STUDENT_LETTER + " " + VALID_NAME_AMY + VALID_PHONE_AMY + VALID_GENDER_AMY + VALID_TAG_PM, expectedMessage); } @Test public void parse_compulsoryTutorFieldMissing_failure() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); // missing name prefix assertParseFailure(parser, VALID_TUTOR_LETTER + " " + VALID_NAME_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + TAG_DESC_PM, expectedMessage); // missing phone prefix assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + VALID_PHONE_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + TAG_DESC_PM, expectedMessage); // missing gender prefix assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + VALID_GENDER_BOB + QUALIFICATION_DESC_BOB + TAG_DESC_PM, expectedMessage); // missing qualification prefix assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + VALID_QUALIFICATION_BOB + TAG_DESC_PM, expectedMessage); // missing tag prefix assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + VALID_TAG_PM, expectedMessage); // all prefixes missing assertParseFailure(parser, VALID_TUTOR_LETTER + " " + VALID_NAME_BOB + VALID_PHONE_BOB + VALID_GENDER_BOB + VALID_QUALIFICATION_BOB + VALID_TAG_PM, expectedMessage); } @Test public void parse_invalidStudentValue_failure() { // invalid name assertParseFailure(parser, VALID_STUDENT_LETTER + INVALID_NAME_DESC + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM_TP, Name.MESSAGE_CONSTRAINTS); // invalid phone assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + INVALID_PHONE_DESC + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM_TP, Phone.MESSAGE_CONSTRAINTS); // invalid gender assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + INVALID_GENDER_DESC + REMARK_DESC_AMY + TAG_DESC_PM_TP, Gender.MESSAGE_CONSTRAINTS); // invalid tag assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + INVALID_TAG_DESC, Tag.MESSAGE_INVALID_TAG); // invalid remark assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + INVALID_REMARK_DESC + TAG_DESC_PM_TP, Remark.MESSAGE_CONSTRAINTS); // two invalid values, only first invalid value reported assertParseFailure(parser, VALID_STUDENT_LETTER + INVALID_NAME_DESC + PHONE_DESC_AMY + INVALID_GENDER_DESC + REMARK_DESC_AMY + TAG_DESC_PM_TP, Name.MESSAGE_CONSTRAINTS); // Invalid personType (not "t" or "s") String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertParseFailure(parser, INVALID_PREAMBLE + NAME_DESC_AMY + PHONE_DESC_AMY + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM_TP, expectedMessage); } @Test public void parse_invalidTutorValue_failure() { // invalid name assertParseFailure(parser, VALID_TUTOR_LETTER + INVALID_NAME_DESC + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM_TP, Name.MESSAGE_CONSTRAINTS); // invalid phone assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + INVALID_PHONE_DESC + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM_TP, Phone.MESSAGE_CONSTRAINTS); // invalid gender assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + INVALID_GENDER_DESC + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM_TP, Gender.MESSAGE_CONSTRAINTS); // invalid qualification assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + INVALID_QUALIFICATION_DESC + REMARK_DESC_BOB + TAG_DESC_PM_TP, Qualification.MESSAGE_CONSTRAINTS); // invalid tag assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + INVALID_TAG_DESC, Tag.MESSAGE_INVALID_TAG); // invalid remark assertParseFailure(parser, VALID_TUTOR_LETTER + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + INVALID_REMARK_DESC + TAG_DESC_PM_TP, Remark.MESSAGE_CONSTRAINTS); // two invalid values, only first invalid value reported assertParseFailure(parser, VALID_TUTOR_LETTER + INVALID_NAME_DESC + PHONE_DESC_BOB + INVALID_GENDER_DESC + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM_TP, Name.MESSAGE_CONSTRAINTS); // Invalid personType (not "t" or "s") String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertParseFailure(parser, INVALID_PREAMBLE + NAME_DESC_BOB + PHONE_DESC_BOB + GENDER_DESC_BOB + QUALIFICATION_DESC_BOB + REMARK_DESC_BOB + TAG_DESC_PM_TP, expectedMessage); } @Test public void parse_invalidStudentWithQualification_throwsParseException() { assertParseFailure(parser, VALID_STUDENT_LETTER + NAME_DESC_AMY + PHONE_DESC_AMY + QUALIFICATION_DESC_BOB + GENDER_DESC_AMY + REMARK_DESC_AMY + TAG_DESC_PM, MESSAGE_INVALID_INPUT_STUDENT_WITH_QUALIFICATION); } }
java
13
0.707365
120
56.670412
267
starcoderdata
/* Copyright 2022 * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #include "libyagbe/timer.h" #include "libyagbe/bus.h" #include "libyagbe/compat/compat_stdbool.h" #include "libyagbe/debug/logger.h" #include "libyagbe/scheduler.h" #include "utility.h" static struct libyagbe_timer timer; static const unsigned int timing[4] = {1024, 256, 16, 8}; static void handle_tima_increment(void); static void handle_tima_overflow(void); static void set_tac_value(const uint8_t new_tac) { timer.tac = (timer.tac & ~0x07) | (new_tac & 0x07); } static bool timer_is_enabled(void) { return BIT_IS_SET(timer.tac, LIBYAGBE_TIMER_TAC_ENABLED); } static void insert_tima_increment_event(void) { struct libyagbe_scheduler_event event; event.timestamp = timing[timer.tac & LIBYAGBE_TIMER_TAC_CLOCK_MASK]; event.cb_func = &handle_tima_increment; event.type = LIBYAGBE_SCHEDULER_EVENT_TIMA_INCREMENT; event.group = LIBYAGBE_SCHEDULER_EVENT_GROUP_TIMER; libyagbe_scheduler_insert_event(&event); } static void insert_tima_overflow_event(void) { struct libyagbe_scheduler_event event; event.timestamp = timing[timer.tac & LIBYAGBE_TIMER_TAC_CLOCK_MASK]; event.cb_func = &handle_tima_overflow; event.type = LIBYAGBE_SCHEDULER_EVENT_TIMA_OVERFLOW; event.group = LIBYAGBE_SCHEDULER_EVENT_GROUP_TIMER; libyagbe_scheduler_insert_event(&event); } #if 0 static void adjust_tima_overflow_timestamp(const uint8_t new_tima_value) { (void)new_tima_value; struct libyagbe_scheduler_event* event = libyagbe_scheduler_find_event(LIBYAGBE_SCHEDULER_EVENT_TIMA_OVERFLOW); uintmax_t delta; /* This event should be guaranteed to be present. */ assert(event != NULL); delta = (0xFF - new_tima_value) * timing[timer.tac & LIBYAGBE_TIMER_TAC_CLOCK_MASK]; } #endif static void handle_tima_overflow(void) { timer.tima = timer.tma; libyagbe_bus_set_interrupt(LIBYAGBE_BUS_IF_TIMER); if (timer_is_enabled()) { insert_tima_overflow_event(); } } static void handle_tima_increment(void) { timer.tima++; if (timer_is_enabled()) { insert_tima_increment_event(); } } void libyagbe_timer_reset(void) { timer.tima = 0x00; timer.tma = 0x00; timer.tac = 0xF8; } void libyagbe_timer_handle_tima_write(const uint8_t new_tima_value) { if (timer_is_enabled()) { /* The timer is enabled, which means a TIMA overflow event is already * present. We need to adjust the expiry time for it. */ /*adjust_tima_overflow_timestamp(new_tima_value);*/ } timer.tima = new_tima_value; } void libyagbe_timer_handle_tma_write(const uint8_t new_tma_value) { timer.tma = new_tma_value; } void libyagbe_timer_handle_tac_write(const uint8_t new_tac_value) { /* Is the timer being enabled from a disabled state? */ if (!timer_is_enabled() && BIT_IS_SET(new_tac_value, LIBYAGBE_TIMER_TAC_ENABLED)) { libyagbe_log(LIBYAGBE_LOG_LEVEL_INFO, "Timer became enabled."); /* The timer has now been enabled from a previously disabled state, * schedule the appropriate events. */ insert_tima_increment_event(); insert_tima_overflow_event(); set_tac_value(new_tac_value); return; } /* Is the timer being disabled from an enabled state? */ if (timer_is_enabled() && !BIT_IS_SET(new_tac_value, LIBYAGBE_TIMER_TAC_ENABLED)) { libyagbe_log(LIBYAGBE_LOG_LEVEL_INFO, "Timer became disabled."); libyagbe_scheduler_delete_event_group(LIBYAGBE_SCHEDULER_EVENT_GROUP_TIMER); set_tac_value(new_tac_value); return; } }
c
10
0.717371
80
30.094891
137
starcoderdata
<?php namespace App\Http\Controllers; use App\User; use App\Team; use App\Post; use App\Time_Line; use App\Time_Line_Post; use App\Time_Line_Post_Comment; use App\Time_Line_Post_Good; use Illuminate\Http\Request; use App\Http\Requests\PostRequest; use App\Http\Requests\CommentRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class TimeLinePostController extends Controller { public function index(Team $team, Time_Line_Post $time_line_post) { $time_line=$team->time_lines()->first(); return view('teams/time_lines/index')->with(['team'=>$team,'time_line_posts'=>$time_line_post->getPaginateByLimit($time_line->id)]); } public function show(Team $team, Time_Line_Post $time_line_post) { $time_line_post_comments=DB::table('time_line_post_comments')->where('time_line_post_id',$time_line_post->id)->get(); return view('teams/time_lines/show')->with(['team'=>$team,'time_line_post'=>$time_line_post,'time_line_post_comments'=>$time_line_post_comments]); } public function create(Team $team) { return view('teams/time_lines/create')->with(['team'=>$team ]); } public function store(PostRequest $request, Time_Line_Post $time_line_post, Team $team) { $user=Auth::user(); $time_line_post->title=$request['post']['title']; $time_line_post->body=$request['post']['body']; $time_line_post->user_id=$user->id; $time_line_post->time_line_id=DB::table('time_lines')->where('team_id',$team->id)->first()->id; $time_line_post->save(); return redirect('/teams/'.$team->id.'/time_lines/index'); } public function post_delete(Request $request, Team $team, Time_Line_Post $time_line_post) { if(!DB::table('time_line_post_comments')->where('time_line_post_id',$time_line_post->id)->doesntExist()){ DB::table('time_line_post_comments')->where('time_line_post_id',$time_line_post->id)->delete(); } $time_line_post_delete=Time_Line_Post::where('id',$time_line_post->id)->first(); $time_line_post_delete->delete(); return redirect('/teams/'.$team->id.'/time_lines/index'); } public function comment(CommentRequest $request, Team $team, Time_Line_Post $time_line_post, Time_Line_Post_Comment $time_line_post_comment) { $user=Auth::user(); $time_line_post_comment->body=$request['comment']['body']; $time_line_post_comment->user_id=$user->id; $time_line_post_comment->time_line_post_id=$time_line_post->id; $time_line_post_comment->save(); return redirect('/teams/'.$team->id.'/time_line_posts/'.$time_line_post->id.'/show'); } public function good(Request $request, Team $team, Time_Line_Post $time_line_post, Time_Line_Post_Good $time_line_post_good) { $user=Auth::user(); if(DB::table('time_line_post_goods')->where('time_line_post_id',$time_line_post->id)->where('user_id',$user->id)->doesntExist()){ $time_line_post_good->user_id=$user->id; $time_line_post_good->time_line_post_id=$time_line_post->id; $time_line_post_good->save(); }else{ $good_delete=Time_Line_Post_Good::where('time_line_post_id',$time_line_post->id)->where('user_id',$user->id)->first(); $good_delete->delete(); } return redirect('/teams/'.$team->id.'/time_line_posts/'.$time_line_post->id.'/show'); } public function comment_delete(Request $request, Team $team, Time_Line_Post $time_line_post, Time_Line_Post_Comment $time_line_post_comment) { $comment_delete=Time_Line_Post_Comment::where('id',$time_line_post_comment->id)->first(); $comment_delete->delete(); return redirect('/teams/'.$team->id.'/time_line_posts/'.$time_line_post->id.'/show'); } }
php
17
0.617901
154
40.515789
95
starcoderdata
package sbproclient var ( messagePrefix []byte = []byte(" messageSuffix []byte = []byte(" ) var ( requestSymbols []byte = []byte("newsymbols^-^-") ) var ( begin = []byte(" end = []byte(" )
go
6
0.555556
49
14
15
starcoderdata
requirejs.config({ paths : { backbone : 'vendor/js/backbone-min', handlebars : 'vendor/js/handlebars.amd.min', jquery : 'vendor/js/jquery.min', underscore : 'vendor/js/underscore-min' }, shim : { underscore : { exports : '_' } } }); require( [ 'js/controllers/AppController' ], function ( AppController ) { var app = new AppController( document.getElementById('app') ); } );
javascript
13
0.529897
70
19.25
24
starcoderdata
## ## division.py ## def division(x, y): try: result = x // y except ZeroDivisionError as divisionError: print('No, you still cannot divide by zero (0)!') print('Error Caught: ---> ', divisionError) except KeyboardInterrupt as myKeyboard: print('You must use integers!') print('Error Caught: ---> ', myKeyboard) else: print(result) def main(): x = int(input('Enter a value for x: ')) y = int(input('Enter a value for y: ')) division(x, y) if __name__ == '__main__': main() ## ## End of file...
python
10
0.614828
51
18.785714
28
starcoderdata
#ifndef FWLite_TFileService_h #define FWLite_TFileService_h /* \class fwlite::TFileService * * \author CERN * */ #include "CommonTools/Utils/interface/TFileDirectory.h" namespace fwlite { class TFileService : public TFileDirectory { public: /// constructor TFileService(const std::string& fileName); /// constructor with external TFile TFileService(TFile * aFile); /// destructor ~TFileService() override; /// return opened TFile TFile & file() const { return * file_; } private: /// pointer to opened TFile TFile * file_; std::string fileName_; }; } #endif
c
11
0.69103
55
16.705882
34
starcoderdata
V get(const K &key) override { // We check if 'key' is in the hash map auto iter = m_hashmap.find(key); if (iter == m_hashmap.end()) { throw std::invalid_argument( "Key is not found!"); // throw an exception that indicates 'not found' } // Otherwise, push the (key, value) pair to the front of 'm_list' and update // the hash map m_list.emplace_front(std::make_pair(key, iter->second->second)); m_list.erase(iter->second); iter->second = m_list.begin(); // Return 'value' from the pair return m_list.begin()->second; }
c++
10
0.612069
80
37.733333
15
inline
import React from "react"; import Logo from "./Logo"; import Burger from "./Burger"; function NavBrand() { return ( <> <div className="navbar-brand"> <Logo /> <Burger /> <input type="checkbox" id="nav-toggle-state" /> {/* ^ Necessary for burger functionality */} ); } export default NavBrand;
javascript
10
0.567039
53
17.894737
19
starcoderdata
<?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Gate; use DataTables; use App\TypeOfProductTrade; use App\permission_ex_details_freight; use App\permission_ent_details_freight; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class TypeOfProductTradeController extends Controller { public function index() { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } $TypeOfProductTrades = TypeOfProductTrade::orderBy('id', 'DESC')->paginate(50); return view('admin.TypeOfProductTrades.index', compact('TypeOfProductTrades')); } public function getTypeOfProductTrade() { $TypeOfProductTrades = TypeOfProductTrade::select(['id','name','created_at','updated_at']); return DataTables::of($TypeOfProductTrades) ->addColumn('action', function ($TypeOfProductTrades) { return '<a href="/typeofproducttrade/'.$TypeOfProductTrades->id.'/edit" class="btn btn-block btn-primary" ><i class="fa fa-edit"> تعديل '; })//->addColumn('delete', function ($TypeOfProductTrades) { // return '<a class="btn btn-danger btn-block delete p2" data-title-message="تم حذف المجوعه" data-message="تم حذف المجموعه بنجاح" del-name="'.$TypeOfProductTrades->name.'" del-url="/TypeOfProductTrade/'.$TypeOfProductTrades->id.'" tabindex="1" data-toggle="tooltip" data-placement="top" title="Delete Account Type"><i class="fa fa-trash"> //}) ->rawColumns([ 'action','delete']) ->make(true); } public function create() { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } return view('admin.TypeOfProductTrades.add'); } public function store(Request $request) { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } $this->validate(request(), [ 'name' => 'required|string|max:150' ]); $TypeOfProductTrades = TypeOfProductTrade::create([ 'name' => $request->name ]); return redirect()->route('typeofproducttrade.index')->with('success', 'تم حفظ نوع الصنف بنجاح'); // return back()->with('success', 'تمام اضافه المنتج بنجاح'); } public function edit($id) { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } $TypeOfProductTrades = TypeOfProductTrade::where('id', $id)->first(); if ($TypeOfProductTrades != null) { return view('admin.TypeOfProductTrades.edit', ['TypeOfProductTrades' => $TypeOfProductTrades]); } return back(); } public function update(Request $request, $id) { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } $TypeOfProductTrades = TypeOfProductTrade::where('id', $id)->first(); if ($TypeOfProductTrades != null) { $this->validate(request(), [ 'name' => 'required|string|max:150' ]); $TypeOfProductTrades->update([ 'name' => $request->name ]); return redirect()->route('typeofproducttrade.index')->with('success', 'تم تعديل المنتج بنجاح'); } return back()->with('delete', 'Account type not has been updated'); } public function destroy($id) { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } $TypeOfProductTrades = TypeOfProductTrade::where('id', $id)->first(); if ($TypeOfProductTrades != null) { $TypeOfProductTrades->delete(); return response()->json(['status' => true, 'message' => 'mobilats type has been deleted successfully']); } else { return back(); } } public function showInventory() { if (! Gate::allows('تكويد اصناف شحن')) { return redirect()->back()->with('delete', 'ليس لديك صلاحيه للدخول'); } $MobilatDetails4 = MobilatDetails::where('action',2)->where('Prodact_name', 1)->get(); $MobilatDetails3 = MobilatDetails::where('action',1)->where('Prodact_name', 1)->get(); $totalprodact = count($MobilatDetails3)-count($MobilatDetails4); $TypeOfProductTrade = TypeOfProductTrade::orderBy('id', 'DESC')->paginate(50); $permission_ex_details_freight = permission_ex_details_freight::where('TypeOfProductTrade',1)->where('active',1)->pluck('Quantity')->sum(); $permission_ent_details_freight = permission_ent_details_freight::where('type_id',1)->pluck('Quantityrecipient')->sum(); $total = $permission_ent_details_freight - $permission_ex_details_freight; if ($TypeOfProductTrade != null) { return view('admin.TypeOfProductTrades.inventory', compact('TypeOfProductTrade' )); } else { return back(); } } }
php
18
0.608981
366
35.542254
142
starcoderdata
namespace W5XD_antennas { partial class TwoByRatPak { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.groupLeft = new System.Windows.Forms.GroupBox(); this.buttonL80_15m = new System.Windows.Forms.RadioButton(); this.buttonL80_160m = new System.Windows.Forms.RadioButton(); this.buttonL40m = new System.Windows.Forms.RadioButton(); this.buttonL20m = new System.Windows.Forms.RadioButton(); this.buttonL15m = new System.Windows.Forms.RadioButton(); this.buttonL10m = new System.Windows.Forms.RadioButton(); this.groupBoxR = new System.Windows.Forms.GroupBox(); this.buttonR80_15m = new System.Windows.Forms.RadioButton(); this.buttonR80_160m = new System.Windows.Forms.RadioButton(); this.buttonR40m = new System.Windows.Forms.RadioButton(); this.buttonR20m = new System.Windows.Forms.RadioButton(); this.buttonR15m = new System.Windows.Forms.RadioButton(); this.buttonR10m = new System.Windows.Forms.RadioButton(); this.groupLeft.SuspendLayout(); this.groupBoxR.SuspendLayout(); this.SuspendLayout(); // // groupLeft // this.groupLeft.Controls.Add(this.buttonL80_15m); this.groupLeft.Controls.Add(this.buttonL80_160m); this.groupLeft.Controls.Add(this.buttonL40m); this.groupLeft.Controls.Add(this.buttonL20m); this.groupLeft.Controls.Add(this.buttonL15m); this.groupLeft.Controls.Add(this.buttonL10m); this.groupLeft.Location = new System.Drawing.Point(5, 3); this.groupLeft.Name = "groupLeft"; this.groupLeft.Size = new System.Drawing.Size(356, 68); this.groupLeft.TabIndex = 0; this.groupLeft.TabStop = false; this.groupLeft.Text = "Left"; // // buttonL80_15m // this.buttonL80_15m.Enabled = false; this.buttonL80_15m.Location = new System.Drawing.Point(300, 19); this.buttonL80_15m.Name = "buttonL80_15m"; this.buttonL80_15m.Size = new System.Drawing.Size(55, 43); this.buttonL80_15m.TabIndex = 5; this.buttonL80_15m.Text = "Vert"; this.buttonL80_15m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonL80_15m.UseVisualStyleBackColor = true; // // buttonL80_160m // this.buttonL80_160m.Enabled = false; this.buttonL80_160m.Location = new System.Drawing.Point(232, 19); this.buttonL80_160m.Name = "buttonL80_160m"; this.buttonL80_160m.Size = new System.Drawing.Size(64, 43); this.buttonL80_160m.TabIndex = 4; this.buttonL80_160m.Text = "80&&160 loop"; this.buttonL80_160m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonL80_160m.UseVisualStyleBackColor = true; // // buttonL40m // this.buttonL40m.Enabled = false; this.buttonL40m.Location = new System.Drawing.Point(171, 19); this.buttonL40m.Name = "buttonL40m"; this.buttonL40m.Size = new System.Drawing.Size(57, 43); this.buttonL40m.TabIndex = 3; this.buttonL40m.Text = "40m dipole"; this.buttonL40m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonL40m.UseVisualStyleBackColor = true; // // buttonL20m // this.buttonL20m.Enabled = false; this.buttonL20m.Location = new System.Drawing.Point(116, 19); this.buttonL20m.Name = "buttonL20m"; this.buttonL20m.Size = new System.Drawing.Size(51, 43); this.buttonL20m.TabIndex = 2; this.buttonL20m.Text = "KT34 20"; this.buttonL20m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonL20m.UseVisualStyleBackColor = true; // // buttonL15m // this.buttonL15m.Enabled = false; this.buttonL15m.Location = new System.Drawing.Point(61, 19); this.buttonL15m.Name = "buttonL15m"; this.buttonL15m.Size = new System.Drawing.Size(51, 43); this.buttonL15m.TabIndex = 1; this.buttonL15m.Text = "KT34 15"; this.buttonL15m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonL15m.UseVisualStyleBackColor = true; // // buttonL10m // this.buttonL10m.Enabled = false; this.buttonL10m.Location = new System.Drawing.Point(6, 19); this.buttonL10m.Name = "buttonL10m"; this.buttonL10m.Size = new System.Drawing.Size(51, 43); this.buttonL10m.TabIndex = 0; this.buttonL10m.Text = "KT34 10"; this.buttonL10m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonL10m.UseVisualStyleBackColor = true; // // groupBoxR // this.groupBoxR.Controls.Add(this.buttonR80_15m); this.groupBoxR.Controls.Add(this.buttonR80_160m); this.groupBoxR.Controls.Add(this.buttonR40m); this.groupBoxR.Controls.Add(this.buttonR20m); this.groupBoxR.Controls.Add(this.buttonR15m); this.groupBoxR.Controls.Add(this.buttonR10m); this.groupBoxR.Location = new System.Drawing.Point(379, 3); this.groupBoxR.Name = "groupBoxR"; this.groupBoxR.Size = new System.Drawing.Size(358, 68); this.groupBoxR.TabIndex = 1; this.groupBoxR.TabStop = false; this.groupBoxR.Text = "Right"; // // buttonR80_15m // this.buttonR80_15m.Enabled = false; this.buttonR80_15m.Location = new System.Drawing.Point(300, 19); this.buttonR80_15m.Name = "buttonR80_15m"; this.buttonR80_15m.Size = new System.Drawing.Size(55, 43); this.buttonR80_15m.TabIndex = 5; this.buttonR80_15m.Text = "Vert"; this.buttonR80_15m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonR80_15m.UseVisualStyleBackColor = true; // // buttonR80_160m // this.buttonR80_160m.Enabled = false; this.buttonR80_160m.Location = new System.Drawing.Point(232, 19); this.buttonR80_160m.Name = "buttonR80_160m"; this.buttonR80_160m.Size = new System.Drawing.Size(64, 43); this.buttonR80_160m.TabIndex = 4; this.buttonR80_160m.Text = "80&&160 loop"; this.buttonR80_160m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonR80_160m.UseVisualStyleBackColor = true; // // buttonR40m // this.buttonR40m.Enabled = false; this.buttonR40m.Location = new System.Drawing.Point(171, 19); this.buttonR40m.Name = "buttonR40m"; this.buttonR40m.Size = new System.Drawing.Size(57, 43); this.buttonR40m.TabIndex = 3; this.buttonR40m.Text = "40m dipole"; this.buttonR40m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonR40m.UseVisualStyleBackColor = true; // // buttonR20m // this.buttonR20m.Enabled = false; this.buttonR20m.Location = new System.Drawing.Point(116, 19); this.buttonR20m.Name = "buttonR20m"; this.buttonR20m.Size = new System.Drawing.Size(51, 43); this.buttonR20m.TabIndex = 2; this.buttonR20m.Text = "KT34 20"; this.buttonR20m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonR20m.UseVisualStyleBackColor = true; // // buttonR15m // this.buttonR15m.Enabled = false; this.buttonR15m.Location = new System.Drawing.Point(61, 19); this.buttonR15m.Name = "buttonR15m"; this.buttonR15m.Size = new System.Drawing.Size(51, 43); this.buttonR15m.TabIndex = 1; this.buttonR15m.Text = "KT34 15"; this.buttonR15m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonR15m.UseVisualStyleBackColor = true; // // buttonR10m // this.buttonR10m.Enabled = false; this.buttonR10m.Location = new System.Drawing.Point(6, 19); this.buttonR10m.Name = "buttonR10m"; this.buttonR10m.Size = new System.Drawing.Size(51, 43); this.buttonR10m.TabIndex = 0; this.buttonR10m.Text = "KT34 10"; this.buttonR10m.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.buttonR10m.UseVisualStyleBackColor = true; // // TwoByRatPak // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(743, 77); this.Controls.Add(this.groupBoxR); this.Controls.Add(this.groupLeft); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "TwoByRatPak"; this.Text = "W5XD RatPak"; this.Load += new System.EventHandler(this.TwoByRatPak_Load); this.groupLeft.ResumeLayout(false); this.groupBoxR.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupLeft; private System.Windows.Forms.RadioButton buttonL10m; private System.Windows.Forms.RadioButton buttonL80_15m; private System.Windows.Forms.RadioButton buttonL80_160m; private System.Windows.Forms.RadioButton buttonL40m; private System.Windows.Forms.RadioButton buttonL20m; private System.Windows.Forms.RadioButton buttonL15m; private System.Windows.Forms.GroupBox groupBoxR; private System.Windows.Forms.RadioButton buttonR80_15m; private System.Windows.Forms.RadioButton buttonR80_160m; private System.Windows.Forms.RadioButton buttonR40m; private System.Windows.Forms.RadioButton buttonR20m; private System.Windows.Forms.RadioButton buttonR15m; private System.Windows.Forms.RadioButton buttonR10m; } }
c#
11
0.600597
107
46.686992
246
starcoderdata
func (spdx *SPDX) PackageFromImageTarball( tarPath string, opts *TarballOptions, ) (imagePackage *Package, err error) { logrus.Infof("Generating SPDX package from image tarball %s", tarPath) // Extract all files from tarfile opts.ExtractDir, err = spdx.impl.ExtractTarballTmp(tarPath) if err != nil { return nil, errors.Wrap(err, "extracting tarball to temp dir") } defer os.RemoveAll(opts.ExtractDir) // Read the archive manifest json: manifest, err := spdx.impl.ReadArchiveManifest( filepath.Join(opts.ExtractDir, archiveManifestFilename), ) if err != nil { return nil, errors.Wrap(err, "while reading docker archive manifest") } if len(manifest.RepoTags) == 0 { return nil, errors.New("No RepoTags found in manifest") } if manifest.RepoTags[0] == "" { return nil, errors.New( "unable to add tar archive, manifest does not have a RepoTags entry", ) } logrus.Infof("Package describes %s image", manifest.RepoTags[0]) // Create the new SPDX package imagePackage = NewPackage() imagePackage.Options().WorkDir = opts.ExtractDir imagePackage.Name = manifest.RepoTags[0] logrus.Infof("Image manifest lists %d layers", len(manifest.LayerFiles)) // Cycle all the layers from the manifest and add them as packages for _, layerFile := range manifest.LayerFiles { // Generate a package from a layer pkg, err := spdx.impl.PackageFromLayerTarBall(layerFile, opts) if err != nil { return nil, errors.Wrap(err, "building package from layer") } // If the option is enabled, scan the container layers if spdx.options.AnalyzeLayers { if err := spdx.AnalyzeImageLayer(filepath.Join(opts.ExtractDir, layerFile), pkg); err != nil { return nil, errors.Wrap(err, "scanning layer "+pkg.ID) } } else { logrus.Info("Not performing deep image analysis (opts.AnalyzeLayers = false)") } // Add the layer package to the image package if err := imagePackage.AddPackage(pkg); err != nil { return nil, errors.Wrap(err, "adding layer to image package") } } // return the finished package return imagePackage, nil }
go
15
0.718208
97
30.953846
65
inline
<?php namespace App\Exports; use App\User; use Illuminate\Contracts\View\View; use Maatwebsite\Excel\Concerns\FromView; class AllOrgStudent implements FromView { public function view(): View { $students = User::where('role_id', 3)->where('teach_via', 1)->get(); return view('org::exports.all_students', [ 'students' => $students ]); } }
php
13
0.640288
76
20.947368
19
starcoderdata
using System; using FashionStore.Models; using Xamarin.Forms; namespace FashionStore.Utils { public class ProductTemplateSelector : DataTemplateSelector { public DataTemplate ProductTemplate { get; set; } public DataTemplate ProductsTemplate { get; set; } public ProductTemplateSelector() { } protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { return ((ProductData)item).IsSection ? ProductsTemplate : ProductTemplate; } } }
c#
12
0.699346
95
28.142857
21
starcoderdata
<?php namespace MichaelDrennen\RemoteFile\Exceptions; class MissingLastModifiedHeader extends RemoteFileException { }
php
3
0.835821
61
18.285714
7
starcoderdata
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package io.github.mmm.rpc.server; import io.github.mmm.rpc.request.RpcRequest; /** * Interface for a generic RPC service that aggregates all {@link RpcHandler}s to handle any RPC. * * @since 1.0.0 */ public interface RpcService { /** * @param type of the response. * @param request the {@link RpcRequest} to handle. * @return the response for the given {@code request}. */ R handle(RpcRequest request); /** * @param request the {@link HttpRequestReader} to read the request. * @param response the {@link HttpResponseWriter} to write the response. */ void handle(HttpRequestReader request, HttpResponseWriter response); }
java
8
0.697121
97
28.592593
27
starcoderdata
<?php require __DIR__ . '/../vendor/autoload.php'; $dotenv = new Dotenv\Dotenv(__DIR__ . '/..'); $dotenv->load(); $lang = require_once __DIR__ . '/../app/lang/' . strtolower(Language::getLocale()) . '.php'; $method = $_SERVER['REQUEST_METHOD']; $uri = $_SERVER['REQUEST_URI']; $uriParts = explode('/', $uri); $pageSlug = $uriParts[count($uriParts) - 1]; $templates = new \League\Plates\Engine(__DIR__ . '/../app/views'); $templates->registerFunction('activeLink', function($slug) use ($pageSlug) { return ($slug === $pageSlug) ? 'class="active"' : ''; }); $templates->registerFunction('trans', function($key) use ($lang) { if (array_key_exists($key, $lang)) { return $lang[$key]; } return $key; }); $connection = new PDO('mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME'), getenv('DB_USERNAME'), getenv('DB_PASSWORD')); $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $routes) use ($connection, $templates) { require __DIR__ . '/../app/routes.php'; }); if (($pos = strpos($uri, '?')) !== false) { $uri = substr($uri, 0, $pos); } $uri = rawurldecode($uri); $routeInfo = $dispatcher->dispatch($method, $uri); switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: echo $templates->render('404'); break; case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: echo $templates->render('404'); break; case FastRoute\Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; try { echo $handler(...array_values($vars)); } catch (Exception $e) { echo $templates->render('404'); } break; }
php
15
0.585965
136
27.516667
60
starcoderdata
#ifndef WINDOWOBJALLOCATORIMPL_H #define WINDOWOBJALLOCATORIMPL_H #include "../../MPI/WindowObjAllocator.h" namespace _MYNAMESPACE_ { namespace MPI { template < class T > int WinAllocate pointer &baseptr, MPI_Win &win, size_t &localCapacityCount, Environment::CommPtr comm, const size_t globalsize, const size_t localhalosize, const std::string &windowobjectname) { auto Globalsize = globalsize; auto Localhalosize = localhalosize; int MPISize = -1; MPI_Comm_size( comm->GetCommunicator(), &MPISize ); auto MPISize64 = static_cast< size_t >(MPISize); auto rest = ( ( Globalsize % MPISize64 ) == 0 ) ? 0 : MPISize64 - ( Globalsize % MPISize64 ) ; Globalsize += rest; size_t LocalSize = Globalsize / MPISize64 + Localhalosize; #ifdef MSMPI_VER #if MSMPI_VER <= 0x100 auto ret = MPI_Alloc_mem ( LocalSize * sizeof( T ), MPI_INFO_NULL, &baseptr ); ret = MPI_Win_create( baseptr, LocalSize * sizeof( T ), sizeof( T ), MPI_INFO_NULL, comm->GetCommunicator(), &win ); #endif #else auto ret = MPI_Win_allocate( LocalSize * sizeof( T ), sizeof( T ), MPI_INFO_NULL, comm->GetCommunicator(), &baseptr, &win ); #endif localCapacityCount = LocalSize; if( MPI_SUCCESS != ret ) { //! エラーを書く } MPI_Win_set_name( win, windowobjectname.c_str() ); return ret; } template < class T > int WinAllocate &win) { int ret = MPI_SUCCESS; //! たいていのMPIの実装ではWindowオブジェクトが開放されれば、 //! 自分が確保したメモリも開放しているので、ベースポインタを自 //! 前で開放する必要はない。ただしMSMPIv7までは、MPI3に完全 //! に準拠していないため、MPI_Win_allocateがまだ未実装であ //! り、例外として扱う。 #ifdef MSMPI_VER #if MSMPI_VER <= 0x100 T* baseptr = nullptr; int flag = 0; MPI_Win_get_attr( win, MPI_WIN_BASE, &baseptr, &flag ); if( baseptr != nullptr ) { MPI_Free_mem( baseptr ); } #endif #endif MPI_Win_free( &win ); win = MPI_WIN_NULL; return ret; } } } #endif // WINDOWOBJALLOCATORIMPL_H
c
16
0.41619
106
32.870968
93
starcoderdata
var _ = require('lodash'); describe("configParser", function() { var logger = require('../src/logger')(3); var configParser = require('../src/configParser')(logger); it('Should override basic types and objects',function(){ var config = { conf: __dirname + '/configParser/conf.js', // cofig file with data to override provider: {name:'test',key:'value'}}; // comming from command-line var mergedConfig = configParser.mergeConfigs(config); expect(mergedConfig.provider).toEqual({name:'test',key:'value'}); }); it('Should merge arrays in config', function () { var config = { conf: __dirname + '/configParser/conf.js', // default config file multi: [{name: 'option2'}] }; var mergedConfig = configParser.mergeConfigs(config); expect(mergedConfig.multi).toEqual([{name: 'option1'}, {name: 'option2'}]); }); it('Should resolve placeholders in config', function () { var config = { conf: __dirname + '/configParser/conf.js', parameters: { test: 'theme', rtl: 'rtl' }, osTypeString: 'win64' }; var mergedConfig = configParser.mergeConfigs(config); configParser.resolvePlaceholders(mergedConfig); expect(mergedConfig.test.key.param).toEqual('sap-ui-theme=sap_theme'); expect(mergedConfig.test.key.secondParam).toEqual('sap-ui-rtl=true'); }); }); describe("Should parse confkey from command-line", function () { var logger = require('../src/logger')(3); var configParser = require('../src/configParser')(logger); var cliParser = new require('../src/cliParser')(); var ArgvStub = function () { this._ = []; }; beforeEach(function() { delete require.cache[require.resolve('../src/configParser')]; delete require.cache[require.resolve('../conf/default.conf.js')]; delete require.cache[require.resolve('../conf/profile.conf.js')]; delete require.cache[require.resolve('../conf/visual.profile.conf.js')]; }); it('Should parse simple object notation in confkey', function () { var argvStub = new ArgvStub(); argvStub.confKeys = 'key2.key2:value'; var config = configParser.mergeConfigs(argvStub); expect(config.key2).toEqual({key2: 'value'}); expect(config.confKeys).toEqual('key2.key2:value'); expect(config.confKeys).toEqual(argvStub.confKeys) }); it('Should parse complex object notation in confkey', function () { var argvStub = new ArgvStub(); argvStub.confKeys = 'key1[0].key2:value'; var config = configParser.mergeConfigs(argvStub); expect(config.key1).toEqual([{key2: 'value'}]); expect(config.confKeys).toEqual('key1[0].key2:value'); }); it('Should parse several simple object notations in confkey object', function () { var argvStub = new ArgvStub(); argvStub.confKeys = ['key1.key2:value','key1.key3:value1']; var config = configParser.mergeConfigs(argvStub); expect(config.key1).toEqual({key2: 'value',key3: 'value1'}); expect(config.confKeys).toEqual(['key1.key2:value','key1.key3:value1']); }); it('Should parse several simple object notations in confkey string', function () { var argvStub = new ArgvStub(); argvStub.confKeys = 'key1.key2:value;key1.key3:value1'; var config = configParser.mergeConfigs(argvStub); expect(config.key1).toEqual({key2: 'value',key3: 'value1'}); expect(config.confKeys).toContain('key1.key2:value;key1.key3:value1'); }); it('Should overwrite config.browsers with --browsers', () => { var argvStub = new ArgvStub(); argvStub.browsers = 'firefox'; var parsed = cliParser.parse(argvStub) parsed.conf = __dirname + '/configParser/conf.js'; var config = configParser.mergeConfigs(parsed) expect(config.browsers).toEqual([{"browserName": "firefox"}]) }); it('Should overwrite config.browsers with --browsers when not specified', () => { var argvStub = new ArgvStub(); argvStub.browsers = 'firefox'; var parsed = cliParser.parse(argvStub) parsed.conf = __dirname + '/configParser/empty.conf.js'; var config = configParser.mergeConfigs(parsed) expect(config.browsers).toEqual([{"browserName": "firefox"}]) }); it('Should overwrite default config.browsers with --browsers and api profile', () => { var argvStub = new ArgvStub(); argvStub.browsers = 'firefox'; var parsed = cliParser.parse(argvStub) parsed.conf = __dirname + '/configParser/importing.conf.js'; var config = configParser.mergeConfigs(parsed) expect(config.browsers).toEqual([{"browserName": "firefox"}]) }); });
javascript
18
0.666024
88
34.907692
130
starcoderdata
package org.clever.devops.utils; import com.sun.jna.Platform; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * 项目编译打包工具类 * * 作者: lzw * 创建时间:2017-12-14 10:46 */ public class CodeCompileUtils { /** * 使用 mvn 命令编译打包项目 * * @param consoleOutput 控制台回调 * @param projectPath 项目路径 * @param args mvn 参数 * @return 编译成功返回true */ public static boolean mvn(ConsoleOutput consoleOutput, String projectPath, String[] args) { File file = new File(projectPath); // projectPath 不是文件夹或不存在 if (!file.exists() || !file.isDirectory()) { throw new BusinessException(String.format("路径[%1$s]不是文件夹或不存在", projectPath)); } if (args == null || args.length <= 0) { throw new BusinessException("需要执行的Maven命令不能为空"); } // 组织需要执行的命令 List commands = new ArrayList<>(); if (Platform.isWindows()) { // Windows 下先进入对应的盘符下 commands.add(String.format("%1$s:", FilenameUtils.getPrefix(projectPath).split(":")[0])); } commands.add(String.format("cd %1$s", projectPath)); StringBuilder sb = new StringBuilder(); sb.append("mvn "); for (String arg : args) { if (StringUtils.isNotBlank(arg)) { sb.append(StringUtils.trim(arg)).append(" "); } } commands.add(sb.toString()); // 增加退出命令 commands.add("exit"); // 增加回车字符 commands = commands.stream().map(cmd -> { cmd = StringUtils.trim(cmd); if (!cmd.endsWith("\r") || !cmd.endsWith("\r\n")) { cmd = cmd + "\r"; } return cmd; }).collect(Collectors.toList()); // 执行命令 Terminal terminal = ExecShellUtils.newTerminal(consoleOutput, commands); terminal.onTerminalResize(350, 150); return terminal.waitFor() == 0; } }
java
19
0.579361
101
30.318841
69
starcoderdata
<div class="col-md-12" style="margin-top:50px;"> <div class="card"> <div class="card-body"> <h4 class="card-title">Tabel Pembayaran <h6 class="card-subtitle">Add for borders on all sides of the table and cells. <div class="table-responsive"> <table class="table table-bordered"> <th scope="col">No <th scope="col">Nama Modul <th scope="col">Qty <th scope="col">Sub Total <th scope="col">Action <tbody id="tabel-pesanan"> <a href="#" data-toggle="modal" onclick="simpan_list_db()" class="btn btn-success col-md-2" style="float:right; margin-bottom:10px; margin-right:20px;">Bayar <div id="msg" class="col-md-12"> <!-- Modal --> <div class="modal fade bd-example-modal-lg" id="pembayaran" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Pembayaran <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times; <div class="modal-body"> telah membeli modul di tempat kami melanjutkan pembelian, silahkan transfer sejumlah Rp. <span id="totalnya"> ke rekening berikut : sudah melakukan transfer, silahkan upload bukti transfer anda dibawah ini : <form id="uploadBukti" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="">Metode Pembayaran <select name="metode" id="" class="form-control"> <option value="none">Silahkan Pilih Metode <option value="BRI">BRI: 29948200328 a/n Wahyu Bagus Wicaksono <option value="BNI">BNI: 12922100328 a/n Wahyu Bagus Wicaksono <div class="form-group"> <label for="">Upload Bukti Disini <input type="file" name="bukti" class="form-control"> <input type="hidden" name="id_nota" id="id_nota"> <input type="submit" name="submit" value="Kirim" class="btn btn-success" style="float:left;margin-right:10px"> <!-- <img src="<?= base_url() ?>asset/loading.gif" id="loading" alt=""> --> <span id="msg"> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close function loadCart() { $("#tabel-pesanan").html(''); $.getJSON("<?= base_url() ?>Transaksi/ViewAllPesanan", function(data) { let no = 0; $.each(data['data_cart'], function(key, dt) { no++; $("#tabel-pesanan").append( ' + '<th scope="row">' + no + ' + ' + dt['name'] + ' + ' + dt['qty'] + ' + ' + dt['subtotal'] + ' + ' href="#" onclick="if(confirm(\'Apakah Yakin?\')){hapus_cart(\'' + dt['rowid'] + '\')}"><i class="material-icons">delete + ' ); }); $("#tabel-pesanan").append( ' + '<td colspan="3">Total Keseluruhan + data['total_seluruh'] + ' href="#" onclick="if(confirm(\'Apakah anda yakin menghapus data ini ? \')){ hapus_all()}"><i class="material-icons">delete + '> ); }); } loadCart(); function simpan_list_db() { $.getJSON("<?= base_url() ?>Transaksi/createPembayaran", function(data) { if (data['status'] == 1) { $("#msg").html('Anda sukses menyimpan ke nota'); $("#msg").show('animate'); $("#msg").addClass("alert alert-success"); setTimeout(() => { $("#msg").hide('animate'); $("#msg").removeClass("alert alert-success"); setTimeout(() => { $("#totalnya").html(data['total']); $("#pembayaran").modal("show"); $("#id_nota").val(data['id_nota']); loadTotalCart(); loadCart(); }, 500); }, 3000); } }); } $("#uploadBukti").submit(function(e) { e.preventDefault(); let url = "<?= base_url() ?>Transaksi/uploadBuktiTransfer"; let formData = new FormData($("#uploadBukti")[0]); $.ajax({ url: url, type: "post", data: formData, contentType: false, processData: false, dataType: "json", beforeSend: function() { $("#loading").css("display", "block"); }, success: function(data) { if (data['status'] == 1) { $("#loading").css("display", "none"); $("#msg").html("Bukti telah terupload"); $("#msg").show("fade"); $("#msg").addClass("alert alert-success"); setTimeout(() => { $("#msg").hide("fade"); setTimeout(() => { $("#pembayaran").modal("hide"); $("#msg").removeClass("alert alert-success"); location.href="DashboardUser/modulPage"; }, 500); }, 2000); } else { $("#loading").css("display", "none"); $("#msg").html("Bukti gagal terupload"); $("#msg").show("fade"); $("#msg").addClass("alert alert-danger"); setTimeout(() => { $("#msg").hide("fade"); setTimeout(() => { $("#pembayaran").modal("hide"); $("#msg").removeClass("alert alert-danger"); }, 500); }, 2000); } } }); });
php
4
0.571637
226
33.503145
159
starcoderdata
var express = require('express'); var app = express(); var micro = require('../../index'); var Client = require('../../index').Client; var service; micro.init({ host: '192.168.99.100', port: 32768 }); service = new Client('service'); app.get('/', function (req, res) { service .request('getDate', { param: new Date() }) .timeout(1000) .send() .on('succeeded', function (result) { res.end(result); }); }); app.get('/error', function (req, res) { service .request('failed') .send() .on('succeeded', function (result) { res.end(result); }) .on('failed', function (result) { res.end(result); }); }); app.get('/fire', function (req, res) { service .request('error') .fireAndForget() .send(); res.end(); }); app.get('/cb', function (req, res) { service .request('getDate', { param: new Date() }, function (err, result) { res.end(result); }) .send(); }); app.listen(3000);
javascript
15
0.57674
72
19.568627
51
starcoderdata
using AnaliseOperante.source.dominio; using AnaliseOperante.source.helpers; using AnaliseOperante.source.services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AnaliseOperante.source.view { public partial class ExperimentoCrud : Form { private readonly Experimento experimento; public ExperimentoCrud(long idExperimento = 0) { InitializeComponent(); CarregarListaLinhaDeBase(); CarregarListaCondicao(); if (idExperimento == 0) { experimento = new Experimento(); Text = "Criando novo Experimento"; return; } else { experimento = ExperimentoService.GetById(idExperimento); } Text = "Editando Experimento: " + experimento.Nome; textNome.Text = experimento.Nome; textLinhaDeBase.Text = experimento.LinhaDeBase?.Nome; textInstrucao.Text = experimento.Instrucao; experimento.Condicoes.ForEach(it => AdicionaCondicaoEscolhida(it)); } private void CarregarListaLinhaDeBase() { List linhasDeBase = LinhaDeBaseService.GetAll(); listViewLinhaDeBase.Items.Clear(); listViewLinhaDeBase.Items.AddRange(linhasDeBase.Select(it => { var item = new ListViewItem(it.Nome); item.SubItems.Add(it.Id.ToString()); return item; }).Cast } private void CarregarListaCondicao() { List condicoes = CondicaoService.GetAll(); listViewCondicao.Items.Clear(); listViewCondicao.Items.AddRange(condicoes.Select(it => { var item = new ListViewItem(it.Nome); item.SubItems.Add(it.Id.ToString()); return item; }).Cast } private void AdicionaCondicaoEscolhida(Condicao condicao) { var item = new ListViewItem(condicao.Nome); item.SubItems.Add(condicao.Id.ToString()); listViewCondicoesSelecionadas.Items.Add(item); } private void btnSelecionarLinhaDeBase_Click(object sender, EventArgs e) { if (listViewLinhaDeBase.SelectedItems.Count == 0) { MessageBox.Show("Nenhuma Linha De Base selecionada!", "Advertência"); return; } experimento.LinhaDeBase = LinhaDeBaseService.GetById(ViewHelper.GetIdSelecionadoInListView(listViewLinhaDeBase)); textLinhaDeBase.Text = experimento.LinhaDeBase.Nome; } private void btnRemoverLinhaDeBase_Click(object sender, EventArgs e) { if (experimento.LinhaDeBase == null) { MessageBox.Show("Esse experimento não possui Linha De Base!", "Advertência"); return; } experimento.LinhaDeBase = null; textLinhaDeBase.Text = string.Empty; } private void btnAdicionarCondicao_Click(object sender, EventArgs e) { if (listViewCondicao.SelectedItems.Count == 0) { MessageBox.Show("Nenhuma Condição selecionada!", "Advertência"); return; } Condicao condicao = CondicaoService.GetById(ViewHelper.GetIdSelecionadoInListView(listViewCondicao)); experimento.Condicoes.Add(condicao); AdicionaCondicaoEscolhida(condicao); } private void btnRemoverCondicao_Click(object sender, EventArgs e) { if (listViewCondicoesSelecionadas.SelectedItems.Count == 0) { MessageBox.Show("Nenhuma Condição selecionada!", "Advertência"); return; } experimento.Condicoes.Remove(experimento.Condicoes.Find(it => it.Id == ViewHelper.GetIdSelecionadoInListView(listViewCondicoesSelecionadas))); listViewCondicao.Items.Clear(); experimento.Condicoes.ForEach(it => AdicionaCondicaoEscolhida(it)); } private void btnSalvarExperimento_Click(object sender, EventArgs e) { experimento.Nome = textNome.Text; experimento.Instrucao = textInstrucao.Text; ExperimentoService.Salvar(experimento); MessageBox.Show("Experimento salvo com sucesso!", "Sucesso"); Close(); } } }
c#
28
0.746028
145
31.260504
119
starcoderdata
void CPageDisplay::createXpdfDisplayParams (boost::shared_ptr<GfxResources>& res, boost::shared_ptr<GfxState>& state) { // // Init Gfx resources // // Get resource dictionary CPageAttributes::InheritedAttributes atr; CPageAttributes::fillInherited (_page->getDictionary(),atr); // Start the resource stack boost::shared_ptr<CPdf> pdf = _page->getDictionary()->getPdf().lock(); XRef* xref = (pdf)?pdf->getCXref():NULL; assert (xref); Object* obj = atr._resources->_makeXpdfObject (); assert (obj); assert (objDict == obj->getType()); res = boost::shared_ptr<GfxResources> (new GfxResources(xref, obj->getDict(), NULL)); xpdf::freeXpdfObject (obj); // // Init Gfx state // // Create Media (Bounding) box boost::shared_ptr<PDFRectangle> rc (new PDFRectangle (_params.pageRect.xleft, _params.pageRect.yleft, _params.pageRect.xright, _params.pageRect.yright)); state = boost::shared_ptr<GfxState> (new GfxState (_params.hDpi, _params.vDpi, rc.get(), _params.rotate, _params.upsideDown)); }
c++
11
0.68906
112
32.645161
31
inline
/* * Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved. This * code is released under a tri EPL/GPL/LGPL license. You can use it, * redistribute it and/or modify it under the terms of the: * * Eclipse Public License version 1.0 * GNU General Public License version 2 * GNU Lesser General Public License version 2.1 */ package org.jruby.truffle.nodes.core; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.source.SourceSection; import org.jruby.truffle.nodes.objectstorage.ReadHeadObjectFieldNode; import org.jruby.truffle.runtime.NotProvided; import org.jruby.truffle.runtime.RubyCallStack; import org.jruby.truffle.runtime.RubyContext; import org.jruby.truffle.runtime.backtrace.Backtrace; import org.jruby.truffle.runtime.core.RubyBasicObject; import org.jruby.truffle.runtime.core.RubyException; @CoreClass(name = "Exception") public abstract class ExceptionNodes { @CoreMethod(names = "initialize", optional = 1) public abstract static class InitializeNode extends CoreMethodArrayArgumentsNode { public InitializeNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } @Specialization public RubyBasicObject initialize(RubyException exception, NotProvided message) { exception.initialize(nil()); return exception; } @Specialization(guards = "wasProvided(message)") public RubyBasicObject initialize(RubyException exception, Object message) { exception.initialize(message); return exception; } } @CoreMethod(names = "backtrace") public abstract static class BacktraceNode extends CoreMethodArrayArgumentsNode { @Child ReadHeadObjectFieldNode readCustomBacktrace; public BacktraceNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); readCustomBacktrace = new ReadHeadObjectFieldNode("@custom_backtrace"); } @Specialization public Object backtrace(RubyException exception) { if (readCustomBacktrace.isSet(exception)) { return readCustomBacktrace.execute(exception); } else if (exception.getBacktrace() != null) { return exception.asRubyStringArray(); } else { return nil(); } } } @RubiniusOnly @CoreMethod(names = "capture_backtrace!", optional = 1) public abstract static class CaptureBacktraceNode extends CoreMethodArrayArgumentsNode { public CaptureBacktraceNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } @Specialization public RubyBasicObject captureBacktrace(RubyException exception, NotProvided offset) { return captureBacktrace(exception, 1); } @Specialization public RubyBasicObject captureBacktrace(RubyException exception, int offset) { Backtrace backtrace = RubyCallStack.getBacktrace(this, offset); exception.setBacktrace(backtrace); return nil(); } } @CoreMethod(names = "message") public abstract static class MessageNode extends CoreMethodArrayArgumentsNode { public MessageNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } @Specialization public Object message(RubyException exception) { return exception.getMessage(); } } }
java
13
0.690562
94
33.409524
105
starcoderdata
$(document).ready( setTimeout(function(){ $('.content-form').css("opacity", "1"); }, 100) ) //Email $('#email').on('focus', function(){ $('.lbl-email').css("margin-top", "-20px"); $('.lbl-email').css("font-size", "14px"); }) $('#email').on('focusout', function(){ if($('#email').val().length < 1){ $('.lbl-email').css("margin-top", "10px"); $('.lbl-email').css("font-size", "20px"); }else{ $('.lbl-email').css("margin-top", "-20px"); $('.lbl-email').css("font-size", "14px"); } }) //Contraseña $('#clave').on('focus', function(){ $('.lbl-clave').css("margin-top", "20px"); $('.lbl-clave').css("font-size", "14px"); }) $('#clave').on('focusout', function(){ if($('#clave').val().length < 1){ $('.lbl-clave').css("margin-top", "50px"); $('.lbl-clave').css("font-size", "20px"); }else{ $('.lbl-clave').css("margin-top", "20px"); $('.lbl-clave').css("font-size", "14px"); } })
javascript
15
0.464286
51
21.042553
47
starcoderdata
#define EDCB_VERSION_TAG "tkntrec-211119" // Only ASCII characters can be used here. #ifndef EDCB_VERSION_TEXT #if defined(EDCB_VERSION_TAG) && defined(EDCB_VERSION_EXTRA) #define EDCB_VERSION_TEXT " " EDCB_VERSION_TAG " " EDCB_VERSION_EXTRA #elif defined(EDCB_VERSION_TAG) #define EDCB_VERSION_TEXT " " EDCB_VERSION_TAG #elif defined(EDCB_VERSION_EXTRA) #define EDCB_VERSION_TEXT " " EDCB_VERSION_EXTRA #endif #endif #ifndef EDCB_RC_DIALOG_FONT #if defined(EDCB_RC_DIALOG_FONT_YUGOTHIC) #define EDCB_RC_DIALOG_FONT "Yu Gothic UI" #elif defined(EDCB_RC_DIALOG_FONT_MEIRYO) #define EDCB_RC_DIALOG_FONT "Meiryo UI" #endif #endif
c
6
0.732719
69
29
21
starcoderdata
<?php /** * Trait MathAndTrigonometry-A * * @link https://www.icy2003.com/ * @author icy2003 * @copyright Copyright (c) 2017, icy2003 */ namespace icy2003\php\icomponents\excel\mathAndTrigonometry; use icy2003\php\ihelpers\Strings; /** * MathAndTrigonometry-A */ trait AMAT { /** * 返回数字的绝对值 * * - y = |x|, x ∈ (-∞, +∞) * * @param double $number 必需。 需要计算其绝对值的实数 * * @return double */ public static function abs($number) { return abs($number); } /** * 返回数字的反余弦值 * * - y = arccos(x), x ∈ [-1, 1] * * @param double $number 必需。 所求角度的余弦值,必须介于 -1 到 1 之间 * * @return double */ public static function acos($number) { return acos($number); } /** * 返回数字的反双曲余弦值 * * - y = arcosh(x) = ln(x + √(x^2 -1)), x ∈ [1, +∞) * * @param double $number 必需。 大于或等于 1 的任意实数 * * @return double */ public static function acosh($number) { return acosh($number); } /** * 返回数字的反余切值的主值 * * - y = arccot(x), x ∈ (-∞, +∞) * * @param double $number 必需。 Number 为所需角度的余切值。 此值必须是实数 * * @return double */ public static function acot($number) { return pi() / 2 - atan($number); } /** * 返回数字的反双曲余切值 * * - y = arccoth(x) = arctanh(1 / x), {x| x > 1 或 x < -1} * * @param double $number 必需。 Number 的绝对值必须大于 1 * * @return double */ public static function acoth($number) { return atanh(1 / $number); } /** * 将罗马数字转换为阿拉伯数字 * * @param string $string 必需。 用引号引起的字符串、空字符串 ("") 或对包含文本的单元格的引用 * * @return integer */ public static function arabic($string) { $roman = array( 'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1, ); $strlen = Strings::length($string); $values = []; for ($i = 0; $i < $strlen; $i++) { if (isset($roman[strtoupper($string[$i])])) { $values[] = $roman[strtoupper($string[$i])]; } } $sum = 0; while ($current = current($values)) { $next = next($values); $next > $current ? $sum += $next - $current + 0 * next($values) : $sum += $current; } return $sum; } /** * 返回数字的反正弦值 * * - y = arcsin(x), x ∈ [-1, 1] * * @param double $number 必需。 所求角度的正弦值,必须介于 -1 到 1 之间 * * @return double */ public static function asin($number) { return asin($number); } /** * 返回数字的反双曲正弦值 * * - y = arsinh(x) = ln(x + √(x^2 + 1)), x ∈ (-∞, +∞) * * @param double $number 必需。 任意实数 * * @return double */ public static function asinh($number) { return asinh($number); } /** * 返回数字的反正切值 * * - y = arctan(x), x ∈(-π/2, π/2) * * @param double $number 必需。 所求角度的正切值 * * @return double */ public static function atan($number) { return atan($number); } /** * 返回给定的 X 轴及 Y 轴坐标值的反正切值 * * @param double $x 必需。 点的 x 坐标 * @param double $y 必需。 点的 y 坐标 * * @return double */ public static function atan2($x, $y) { $sign = 1; if ($y < 0) { $sign = -1; } if ($x < 0) { return $sign * (pi() - self::abs(self::atan($y / $x))); } elseif ($x == 0) { return pi() / 2 * $sign; } else { return $sign * self::abs(self::atan($y / $x)); } } /** * 返回数字的反双曲正切值 * * - y = artanh(x), x ∈(-1, 1) = 1/2 * ln((1 + x) / (1 - x)) * * @param double $number 必需。 -1 到 1 之间的任意实数 * * @return double */ public static function atanh($number) { return atanh($number); } }
php
19
0.438601
95
19.256281
199
starcoderdata
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.nexus.downloader.main.resources; import org.apache.commons.lang3.StringUtils; import spark.Request; public final class QueryParameterHelper { private QueryParameterHelper() { // hide utility class constructor } public static int getCount(Request req) { return getInt(req, "count", 0, Integer.MAX_VALUE, 10); } public static int getInt(Request request, String name, int minValue, int maxValue, int defaultValue) { String value = request.queryParams(name); if (StringUtils.isBlank(value)) { return defaultValue; } try { int actualValue = Integer.parseInt(value); if (actualValue < minValue || actualValue > maxValue) { throw BadRequestException.invalidValue(name, actualValue, minValue, maxValue); } return actualValue; } catch (NumberFormatException e) { throw BadRequestException.invalidInteger(name, value); } } public static int getStart(Request req) { return getInt(req, "start", 0, Integer.MAX_VALUE, 0); } }
java
15
0.681946
132
36.890909
55
starcoderdata
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) # based largely on https://djangosnippets.org/snippets/261 from django.contrib.gis.db import models class Topic(models.Model): name = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.name # A simple feedback form with four fields. class Feedback(models.Model): title = models.CharField(max_length=80, default='GeoK Feedback') name = models.CharField(max_length=50) email = models.EmailField() topic = models.ForeignKey(Topic) message = models.TextField() def __unicode__(self): return self.title
python
9
0.718788
104
28.464286
28
starcoderdata
private void Awake() { // Get the mutation handler script. _mutationHandlerScript = GameObject.FindGameObjectWithTag("MutationHandler").GetComponent<MutationHandler>(); // Get the images. _elephant = transform.GetChild(0).GetComponent<Image>(); _fish = transform.GetChild(1).GetComponent<Image>(); _hawk = transform.GetChild(2).GetComponent<Image>(); _rhino = transform.GetChild(3).GetComponent<Image>(); _turtle = transform.GetChild(4).GetComponent<Image>(); // Get the transformation script. _transformationScript = GameObject.FindGameObjectWithTag("Player").transform.GetChild(0) .GetComponent<Transformation>(); }
c#
15
0.65034
117
45
16
inline
<?php /** * @author oba.ou */ /* @var $this yii\web\View */ /* @var $form yii\widgets\ActiveForm */ /* @var $generator yii\gii\generators\form\Generator */ echo $form->field($generator, 'tableName')->hiddenInput()->label(false)->error(false)->hint(false); $field = $form->field($generator,'tableNameHelper'); $field->parts['{input}'] = \kartik\select2\Select2::widget([ 'model' => $generator, 'attribute' => 'tableNameHelper', 'data' => $generator->tableNameData, 'options' => [ 'placeholder' => '选择数据库', ], 'pluginOptions' => [ 'allowClear' => true ], 'pluginEvents' => [ "change" =>'function(){ $("#generator-modelclass").val(this.value); var val = this.options[this.selectedIndex].text; $("#generator-tablename").val(val); }', ] ]); echo $field; echo $form->field($generator, 'modelClass'); echo $form->field($generator, 'ns'); echo $form->field($generator, 'baseClass'); echo $form->field($generator, 'db'); echo $form->field($generator, 'useTablePrefix')->checkbox(); echo $form->field($generator, 'generateRelations')->checkbox(); echo $form->field($generator, 'generateLabelsFromComments')->checkbox(); echo $form->field($generator, 'generateQuery')->checkbox(); echo $form->field($generator, 'queryNs'); echo $form->field($generator, 'queryClass'); echo $form->field($generator, 'queryBaseClass'); echo $form->field($generator, 'enableI18N')->checkbox(); echo $form->field($generator, 'messageCategory');
php
11
0.632199
99
30.183673
49
starcoderdata
def _fetch_nametable(self): """ Fetch nametable byte. This state, just like other fetch/store states, can be used both to read tiles 2 through 33 of the current line and to fetch tiles 0 and 1 for the next line. """ # Render the pixel if self._cycle_x <= 256: self._render_pixel() self._cycle_x += 1 self._state = self.STORE_NAMETABLE
python
8
0.567757
78
29.642857
14
inline
#pragma once #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif // !_USE_MATH_DEFINES #include "mkl.h" #include std::vector solve_linear_system(std::vector A, std::vector b);
c
8
0.734317
99
29.222222
9
starcoderdata
/* * Copyright (c) 2020-2021 * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * */ /** * @file * This file defines a run loop aware base object for managing a * connection bewteen two IP-based peers. * */ #ifndef OPENHLXCOMMONCONNECTIONBASIS_HPP #define OPENHLXCOMMONCONNECTIONBASIS_HPP #include #include #include namespace HLX { namespace Common { /** * @brief * A run loop aware base object for managing a connection bewteen * two IP-based peers. * * @ingroup common * */ class ConnectionBasis { public: virtual ~ConnectionBasis(void); Status Init(const RunLoopParameters &aRunLoopParameters); CFStringRef GetScheme(void) const; const HostURLAddress & GetPeerAddress(void) const; RunLoopParameters &GetRunLoopParameters(void); Status SetPeerAddress(const HostURLAddress &aPeerAddress); protected: ConnectionBasis(CFStringRef aSchemeRef); private: CFStringRef mSchemeRef; RunLoopParameters mRunLoopParameters; HostURLAddress mPeerAddress; }; }; // namespace Common }; // namespace HLX #endif // OPENHLXCOMMONCONNECTIONBASIS_HPP
c++
13
0.701299
70
23
77
starcoderdata