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
'use strict'; const parse = require('../lib/parse'); const expect = require('chai').expect; describe('parse test', () => { it('should return empty object', () => { const args = []; const result = parse(args); expect(result).to.be.a('object'); expect(result).to.be.empty; }); it('should return string value', () => { const args = ['test=string']; const result = parse(args); expect(result).to.deep.equal({test: 'string'}); }); it('should return array value', () => { const args = ['test=[array1, array2]']; const result = parse(args); expect(result).to.deep.equal({test: ['array1', 'array2']}); expect(result.test).to.have.lengthOf(2); }); it('should return array value(different writing)', () => { const args = ['test[]=array1']; const result = parse(args); expect(result).to.deep.equal({test: ['array1']}); expect(result.test).to.have.lengthOf(1); }); context('when creating nested object', () => { it('should return string value', () => { const args = ['test[key]=string']; const result = parse(args); expect(result).to.deep.equal({ test: { key: 'string' } }); }); it('should return array value', () => { const args = ['test[key]=[array1, array2]']; const result = parse(args); expect(result).to.deep.equal({ test: { key: ['array1', 'array2'] } }); }); }); context('when multiple arguments', () => { it('should return concated object', () => { const args = ['key1=hoge', 'key2=fuga']; const result = parse(args); expect(result).to.deep.equal({ key1: 'hoge', key2: 'fuga' }); }); it('should return concated object and then it has parent key', () => { const args = ['key[test]=hoge', 'key[test2]=fuga']; const result = parse(args); expect(result).to.deep.equal({ key: { test: 'hoge', test2: 'fuga' } }); }); }); });
javascript
25
0.530732
74
22.837209
86
starcoderdata
def hostStringBuilder(host: str) -> str: """ Generate a string representation of a host based on host status """ if utils.checkIfHostActive(host): return f" ► {utils.bcolors.OKGREEN}{host} is UP {utils.bcolors.ENDC}✅" else: return f" ► {utils.bcolors.FAIL}{host} is DOWN {utils.bcolors.ENDC}⛔"
python
11
0.638806
81
41
8
inline
@org.junit.Test public void main() { int d=1; Number test; Class<? extends Number> integerClass=Integer.class; // ArrayList dd = new ArrayList<>(); // Object hh = dd; // dd.add(test); // Collection<?> as= (Collection<?>) hh; test=1; // show(integerClass.cast(test)); show(d); }
java
7
0.616162
53
20.285714
14
inline
<div class="width_max1300px"> <?php include_once("application/views/page_dynamic/post/include_post_header.php"); $page=(int)$data['page']; if($page<1) { $page=1; } echo "<div class='page_title'><i class='fa fa-heart-o'> Bài viết được yêu thích $total=$this->db->query("SELECT id FROM post_content WHERE m_status='public' LIMIT 0,100")->num_rows(); if($total<1) { echo "<div class='stt_tip'>Không có bài viết nào được hiển thị tại đây ! } else { $phantrang=page_seperator($total,$page,24,Array('class_name'=>'page_seperator_item','strlink'=>"bai-viet-yeu-thich/trang-[[pagenumber]].html")); $list=$this->db->query("SELECT id FROM post_content WHERE (m_status='public') ORDER BY m_like DESC,id DESC LIMIT ".$phantrang['start'].",".$phantrang['limit'])->result(); if($list==false||$list==null||count($list)<1) { echo "<div class='stt_tip'>Không có bài viết nào được hiển thị tại đây } else { echo "<div class='width3 width3_0_12 width3_980_9'>"; foreach($list as $item) { $post_row=$this->PostContentModel->get_row($item->id); echo "<div class='width_40 padding'>".$this->PostContentModel->get_str_item_like($post_row)." } echo "<div class='clear_both'> echo "<div class='page_seperator_box'>".$phantrang['str_link']." echo " echo "<div class='width3 width3_0_12 width3_980_3'>"; include_once("application/views/page_dynamic/post/include_post_adver.php"); echo " echo "<div class='clear_both'> } } ?>
php
16
0.562336
178
43.232558
43
starcoderdata
package org.nzbhydra.mapping; import org.junit.Test; import java.text.ParseException; import java.util.Arrays; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class SemanticVersionTest { @Test public void testEquality() throws ParseException { SemanticVersion v1 = new SemanticVersion("1.2.3-alpha.1+build.2"); SemanticVersion v2 = new SemanticVersion("1.2.3-alpha.1+build.2"); assertEquals(v1, v2); } @Test(expected = IllegalArgumentException.class) public void testOutOfBounds() { new SemanticVersion(-1, 0, 0); } @Test public void testParsePlain() throws ParseException { SemanticVersion v = new SemanticVersion("1.2.3"); assertEquals(1, v.major); assertEquals(2, v.minor); assertEquals(3, v.patch); assertEquals("1.2.3", v.toString()); v = new SemanticVersion("11.22.33"); assertEquals(11, v.major); assertEquals(22, v.minor); assertEquals(33, v.patch); assertEquals("11.22.33", v.toString()); v = new SemanticVersion("11.22.33-SNAPSHOT"); assertEquals(11, v.major); assertEquals(22, v.minor); assertEquals(33, v.patch); assertEquals("SNAPSHOT", v.qualifier); assertEquals("11.22.33-SNAPSHOT", v.toString()); } @Test public void testNewer() { SemanticVersion[] inorder = { new SemanticVersion(0, 1, 4), new SemanticVersion(1, 1, 1), new SemanticVersion(1, 2, 1), new SemanticVersion(1, 2, 3) }; SemanticVersion[] wrongorder = { inorder[0], inorder[3], inorder[1], inorder[2] }; Arrays.sort(wrongorder); assertArrayEquals(inorder, wrongorder); } @Test public void testUpdate() { assertTrue(new SemanticVersion(1, 1, 1).isUpdateFor(new SemanticVersion(1, 1, 0))); assertFalse(new SemanticVersion(1, 1, 1).isUpdateFor(new SemanticVersion(1, 1, 2))); assertFalse(new SemanticVersion(1, 1, 1).isUpdateFor(new SemanticVersion(1, 1, 1))); assertTrue(new SemanticVersion(1, 0, 0).isUpdateFor(new SemanticVersion(1, 0, 0, "SNAPSHOT"))); assertTrue(new SemanticVersion(1, 0, 0).isUpdateFor(new SemanticVersion(1, 0, 0, "beta"))); assertFalse(new SemanticVersion(1, 0, 0, "SNAPSHOT").isUpdateFor(new SemanticVersion(1, 0, 0, "SNAPSHOT"))); assertFalse(new SemanticVersion(1, 0, 0, "SNAPSHOT").isUpdateFor(new SemanticVersion(1, 0, 0))); assertTrue(new SemanticVersion(1, 0, 0, "SNAPSHOT").isSameOrNewer(new SemanticVersion(1, 0, 0, "SNAPSHOT"))); assertTrue(new SemanticVersion(1, 1, 2).isCompatibleUpdateFor(new SemanticVersion(1, 1, 1))); assertFalse(new SemanticVersion(2, 1, 1).isCompatibleUpdateFor(new SemanticVersion(1, 1, 0))); } }
java
13
0.648802
117
35.204819
83
starcoderdata
<?php namespace App\Component\NewsParser\Services; use App\Component\NewsParser\Models\NewsModel; use Illuminate\Support\Collection; abstract class AbstractService { protected Collection $config; public function __construct(Collection $config) { $this->config = $config; } /** * @param string $theme * @return NewsModel[] */ abstract public function parsing(string $theme) :array; }
php
9
0.677346
59
17.208333
24
starcoderdata
#pragma once #include "../debug.h" extern const char* ANOMDET_SAMPLES_FILE; extern const char* ANOMDET_SAMPLES2_FILE; extern const char* REDWINE_SAMPLES_FILE; extern const char* KMEANS_FILE; extern const char* SAMPLES_FILE; extern const char* WEIGHTS_FILE; extern const char* REDWINE_CSV_FILE; extern const char* ADULT_FILE; extern const char* YEAR_PRED_FILE; extern const char* NN_DIM_RESULTS_FILE; extern std::thread::id main_thread_id; template <typename T> struct Test { int testNo = 0; virtual int operator()(int argc, const char **argv) const { outln("base test"); return 0; } virtual ~Test() {} }; // io template <typename T> struct testParseOctave : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testDim3Octave : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testPrint : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testLogRegCostFunctionNoRegMapFeature : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testLinRegCostFunctionNoReg : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testLinRegCostFunction : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCostFunction : public Test { int operator()(int argc, const char **argv)const; }; // math template <typename T> struct testCubes : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNextPowerOf2 : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testLargestFactor : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCountSpanrows : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMod : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSign : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testBisection : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMatRowMath : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAutodot : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMultLoop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSqrMatsMultSmall : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSqrMatsMult : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testProductKernel3 : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testProductShapes : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testProductShapesTxB : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testProductShapesKernelPtr : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testProductShapesLoop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testLargeMatProds : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testHugeMatProds : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testHugeMatProds2 : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testHugeMatProds3 : public Test { int operator()(int argc, const char **argv)const;}; // fill template <typename T> struct testFillVsLoadRnd: public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testFillNsb : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testFillers : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testFillXvsY : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testXRFill : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testTinyXRFill : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMemsetFill: public Test { int operator()(int argc, const char **argv)const;}; // form template <typename T> struct testTiler : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testDTiler : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAnonMatrices : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testTranspose : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testTransposeNneqP : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testTransposeLoop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testTransposeHuge : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCat : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testBinCat : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testReshape : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSubmatrices : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSubmatrices2 : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testDropFirstAlts : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAttFreqsSmall : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAttFreqsMed : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAttFreqsLarge : public Test { int operator()(int argc, const char **argv)const;}; //template <typename T> struct testAttFreqs : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSigmoidNneqP : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct intestOps : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testBinaryOps : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSumSqrDiffsLoop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNormalize : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural2l : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural2lCsv : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural2lAdult : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural2lYrPred : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural2lYrPredMulti : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural2Loop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeural3l : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testLUdecomp : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testFileIO : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMaxColIdxs : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAccuracy : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testEqualsEtc : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSuite : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCheckNNGradients : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testOps : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNeuralMnistHw : public Test { int operator()(int argc, const char **argv)const;}; // mem template <typename T> struct testCudaMemcpy : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCudaMemcpyVsCopyKernelVsmMemcpy : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCopyKernels : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCudaMemcpyArray : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCudaMemcpy2D : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testMemUsage : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testRowCopy : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCopyVsCopyK : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testClippedRowSubset : public Test { int operator()(int argc, const char **argv) const;}; template <typename T> struct testLastError : public Test { int operator()(int argc, const char **argv) const; }; template <typename T> struct testMemcpyShared: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testInc: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testHfreeDalloc: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testMemset: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testPackedMat: public Test { int operator()(int argc, const char **argv)const; }; // reduction template <typename T> struct testStrmOrNot: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCount : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testColumnAndRowSum : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testBounds : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testRedux : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testColumnRedux : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testReduceRows : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCuSet1D : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCuSet : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testDedeup : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testJaccard : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testQpow : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMergeSorted : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testOrderedCountedSet : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testShuffle : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testShufflet : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testSumLoop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testNneqP : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAnP : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMeansFile : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testFeatureMeans : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMeansLoop : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testAnomDet : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMVAnomDet : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testKmeans : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMeansPitch : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testEtoX : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testRedWineScSv : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testCsv : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testRandSequence : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testRandomizingCopyRows : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testRandAsFnOfSize : public Test { int operator()(int argc, const char **argv)const;}; template <typename T> struct testMontePi: public Test { int operator()(int argc, const char **argv)const;}; // multi gpu template <typename T> struct testMultiGPUMemcpy : public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testMultiGPUMath: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testMultiGPUTiling: public Test { int operator()(int argc, const char **argv)const; }; // multi thread / omp template <typename T> struct testCMap: public Test { int operator()(int argc, const char **argv)const; }; // opengl #ifdef CuMatrix_Enable_Ogl template <typename T> struct testOglHelloworld: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testOglAnim0: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testOglPointAnim: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testFrag7Csv: public Test { int operator()(int argc, const char **argv)const;}; #endif // CuMatrix_Enable_Ogl // ftors template <typename T> struct testFastInvSqrt: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCopyFtor: public Test { int operator()(int argc, const char **argv)const; }; // recurnels template <typename T> struct testStrassen: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testRecCuMatAddition: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCdpSum: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCdpSync1: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testCdpRedux: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct testPermus: public Test { int operator()(int argc, const char **argv)const; }; // umem // amortization template <typename T> struct testBinaryOpAmort: public Test { int operator()(int argc, const char **argv)const; }; template <typename T> struct tests { static list argsl; static int runTest(int argc, const char** argv); static T timeTest( const Test test, int argv, const char** args, int* theResult ); };
c
10
0.727533
138
75.64574
223
starcoderdata
/* | Copyright 2017 Esri | | 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. */ define({ "searchSourceSetting": { "title": "Pengaturan Pencarian dan Buffer", "mainHint": "Anda dapat mengaktifkan pencarian teks alamat dan fitur, digitalisasi geometri, dan buffering." }, "addressSourceSetting": { "title": "Layer Alamat", "mainHint": "Anda dapat menetapkan layer label penerima mana yang tersedia." }, "notificationSetting": { "title": "Opsi Notifikasi", "mainHint": "Anda dapat menetapkan tipe notifikasi mana yang tersedia." }, "groupingLabels": { "addressSources": "Layer yang akan digunakan untuk memilih layer penerima", "averyStickersDetails": " "csvDetails": "File nilai terpisah koma (CSV)", "drawingTools": "Alat gambar untuk menetapkan area", "featureLayerDetails": "Feature layer", "geocoderDetails": "Geocoder", "labelFormats": "Format label yang tersedia", "printingOptions": "Opsi untuk halaman label cetak", "searchSources": "Cari sumber", "stickerFormatDetails": "Parameter halaman label" }, "hints": { "alignmentAids": "Tanda ditambahkan ke halaman label untuk membantu Anda menyejajarkan halaman dengan printer Anda", "csvNameList": "Daftar terpisah koma nama kolom sensitif terhadap huruf besar atau kecil", "horizontalGap": "Spasi antara dua label dalam satu baris", "insetToLabel": "Spasi antara sisi label dan awal teks", "labelFormatDescription": "Bagaimana gaya label disajikan dalam daftar opsi format widget", "labelFormatDescriptionHint": "Tooltip untuk menambah deskripsi dalam daftar opsi format", "labelHeight": "Tinggi setiap label di halaman", "labelWidth": "Lebar setiap label di halaman", "localSearchRadius": "Menentukan radius dari area di sekitar pusat peta saat ini yang digunakan untuk mendorong peringkat calon geocoding sehingga calon yang terdekat dengan lokasi akan dimunculkan terlebih dahulu", "rasterResolution": "Sekitar 100 piksel per inci cocok dengan resolusi layar. Semakin tinggi resolusi, semakin banyak memori browser diperlukan. Setiap browser memiliki perbedaan kemampuan untuk menangani permintaan memori besar dengan baik.", "selectionListOfOptionsToDisplay": "Item yang dicentang ditampilkan sebagai opsi di widget; Ubah urutan sesuai keinginan", "verticalGap": "Spasi antara dua label dalam satu kolom" }, "propertyLabels": { "bufferDefaultDistance": "Jarak buffer default", "bufferUnits": "Unit buffer yang akan disediakan di widget", "countryRegionCodes": "Kode negara atau wilayah", "description": "Deskripsi", "descriptionHint": "Petunjuk deskripsi", "displayField": "Kolom tampilan", "drawingToolsFreehandPolygon": "poligon bebas", "drawingToolsLine": "garis", "drawingToolsPoint": "titik", "drawingToolsPolygon": "poligon", "drawingToolsPolyline": "polyline", "enableLocalSearch": "Aktifkan pencarian lokal", "exactMatch": "Benar-benar cocok", "fontSizeAlignmentNote": "Ukuran font untuk catatan tentang margin cetak", "gridDarkness": "Kegelapan kisi", "gridlineLeftInset": "Sisipan garis kisi kiri", "gridlineMajorTickMarksGap": "Tanda centang besar setiap", "gridlineMinorTickMarksGap": "Tanda centang kecil setiap", "gridlineRightInset": "Sisipan garis kisi kanan", "labelBorderDarkness": "Kegelapan batas label", "labelBottomEdge": "Tepi bawah label di halaman", "labelFontSize": "Ukuran font", "labelHeight": "Tinggi label", "labelHorizontalGap": "Celah horizontal", "labelInitialInset": "Sisipan untuk teks label", "labelLeftEdge": "Tepi kiri label di halaman", "labelMaxLineCount": "Jumlah maksimum garis di label", "labelPageHeight": "Tinggi halaman", "labelPageWidth": "Lebar halaman", "labelRightEdge": "Tepi kanan label di halaman", "labelsInAColumn": "Jumlah label dalam satu kolom", "labelsInARow": "Jumlah label dalam satu baris", "labelTopEdge": "Tepi atas label di halaman", "labelVerticalGap": "Celah vertikal", "labelWidth": "Lebar label", "limitSearchToMapExtent": "Cari hanya dalam jangkauan peta saat ini", "maximumResults": "Hasil maksimum", "maximumSuggestions": "Saran maksimum", "minimumScale": "Skala minimum", "name": "Nama", "percentBlack": "% hitam", "pixels": "piksel", "pixelsPerInch": "piksel per inci", "placeholderText": "Teks placeholder", "placeholderTextForAllSources": "Teks placeholder untuk mencari semua sumber", "radius": "Radius", "rasterResolution": "Resolusi raster", "searchFields": "Kolom pencarian", "showAlignmentAids": "Tampilkan alat bantu penyejajaran di halaman", "showGridTickMarks": "Tampilkan tanda centang kisi", "showLabelOutlines": "Tampilkan garis kerangka label", "showPopupForFoundItem": "Tampilkan pop-up untuk fitur atau lokasi yang ditemukan", "tool": "Alat", "units": "Unit", "url": "URL", "urlToGeometryService": "URL ke layanan geometri", "useRelatedRecords": "Gunakan catatan terkaitnya", "useSecondarySearchLayer": "Gunakan layer pemilihan sekunder", "useSelectionDrawTools": "Gunakan alat gambar pilihan", "useVectorFonts": "Gunakan font vektor (hanya font Latin)", "zoomScale": "Skala zoom" }, "buttons": { "addAddressSource": "Tambahkan layer berisi label alamat di popup-nya", "addLabelFormat": "Tambah format label", "addSearchSource": "Tambah sumber pencarian", "set": "Atur" }, "placeholders": { "averyExample": "mis., label Avery(r) ${averyPartNumber}", "countryRegionCodes": "mis., USA,CHN", "descriptionCSV": "Nilai terpisah koma", "descriptionPDF": "Label PDF ${heightLabelIn} x ${widthLabelIn} inci; ${labelsPerPage} per halaman" }, "tooltips": { "getWebmapFeatureLayer": "Dapatkan feature layer dari webmap", "openCountryCodes": "Klik untuk mendapatkan informasi selengkapnya mengenai kode", "openFieldSelector": "Klik untuk membuka pemilih kolom", "setAndValidateURL": "Atur dan validasi URL" }, "problems": { "noAddresseeLayers": "Harap sebutkan paling sedikit satu layer penerima", "noBufferUnitsForDrawingTools": "Harap konfigurasikan paling sedikit satu unit buffer untuk alat gambar", "noBufferUnitsForSearchSource": "Harap konfigurasikan paling sedikit satu unit buffer untuk sumber pencarian \"${sourceName}\"", "noGeometryServiceURL": "Harap konfigurasikan URL ke layanan geometri", "noNotificationLabelFormats": "Harap sebutkan paling sedikit satu format label notifikasi", "noSearchSourceFields": "Harap konfigurasikan satu kolom pencarian atau lebih untuk sumber pencarian \"${sourceName}\"", "noSearchSourceURL": "Harap konfigurasikan URL untuk sumber pencarian \"${sourceName}\"" } });
javascript
8
0.721185
247
49.636986
146
starcoderdata
public override string GetValueRepresentation(object parameter) { try { var type = parameter.GetType(); var getCacheKeyMethod = this.GetType().GetMethod(nameof(GetCacheKeyValueRepresentation), BindingFlags.NonPublic | BindingFlags.Instance); var typedGetCacheKeyMethod = getCacheKeyMethod.MakeGenericMethod(type); var cacheKey = (string)typedGetCacheKeyMethod.Invoke(this, new[] { parameter }); return cacheKey; } catch (TargetInvocationException ex) { // unwrap the reflection exception and re-throw the inner exception throw ex.InnerException; } }
c#
16
0.593875
153
40.777778
18
inline
import React from 'react'; import Grid from 'material-ui/Grid'; import ServiceURL from '../components/serviceURL'; import Problem from '../components/problemViews/JupyterProblem'; import Notebook from './notebook'; class Example extends React.Component { constructor() { super(); this.state = { problemFetched: false, ProblemFile: {}, solution: {}, }; this._getProblem = this._getProblem.bind(this); this._getStaticProblem = this._getStaticProblem.bind(this); this._getId = this._getId.bind(this); this._problemSolveUpdate = this._problemSolveUpdate.bind(this); } componentDidMount() { // this._getProblem(); } _getId(url) { const len = url.length; const str = url.lastIndexOf('/'); return url.substring(str + 1, len); } _problemSolveUpdate(one, two, url) { const id = this._getId(url); // Get File this._getStaticProblem(id); } _problemSolutionSubmitRequest() { alert('_problemSolutionSubmitRequest'); } _problemSolveSuccess() { alert('_problemSolveSuccess'); } /** * Example function to get notebook's executed JSON data of given problem */ _getProblem(json) { fetch(json.problemUrl) .then(response => response.json()) .then(data => { this.setState({ ProblemFile: { problemJSON: data }, problemFetched: true }); }); } _getStaticProblem = id => { window.gapi.load('client:auth2', () => { // 2. Initialize the JavaScript client library. window.gapi.client .init({ apiKey: ' // clientId and scope are optional if auth is not required. clientId: '765594031611-aitdj645mls974mu5oo7h7m27bh50prc.apps.' + 'googleusercontent.com', discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'], }) .then(resolve => { // 3. Initialize and make the API request. window.gapi.client.drive.files .get({ fileId: id, alt: 'media', }) .then( res => this.setState({ solution: { json: JSON.parse(res.body) } }), reason => console.log('error', reason), ); // window.gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); // console.log('resolve', resolve) // fetch('https://www.googleapis.com/drive/v3/files/1fu4vKrbwz4b4QzvHJzKo4CAPefIMGmd?alt=media') // .then(data => console.log('------', data)) }); }); }; render() { const { problemFetched, ProblemFile } = this.state; return ( <ServiceURL onPastingUrl={this._getProblem} /> {/* {this.state.problems && ( )} */} <Grid container justify="center"> <Grid item xs={10}> {problemFetched && ( <Problem problemSolveUpdate={this._problemSolveUpdate} problemSolutionSubmitRequest={this._problemSolutionSubmitRequest} problemSolveSuccess={this._problemSolveSuccess} dispatch={() => {}} onChange={() => {}} problem={ProblemFile} solution={this.state.solution} /> )} ); } } export default Example;
javascript
25
0.576796
106
31.909091
110
starcoderdata
async fn set_check_bad() { let (state, _) = state_setup().await; let cid: CidJson = from_str(r#"{"/":"bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4"}"#) .unwrap(); match sync_check_bad(Data(state.clone()), Params((cid.clone(),))).await { Ok(reason) => assert_eq!(reason, ""), Err(e) => std::panic::panic_any(e), } // Mark that block as bad manually and check again to verify assert!(sync_mark_bad(Data(state.clone()), Params((cid.clone(),))) .await .is_ok()); match sync_check_bad(Data(state), Params((cid,))).await { Ok(reason) => assert_eq!(reason, "Marked bad manually through RPC API"), Err(e) => std::panic::panic_any(e), } }
rust
13
0.534884
97
39.9
20
inline
#ifndef RESOURCECOMPONENT_H #define RESOURCECOMPONENT_H #include #include class ResourceComponent : public GameComponent { private: public: ResourceComponent (RESOURCE_TYPE resType) : GameComponent("ResourceComponent") { this->resType = resType; } RESOURCE_TYPE resType; int gatherSlots[4] = {-1, -1, -1, -1}; int maxGatherers = 4; int flashNum = 0; int flashTimer = 30; bool flashOn = false; }; #endif
c
10
0.71875
81
17.708333
24
starcoderdata
package com.turing.readers; import com.turing.model.Params; import org.json.simple.parser.ParseException; import java.io.IOException; public interface Reader { Params read(String path) throws IOException, ParseException; }
java
6
0.795652
64
22
10
starcoderdata
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Province; use App\Country; use App\Http\Requests\ProvinceRequest; use Session; class ProvinceController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $provinces = Province::orderBy('id','DESC')->get(); return view('adminlte::layouts.province.index',compact('provinces')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $countries = Country::orderBy('id','DESC')->get(); //dd($countries); return view('adminlte::layouts.province.create',compact('countries')); } public function listall() { $provinces = Province::orderBy('id','DESC')->get(); return view('adminlte::layouts.province.list-provinces', compact('provinces')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(ProvinceRequest $request) { $provincia = new Province; $provincia->province = $request->province; $provincia->postal = $request->postal; $provincia->id_country = $request->id_country; $provincia->save(); Session::flash('success', $request->province.' Registrado correctamente'); return redirect('admin/provinces'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $province = Province::find($id); return view('adminlte::layouts.province.show',compact('province'));// } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { //$countries = Country::orderBy('id','DESC')->get(); $countries = Country::orderBy('id','DESC')->get(); $province = Province::FindOrFail($id); return view('adminlte::layouts.province.edit', array('province'=>$province,'countries'=>$countries)); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { /*$province = Province::find($id); $province->province = $request->province; $province->postal = $request->postal; $province->id_country = $request->id_country; $province->update(); */ $prov = Province::findOrFail($id); // $prov->update($request->all()); return redirect()->route('provinces.index') ->with('success',$request->province.' Provincia actualizada'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $province = Province::find($id); $province->delete(); return back()->with('warning','Provincia '.$province->province.' eliminada'); } }
php
13
0.595904
109
27.418033
122
starcoderdata
import numpy as np from tqdm import tqdm, trange import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from itertools import islice as take device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') def train_epoch(dataloader, model, opt): # por cada lote for x, y_true in dataloader: # Los pasamos a la GPU, en caso de que haya x, y_true = x.to(device), y_true.to(device) # computamos logits y_lgts = model(x) # computamos la pérdida loss = F.cross_entropy(y_lgts, y_true) # vaciamos los gradientes opt.zero_grad() # retropropagamos loss.backward() # actualizamos parámetros opt.step() def eval_epoch(dl, model, num_batches=None): # evitamos que se registren las operaciones # en la gráfica de cómputo with torch.no_grad(): # historiales losses, accs = [], [] # validación de la época con num_batches # si num_batches==None, se usan todos los lotes for x, y_true in take(dl, num_batches): # Los pasamos a la GPU, en caso de que haya x, y_true = x.to(device), y_true.to(device) # computamos los logits y_lgts = model(x) # computamos los puntajes y_prob = F.softmax(y_lgts, 1) # computamos la clases y_pred = torch.argmax(y_prob, 1) # computamos la pérdida loss = F.cross_entropy(y_lgts, y_true) # computamos la exactitud acc = (y_true == y_pred).type(torch.float32).mean() # guardamos históricos losses.append(loss.item()) accs.append(acc.item()) # promediamos loss = np.mean(losses) * 100 acc = np.mean(accs) * 100 return loss, acc def train(model, trn_dl, tst_dl, lr=1e-3, epochs=20, trn_batches=None, tst_batches=None): # historiales loss_hist, acc_hist = [], [] # optimizador opt = optim.Adam(model.parameters(), lr=lr) # ciclo de entrenamiento for epoch in trange(epochs): # entrenamos la época train_epoch(trn_dl, model, opt) # evaluamos la época en entrenamiento trn_loss, trn_acc = eval_epoch(trn_dl, model, trn_batches) # evaluamos la época en prueba tst_loss, tst_acc = eval_epoch(tst_dl, model, tst_batches) # guardamos historial loss_hist.append([trn_loss, tst_loss]) acc_hist.append([trn_acc, tst_acc]) # imprimimos progreso print(f'E{epoch:02} ' f'loss=[{trn_loss:6.2f},{tst_loss:6.2f}] ' f'acc=[{trn_acc:5.2f},{tst_acc:5.2f}]') return loss_hist, acc_hist
python
15
0.578984
89
26.380952
105
starcoderdata
package com.example.liangzi.logcollectanduploadservice.model; /** * Created by GXL on 17-7-7. */ public class JankDataBean { public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public String getProduct() { return Product; } public void setProduct(String product) { this.Product = product; } public String getVersion() { return Version; } public void setVersion(String version) { this.Version = version; } public String getIMEI() { return IMEI; } public void setIMEI(String IMEI) { this.IMEI = IMEI; } public String getUSERNAME() { return USERNAME; } public void setUSERNAME(String USERNAME) { this.USERNAME = USERNAME; } public String getTESTTYPE() { return TESTTYPE; } public void setTESTTYPE(String TESTTYPE) { this.TESTTYPE = TESTTYPE; } public String getCASENAME() { return CASENAME; } public void setCASENAME(String CASENAME) { this.CASENAME = CASENAME; } public String getAPPNAME() { return APPNAME; } public void setAPPNAME(String APPNAME) { this.APPNAME = APPNAME; } public int getLog() { return log; } public void setLog(int log) { this.log = log; } public String getConclusion() { return Conclusion; } public void setConclusion(String conclusion) { this.Conclusion = conclusion; } public String getRemark() { return Remark; } public void setRemark(String remark) { this.Remark = remark; } public String getSeverity() { return Severity; } public void setSeverity(String severity) { this.Severity = severity; } public String getUploadTIME() { return UploadTIME; } public void setUploadTIME(String uploadTIME) { this.UploadTIME = uploadTIME; } /** * ID : 1 * Product : MYA-AL10 * Version : Maya-AL10C00B022 * IMEI : 0123456789ABCDEF * USERNAME : FOT样机 * TESTTYPE : 开发调试 * CASENAME : CONTACTS_CONTACT_LAUNCH * APPNAME : * log : 1 * Conclusion : null * Remark : * Severity : General * UploadTIME : 2017/6/8 16:22:35 */ public int ID; public String Product; public String Version; public String IMEI; public String USERNAME; public String TESTTYPE; public String CASENAME; public String APPNAME; public int log; public String Conclusion; public String Remark; public String Severity; public String UploadTIME; // public LogDataBean[] getLogDataBeanArray() { // return LogDataBeanArray; // } // // public void setLogDataBeanArray(LogDataBean[] logDataBeanArray) { // LogDataBeanArray = logDataBeanArray; // } // // public LogDataBean[] LogDataBeanArray; public JankDataBean() { } }
java
8
0.59269
71
17.077381
168
starcoderdata
public void testSetupHandicapAsMoves() throws GtpError { createSynchronizer(); expect("list_commands", ""); m_gtp.querySupportedCommands(); assertExpectQueueEmpty(); expect("boardsize 19", ""); expect("clear_board", ""); synchronize(); assertExpectQueueEmpty(); PointList black = new PointList(); black.add(GoPoint.get(3, 4)); black.add(GoPoint.get(4, 4)); setupHandicap(black); expect("play B D5", ""); expect("play B E5", ""); synchronize(); assertExpectQueueEmpty(); // Playing a move should not trigger a re-transmission play(WHITE, 5, 5); expect("play W F6", ""); synchronize(); assertExpectQueueEmpty(); }
java
8
0.556818
62
26.344828
29
inline
#include #include #include #include #include /* * Reads from stdin one byte at a time until it reaches EOF * fd === file descriptor * buf === buffer to store the read contents * size === size of the buffer * chunckSize === bytes read with each read() call * If chunckSize is equal to 0 then contents of fd will be consumed in one read() */ int readfd (int fd, char *buf, size_t size, int chunckSize) { if (!chunckSize) chunckSize = size; size--; int i; int rd=1; for (i = 0; rd && i < size; i+=rd) rd = read (fd, buf+i, chunckSize); buf[i+1] = 0; return i; } void _usage (char *proc) { printf ("Usage : %s <chunck size> <(optional) files>", proc); } int _getChunck (char *s) { int temp = atoi(s); if (temp == 0 && !(s[0] == '0' && !s[1])) temp = -1; return temp; } int main (int argc, char **argv){ size_t bufSize = 1024 * 1024 * 20; char *buf = malloc (bufSize * sizeof(char)); int chunckSize; int read; if (argc < 2){ _usage(argv[0]); return 1; } if ((chunckSize = _getChunck (argv[1])) < 0) return 2; if ( argc == 2){ while ((read = readfd (STDOUT_FILENO, buf, bufSize, chunckSize))) write (STDOUT_FILENO, buf, read); return 0; } for (int i=2; i < argc; i++){ int fd = open (argv[i], O_RDONLY); while ((read = readfd (fd, buf, bufSize, chunckSize))) write (STDOUT_FILENO, buf, read); close (fd); } free (buf); return 0; }
c
11
0.548507
81
23.363636
66
starcoderdata
<?php $__env->startSection('title', '| view cmodules'); ?> <?php $__env->startSection('content'); ?> <div class="row"> <div class="col-md-8"> echo e($cmodule->name); ?> <p class="lead"><?php echo e($cmodule->about); ?> <p class="lead"><?php echo e($cmodule->status); ?> <p class="lead"><?php echo e($cmodule->course_id); ?> <p class="lead"><?php echo e($cmodule->order); ?> <a href="<?php echo e(route('cmodules.index')); ?>">All Cmodules <div class="col-md-4"> <div class="well"> <div class="dl-horizontal"> At: echo e(date('M j, Y h:ia',strtotime($cmodule->created_at))); ?> <div class="dl-horizontal"> At: echo e(date('M j, Y h:ia', strtotime($cmodule->updated_at))); ?> <div class="row"> <div class="col-sm-6"> <a href="<?php echo e(route('cmodules.edit', $cmodule->id)); ?>" class="btn btn btn-primary btn-block">Edit <div class="col-sm-6"> <?php echo Form::open(['route' => ['cmodules.destroy', $cmodule->id], 'method' => 'DELETE']); ?> <input type="submit" class="btn btn-success btn-danger btn-block" value="Delete"> <?php echo Form::close(); ?> <?php $__env->stopSection(); ?> <?php echo $__env->make('main', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
php
13
0.517566
117
29.294118
51
starcoderdata
import qexpy as q import numpy as np import pandas as pd import re def first_sqn(x): if x != 0: return -int(np.floor(np.log10(abs(x)))) else: return 0 first_sgn = np.vectorize(first_sqn) def unit_to_latex(string, plt=None): if plt is None: text_style = 'text' else: text_style = 'mathrm' out = re.sub(r"([a-zA-Z]+)", r'\\'+text_style+r'{\1}', string) out = re.sub(r"\\\\"+text_style + r"{([^}]*)}", r'\ \1', out).replace(' ', '') return out
python
15
0.493716
66
17.206897
29
starcoderdata
def go(): """Do the full data reduction. @author Jessica Lu @author Sylvana Yelda """ #################### # # Calibration files: # everything created under calib/ # #################### # Darks - created in subdir darks/ # Files n0001 - n0009 # - darks needed to make bad pixel mask # - store the resulting dark in the file name that indicates the # integration time (2.8s) and the coadds (10ca). # -- If you use the OSIRIS image, you must include the full filename in the list. darkFiles = list(range(1, 9+1)) calib.makedark(darkFiles, 'dark_2.8s_10ca.fits', instrument=nirc2) # Flats - created in subdir flats/ # Files n0037,n0039,n0041,n0043,n0045: lamps off for flats at K # Files n0038,n0040,n0042,n0044,n0046: lamps on for flats at K offFiles = [37, 39, 41, 43, 45] onFiles = [38, 40, 42, 44, 46] calib.makeflat(onFiles, offFiles, 'flat_kp.fits', instrument=nirc2) # Masks (assumes files were created under calib/darks/ and calib/flats/) calib.makemask('dark_2.8s_10ca.fits', 'flat_kp.fits', 'supermask.fits', instrument=nirc2) #################### # # Galactic Center # #################### ########## # K-band reduction ########## util.mkdir('kp') os.chdir('kp') # Nite 1: # SCI frames (don't forget to add 1 at end): 108-237 # reference star position in first image: [407.77, 673.87] # use a different Strehl star at position: [521.79, 398.92] # Sky frames (don't forget to add 1 at end): 252-261 # # -- If you have more than one position angle, make sure to # clean them seperatly. # -- Strehl and Ref src should be the pixel coordinates of a bright # (but non saturated) source in the first exposure of sci_files. # -- If you use the OSIRIS image, you must include the full filename in the list. sci_files1 = list(range(108, 237+1)) refSrc1 = [407.77, 673.87] strSrc1 = [521.79, 398.92] sky_files1 = list(range(252, 261+1)) # sky.makesky(sky_files1, 'nite1', 'kp', instrument=nirc2) data.clean(sci_files1, 'nite1', 'kp', refSrc1, strSrc1, instrument=nirc2) # Nite 2: # SCI frames (don't forget to add 1 at end): 1108-1237 # reference star position in first image: [407.77, 673.87] # use a different Strehl star at position: [521.79, 398.92] # Sky frames (don't forget to add 1 at end): 1252-1261 and 1400-1405 # -- If you use the OSIRIS image, you must include the full filename in the list. sci_files2 = list(range(1108, 1237+1)) refSrc2 = [407.77, 673.87] strSrc2 = [521.79, 398.92] sky_files2 = list(range(1252, 1261+1)) + list(range(1400, 1405+1)) # sky.makesky(sky_files2, 'nite2', 'kp', instrument=nirc2) data.clean(sci_files2, 'nite2', 'kp', refSrc2, strSrc2, instrument=nirc2) # Combine: # Combine all of them together (from both nights). # Do frame selection (trim=1). # Weight by Strehl (weight='strehl'). # Make 3 submaps. # -- If you use the OSIRIS image, you must include the full filename in the list. sci_files = sci_files1 + sci_files2 data.calcStrehl(sci_files, 'kp', instrument=nirc2) data.combine(sci_files, 'kp', '06junlgs', trim=1, weight='strehl', submaps=3, instrument=nirc2) os.chdir('../') ############ # Lp ############ util.mkdir('lp') os.chdir('lp') # Nite 1 sky_files = list(range(38, 53+1)) sci_files = list(range(87, 94+1)) + list(range(115,122+1)) refSrc = [695., 543.] strSrc = [680., 839.] sky.makesky_lp(sky_files, 'nite1', 'lp') data.clean(sci_files, 'nite1', 'lp', refSrc, strSrc) data.calcStrehl(sci_files, 'lp') data.combine(sci_files, 'lp', '06junlgs', trim=0, weight=None, submaps=3) os.chdir('../') # # Could do other wavelengths or different fields (e.g. Arches). # Can pass in a field flag, for example: # data.clean(arch_files,'nite1','kp',refSrc,strSrc, # field='f1') # data.combine(arch_files,'kp','06maylgs1',trim=1,weight='strehl' # field='f1',submaps=3) #
python
11
0.582909
89
34.113821
123
inline
int main(int argc, char *argv[]) { hg_time_t t1, t2, diff1, diff2; hg_time_t sleep_time = {1, 0}; double epsilon = 1e-9; double t1_double, t2_double; unsigned int t1_ms = 12345, t2_ms; int ret = EXIT_SUCCESS; (void) argc; (void) argv; printf("Current time: %s\n", hg_time_stamp()); hg_time_get_current(&t1); hg_time_sleep(sleep_time); hg_time_get_current(&t2); /* Should have slept at least sleep_time */ if (!hg_time_less(t1, t2)) { fprintf(stderr, "Error: t1 > t2\n"); ret = EXIT_FAILURE; goto done; } t1_double = hg_time_to_double(t1); t2_double = hg_time_to_double(t2); if (t1_double > t2_double) { fprintf(stderr, "Error: t1 > t2\n"); ret = EXIT_FAILURE; goto done; } t1 = hg_time_from_double(t1_double); t2 = hg_time_from_double(t2_double); if (!hg_time_less(t1, t2)) { fprintf(stderr, "Error: t1 > t2\n"); ret = EXIT_FAILURE; goto done; } /* t2 - (t1 + sleep_time) */ diff1 = hg_time_subtract(t2, hg_time_add(t1, sleep_time)); /* (t2 - t1) - sleep_time */ diff2 = hg_time_subtract(hg_time_subtract(t2, t1), sleep_time); /* Should be equal */ if (fabs(hg_time_to_double(diff1) - hg_time_to_double(diff2)) > epsilon) { fprintf(stderr, "Error: diff1 != diff2\n"); ret = EXIT_FAILURE; goto done; } /* Should be equal */ t2_ms = hg_time_to_ms(hg_time_from_ms(t1_ms)); if (t2_ms != t1_ms) { fprintf(stderr, "Error: t1_ms (%u) != t2_ms (%u)\n", t1_ms, t2_ms); ret = EXIT_FAILURE; goto done; } done: return ret; }
c
11
0.540332
78
23.449275
69
inline
func NewGame() *Game { g := &Game{ E: newEntities(), // Oh man, this is such a bad hack. NextNetworkId: uint64(rand.Int63()), // NewClientUpdate: NewNetworkUpdate(), timeDead: 100, NetworkIds: make(map[uint64]*Lookup), } return g }
go
14
0.644
41
18.307692
13
inline
int BucketQuery::Compare( const lltime_t &timeStart, const lltime_t &timeEnd, uint64_t nReferenceIndex, search_type_t type, bool forceSingle ) { int nCompare = 0; reference_t reference; LOG_DEBUG( m_nLogId, "Compare( timeStart:%s, timeEnd:%s, nReferenceIndex:%lu, searchType:%d )", (timeStart.str("%F %H:%M:%S")).c_str(), (timeEnd.str("%F %H:%M:%S")).c_str(), nReferenceIndex, type ); // Force a single reference search. Disables caching search_type_t rrType = type; if ( forceSingle ) { rrType = ST_EQUAL; } if( ReadReference(nReferenceIndex, &reference, rrType) ) { //if(!VerifyReferenceTimes(reference)) // If the reference has bogus times, the best thing to do is return 0 which means that // it is "in the middle". // return 0; // Given the VerifyReferenceTimes call check above, and the assumption that the starttime and // endtime follow the assumptions with repect to m_bucketTimeOut, it is best to use only end time // logic since the end time is 100% sorted on disk. //uint64_t nReferenceTime = (type == ST_LESS_OR_EQUAL) ? (((uint64_t)reference.nEndTime) - ((uint64_t)m_bucketTimeOut)) : ((uint64_t)reference.nEndTime); uint64_t nReferenceTime = (type == ST_LESS_OR_EQUAL) ? ((uint64_t)reference.nStartTime) : ((uint64_t)reference.nEndTime); LOG_DEBUG( m_nLogId, " Compare(): nReferenceTime:%s", (lltime_t(nReferenceTime).str("%F %H:%M:%S")).c_str() ); if( (uint64_t)timeEnd < nReferenceTime ) { nCompare = -1; LOG_DEBUG( m_nLogId, " Compare(): timeEnd:%s < nReferenceTime:%s", (timeEnd.str("%F %H:%M:%S")).c_str(), (lltime_t(nReferenceTime).str("%F %H:%M:%S")).c_str() ); } else if( (uint64_t)timeStart > nReferenceTime ) { nCompare = 1; LOG_DEBUG( m_nLogId, " Compare(): timeStart:%s > nReferenceTime:%s", (timeStart.str("%F %H:%M:%S")).c_str(), (lltime_t(nReferenceTime).str("%F %H:%M:%S")).c_str() ); } else // reference.time between timeStart & timeEnd { nCompare = 0; LOG_DEBUG( m_nLogId, " Compare(): timeStart:%s <= nReferenceTime:%s <= timeEnd:%s", (timeStart.str("%F %H:%M:%S")).c_str(), (lltime_t(nReferenceTime).str("%F %H:%M:%S")).c_str(), (timeEnd.str("%F %H:%M:%S")).c_str() ); } } else { LOG_ERROR( m_nLogId, "Compare(): ReadReference failed at nReferenceIndex = %llu", nReferenceIndex); } LOG_DEBUG( m_nLogId, " Compare(): returning:%d", nCompare ); return( nCompare ); }
c++
20
0.581906
232
48.716981
53
inline
package jpuppeteer.cdp.client.constant.network; /** * Stages of the interception to begin intercepting. Request will intercept before the request is sent. Response will intercept after the response is received. */ public enum InterceptionStage implements jpuppeteer.cdp.client.CDPEnum { REQUEST("Request"), HEADERSRECEIVED("HeadersReceived"), ; private String value; InterceptionStage(String value) { this.value = value; } @Override public String value() { return value; } public static InterceptionStage findByValue(String value) { for(InterceptionStage val : values()) { if (val.value.equals(value)) return val; } return null; } }
java
12
0.682353
158
24.533333
30
starcoderdata
// simpleQueries v1.0 module.exports = sq = { click: (id, callback) => { // Função vai pegar o elemento HTML pela ID e vai adidionar um EventListener // Já vai incluir o preventDefault // E executar a função de callback recebida return document.getElementById(id).addEventListener('click', (event) => { event.preventDefault() callback() }) }, addClass: (id, classesNameArray) => { // Função vai pegar o elemento HTML e adicionar uma ou mais de uma classe na lista de classes function exec() { for(count = 0; count < classesNameArray.length; count++){ document.getElementById(id).classList.add(classesNameArray[count]) } } return exec() }, removeClass: (id, classesNameArray) => { // Função vai pegar o elemento HTL e remover uma classe da lista de classes function exec() { for(count = 0; count < classesNameArray.length; count++){ document.getElementById(id).classList.remove(classesNameArray[count]) } } return exec() }, contains: (id, className, callback) => { // Função vai verificar se o elemento HTML tem determinada classe (parametro) // na lista de classes, se tiver vai executar a função de callback if (callback == undefined) { return document.getElementById(id).classList.contains(className) } if (document.getElementById(id).classList.contains(className)) { callback() } }, value: (id, newValue) => { // Função vai retornar o valor de um elemento html // E caso o newValue seja utilizado, o elemento html vai receber o novo valor if (newValue != null){ return document.getElementById(id).value = newValue } return document.getElementById(id).value } }
javascript
18
0.590447
101
30.253968
63
starcoderdata
void Game(Mode M) { srand(time(0)); PMode( M ) ; CleanScreen() ; GameBoard gb ; Block Cur, Next, Hold ; Cur.GainBlock(), Next.GainBlock(); LoadToBuffer( gb , Cur ) ; int score = 0, line = 0, combo = 0 ; int timecounter = 0; bool next, changable = true ; ShowForm() ; do{ ShowNextBlock( Next ) ; ShowHoldBlock( Hold ) ; ShowScore( score, line, combo ) ; Showpect( gb ); ShowBoard( gb ) ; timecounter = clock() ; next = false ; do{ int interact = GetKeyboardInput() ; /* User input */ if( interact == Down || (clock()-timecounter)*1000 >= std::max( level_time - line*4 , max_level_time )*CLOCKS_PER_SEC ) { timecounter = clock() ; /* reset time for next count */ next = !MoveDown( gb ) ; if( next ) Delay(100) ; ShowBoard( gb ) ; } if( interact == Pause ) { GoToXY( Pause_X , Pause_Y ) ; ColorText( " ---- || PAUSE ---- " , Red ) ; while( !GetKeyboardInput() ) ; } if( interact == Left ) MoveLeft( gb ) ; if( interact == Right ) MoveRight( gb ) ; if( interact == Space ){ AllDown( gb ) ; next = true ; } if( interact == Up ) Rotate( gb ) ; if( interact == C && changable ) { RemShape(gb) ; if( Hold.GetType() == None ){ /* Fisrt Hold */ Hold = Cur ; next = true ; } else{ std::swap( Hold, Cur ) ; changable = false ; LoadToBuffer( gb, Cur ) ; } break; } if( interact != 0 ){ // Refresh Showpect( gb ); ShowBoard( gb ) ; } }while(!next); if( next ) { EraseLine( gb, score, line, combo ) ; Cur = Next , Next.GainBlock() ; changable = true ; LoadToBuffer( gb, Cur ) ; } }while (!GameOver(gb)) ; }
c++
16
0.396522
131
25.147727
88
inline
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; use App\Models\Pet; class CommuniqueTest extends TestCase { /** * A basic feature test example. * * @return void */ public function testCreateCommunique() { $pet = factory(Pet::class)->create(); $data = ['name' => ' 'phone' => '1111111111']; $response = $this->postJson("/api/communiques/{$pet->id}", $data); $response->assertStatus(201); } }
php
13
0.62807
74
21.8
25
starcoderdata
package net.mgsx.game.examples.td.actions; import com.badlogic.ashley.core.Engine; /** * Action with map interaction (click on map action) * @author mgsx * */ public abstract class AbstractTileAction extends Action { public AbstractTileAction(Engine engine) { super(engine); } abstract public void apply(int x, int y); }
java
7
0.740642
55
19.777778
18
starcoderdata
#!/usr/bin/env python import unittest from playhouse.test_utils import test_database from peewee import * from parsemypsa.storage import objects # Data for testing test_db = SqliteDatabase(':memory:') model_list = [objects.Alert, objects.VehiculeInformation, objects.Trip] class TripTestCase(unittest.TestCase): def setUp(self): with test_database(test_db, model_list): self.trip1 = objects.Trip.create(id=1, timestamp=1462731168, duration=200, distance=10000, fuel_consumation=1, typ=0, merged=0) def test_mileage_calculation(self): with test_database(test_db, model_list): self.trip1.calculate_mileage() self.assertEqual(self.trip1.mileage, 10.0) def test_mileage_kml_calculation(self): with test_database(test_db, model_list): self.trip1.calculate_mileage_kml() self.assertEqual(self.trip1.mileage_kml, 10.0) def test_formatted_date(self): with test_database(test_db, model_list): self.assertEqual(self.trip1.return_formatted_date(), "2016-05-08 18:12:48") def test_to_string(self): with test_database(test_db, model_list): self.assertEqual(str(self.trip1), "Trip 1 started on 1462731168, lasted 200 minutes and 10000 m")
python
13
0.686228
139
35.514286
35
starcoderdata
def download_files(output_dir, limit, threads): """Download the assembly archive files""" assembly_urls = [ "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_00.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_01.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_02.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_03.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_04.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_05.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_06.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_07.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_08.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_09.7z", "https://fusion-360-gallery-dataset.s3-us-west-2.amazonaws.com/assembly/a1.0.0/a1.0.0_10.7z", ] if limit is not None: assembly_urls = assembly_urls[:limit] local_files = [] iter_data = zip( assembly_urls, itertools.repeat(output_dir), itertools.count(), ) results = ThreadPool(threads).imap(download_file, iter_data) local_files = [] for local_file in tqdm(results, total=len(assembly_urls)): local_files.append(local_file) # Serial Implementation # for index, url in enumerate(assembly_urls): # local_file = download_file((url, output_dir, index)) # local_files.append(local_file) return local_files
python
9
0.656942
101
51.914286
35
inline
namespace LoadAssembliesOnStartup.Fody.Tests { using System; using Catel.Reflection; using NUnit.Framework; [TestFixture] public partial class WeavingFacts { [Test] public void ExcludesPrivateAssemblies() { var assemblyInfo = AssemblyWeaver.Instance.GetAssembly("ExcludesPrivateAssemblies", @"<LoadAssembliesOnStartup ExcludePrivateAssemblies='true' />"); ApprovalHelper.AssertIlCode(assemblyInfo.AssemblyPath); } [Test, Explicit("Unable to resolve private assets during unit tests in .NET 5")] public void IncludesPrivateAssemblies() { var assemblyInfo = AssemblyWeaver.Instance.GetAssembly("IncludesPrivateAssemblies", @"<LoadAssembliesOnStartup ExcludePrivateAssemblies='false' />"); ApprovalHelper.AssertIlCode(assemblyInfo.AssemblyPath); } } }
c#
13
0.706244
161
35.185185
27
starcoderdata
package org.docksidestage.hangar.dbflute.whitebox.dfprop.simdto; import java.time.LocalDateTime; import java.util.HashSet; import java.util.List; import java.util.Set; import org.dbflute.cbean.result.ListResultBean; import org.dbflute.cbean.scoping.SubQuery; import org.docksidestage.hangar.dbflute.cbean.MemberLoginCB; import org.docksidestage.hangar.dbflute.cbean.PurchaseCB; import org.docksidestage.hangar.dbflute.dtomapper.MemberDtoMapper; import org.docksidestage.hangar.dbflute.exbhv.MemberBhv; import org.docksidestage.hangar.dbflute.exentity.Member; import org.docksidestage.hangar.dbflute.exentity.MemberStatus; import org.docksidestage.hangar.simpleflute.dto.MemberAddressDto; import org.docksidestage.hangar.simpleflute.dto.MemberDto; import org.docksidestage.hangar.simpleflute.dto.MemberStatusDto; import org.docksidestage.hangar.simpleflute.dto.RegionDto; import org.docksidestage.hangar.unit.UnitContainerTestCase; /** * @author jflute * @since 0.9.9.4B (2012/04/22 Sunday) */ public class WxSimpleDtoMapperDetailTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= private MemberBhv memberBhv; // =================================================================================== // Mapping to DTO // ============== public void test_mappingToDtoList_DerivedReferrer_basic() throws Exception { // ## Arrange ## MemberDtoMapper mapper = new MemberDtoMapper(); ListResultBean memberList = memberBhv.selectList(cb -> { cb.specify().derivedMemberLogin().max(new SubQuery { public void query(MemberLoginCB subCB) { subCB.specify().columnLoginDatetime(); } }, Member.PROP_latestLoginDatetime); cb.specify().derivedPurchase().countDistinct(new SubQuery { public void query(PurchaseCB subCB) { subCB.specify().columnProductId(); } }, Member.PROP_productKindCount); }); // ## Act ## List dtoList = mapper.mappingToDtoList(memberList); assertHasAnyElement(dtoList); for (MemberDto dto : dtoList) { // ## Assert ## LocalDateTime loginDatetime = dto.getLatestLoginDatetime(); Integer loginCount = dto.getLoginCount(); Integer productKindCount = dto.getProductKindCount(); if (loginDatetime != null) { markHere("loginDatetime"); } assertNull(loginCount); if (productKindCount != null) { markHere("productKindCount"); } log(dto.getMemberName(), loginDatetime, loginCount, productKindCount); assertNull(dto.getMemberStatus()); } assertMarked("loginDatetime"); assertMarked("productKindCount"); } // =================================================================================== // Mapping to Entity // ================= public void test_mappingToEntityList_DerivedReferrer_basic() throws Exception { // ## Arrange ## MemberDtoMapper mapper = new MemberDtoMapper(); List dtoList; { ListResultBean memberList = memberBhv.selectList(cb -> { cb.specify().derivedMemberLogin().max(new SubQuery { public void query(MemberLoginCB subCB) { subCB.specify().columnLoginDatetime(); } }, Member.PROP_latestLoginDatetime); cb.specify().derivedPurchase().countDistinct(new SubQuery { public void query(PurchaseCB subCB) { subCB.specify().columnProductId(); } }, Member.PROP_productKindCount); }); dtoList = mapper.mappingToDtoList(memberList); } // ## Act ## List memberList = mapper.mappingToEntityList(dtoList); assertHasAnyElement(memberList); for (Member member : memberList) { // ## Assert ## LocalDateTime loginDatetime = member.getLatestLoginDatetime(); Integer loginCount = member.getLoginCount(); Integer productKindCount = member.getProductKindCount(); if (loginDatetime != null) { markHere("loginDatetime"); } assertNull(loginCount); if (productKindCount != null) { markHere("productKindCount"); } log(member.getMemberName(), loginDatetime, loginCount, productKindCount); assertFalse(member.getMemberStatus().isPresent()); } assertMarked("loginDatetime"); assertMarked("productKindCount"); } // =================================================================================== //   Instance Cache // ============== public void test_mappingToDtoList_instanceCache_basic_Tx() throws Exception { // ## Arrange ## ListResultBean memberList = memberBhv.selectList(cb -> { cb.setupSelect_MemberStatus(); cb.setupSelect_MemberAddressAsValid(currentLocalDate()); }); memberBhv.loadMemberAddress(memberList, cb -> cb.setupSelect_Region()); { StringBuilder sb = new StringBuilder(); Set statusCodeSet = new HashSet Set statusHashSet = new HashSet for (Member member : memberList) { MemberStatus status = member.getMemberStatus().get(); sb.append(ln()).append(" ").append(member.getMemberName()); sb.append(", status=").append(status.getMemberStatusName()); sb.append("@").append(Integer.toHexString(status.instanceHash())); statusCodeSet.add(status.getMemberStatusCode()); statusHashSet.add(status.instanceHash()); } log(sb); assertEquals(statusCodeSet.size(), statusHashSet.size()); } MemberDtoMapper mapper = new MemberDtoMapper(); // ## Act ## List dtoList = mapper.mappingToDtoList(memberList); // ## Assert ## assertHasAnyElement(dtoList); StringBuilder sb = new StringBuilder(); Set statusCodeSet = new HashSet Set statusHashSet = new HashSet for (MemberDto memberDto : dtoList) { MemberStatusDto statusDto = memberDto.getMemberStatus(); MemberAddressDto validAddressDto = memberDto.getMemberAddressAsValid(); List addressList = memberDto.getMemberAddressList(); sb.append(ln()).append(" ").append(memberDto.getMemberName()); sb.append(ln()).append(" status: ").append(statusDto.getMemberStatusName()); sb.append("@").append(Integer.toHexString(statusDto.instanceHash())); statusCodeSet.add(statusDto.getMemberStatusCode()); statusHashSet.add(statusDto.instanceHash()); if (validAddressDto != null) { sb.append(ln()).append(" valid: ").append(validAddressDto.getMemberAddressId()); RegionDto regionDto = validAddressDto.getRegion(); assertNull(regionDto); sb.append(", ").append(regionDto); } for (MemberAddressDto addressDto : addressList) { sb.append(ln()).append(" list: ").append(addressDto.getMemberAddressId()); RegionDto regionDto = addressDto.getRegion(); assertNotNull(regionDto); sb.append(", ").append(regionDto).append("@").append(Integer.toHexString(regionDto.instanceHash())); } } log(sb); log(statusCodeSet); log(statusHashSet); assertEquals(statusCodeSet.size(), statusHashSet.size()); } }
java
23
0.536489
116
46.595628
183
starcoderdata
<?php namespace ApiChef\Obfuscate\Dummy; use ApiChef\Obfuscate\Obfuscatable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Obfuscatable; public $timestamps = false; }
php
6
0.759804
39
14.692308
13
starcoderdata
var Mocha = require('mocha'); var mocha = new Mocha({}); var fs = require('fs'); var passing = 0; var total = 0; mocha.addFile('../test/test.js'); mocha.run() .on('test', function(test) { total += 1; }) .on('pass', function(test) { passing += 1; }) .on('end', function() { var message = `${passing}/${total} specs passed`; console.log(message); fs.writeFile('../score.txt', message, function (err) { if (err) throw err; console.log('score.txt saved'); }); });
javascript
12
0.555556
60
20.666667
27
starcoderdata
async fn delete_extents( &self, transaction: &mut Transaction<'_>, search_key: &ExtentKey, ) -> Result<Option<ExtentKey>, Error> { let layer_set = self.extent_tree.layer_set(); let mut merger = layer_set.merger(); let allocator = self.allocator(); let mut iter = merger.seek(Bound::Included(search_key)).await?; let mut delete_extent_mutation = None; // Loop over the extents and deallocate them. while let Some(ItemRef { key: ExtentKey { object_id, attribute_id, range }, value, .. }) = iter.get() { if *object_id != search_key.object_id { break; } if let ExtentValue::Some { device_offset, .. } = value { let device_range = *device_offset..*device_offset + (range.end - range.start); allocator.deallocate(transaction, device_range).await?; delete_extent_mutation = Some(Mutation::extent( ExtentKey::new(search_key.object_id, *attribute_id, 0..range.end), ExtentValue::deleted_extent(), )); // Stop if the transaction is getting too big. At time of writing, this threshold // limits transactions to about 10,000 bytes. const TRANSACTION_MUTATION_THRESHOLD: usize = 200; if transaction.mutations.len() >= TRANSACTION_MUTATION_THRESHOLD { transaction.add(self.store_object_id, delete_extent_mutation.unwrap()); return Ok(Some(ExtentKey::search_key_from_offset( search_key.object_id, *attribute_id, range.end, ))); } } iter.advance().await?; } if let Some(m) = delete_extent_mutation { transaction.add(self.store_object_id, m); } Ok(None) }
rust
21
0.525866
98
44.272727
44
inline
package pm // #cgo LDFLAGS: -lbunsan_pm_compatibility // #include // #include import "C" import ( "time" "unsafe" ) const ( errSize = 1024 * 1024 ) type cRepository struct { repo C.bunsan_pm_repository } type cError struct { message string } func (e *cError) Error() string { return e.message } func NewRepository(config string) (Repository, error) { cConfig := C.CString(config) defer C.free(unsafe.Pointer(cConfig)) cErr := C.malloc(errSize) defer C.free(cErr) cRepo := C.bunsan_pm_repository_new(cConfig, (*C.char)(cErr), errSize) if cRepo == nil { return nil, &cError{C.GoString((*C.char)(cErr))} } return &cRepository{cRepo}, nil } func (r *cRepository) Close() error { C.bunsan_pm_repository_free(r.repo) r.repo = nil return nil } func (r *cRepository) Create(path string, strip bool) error { cPath := C.CString(path) defer C.free(unsafe.Pointer(cPath)) cErr := C.malloc(errSize) defer C.free(cErr) cRet := C.bunsan_pm_repository_create( r.repo, cPath, C.bool(strip), (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil } func (r *cRepository) CreateRecursively(rootPath string, strip bool) error { cRootPath := C.CString(rootPath) defer C.free(unsafe.Pointer(cRootPath)) cErr := C.malloc(errSize) defer C.free(unsafe.Pointer(cErr)) cRet := C.bunsan_pm_repository_create_recursively(r.repo, cRootPath, C.bool(strip), (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil } func (r *cRepository) Extract(pkg, destination string) error { cPkg := C.CString(pkg) defer C.free(unsafe.Pointer(cPkg)) cDst := C.CString(destination) defer C.free(unsafe.Pointer(cDst)) cErr := C.malloc(errSize) defer C.free(cErr) cRet := C.bunsan_pm_repository_extract( r.repo, cPkg, cDst, (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil } func (r *cRepository) Install(pkg, destination string) error { cPkg := C.CString(pkg) defer C.free(unsafe.Pointer(cPkg)) cDst := C.CString(destination) defer C.free(unsafe.Pointer(cDst)) cErr := C.malloc(errSize) defer C.free(cErr) cRet := C.bunsan_pm_repository_install(r.repo, cPkg, cDst, (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil } func (r *cRepository) ForceUpdate(pkg, destination string) error { cPkg := C.CString(pkg) defer C.free(unsafe.Pointer(cPkg)) cDst := C.CString(destination) defer C.free(unsafe.Pointer(cDst)) cErr := C.malloc(errSize) defer C.free(cErr) cRet := C.bunsan_pm_repository_force_update(r.repo, cPkg, cDst, (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil } func (r *cRepository) Update(pkg, destination string, lifetime time.Duration) error { cPkg := C.CString(pkg) defer C.free(unsafe.Pointer(cPkg)) cDst := C.CString(destination) defer C.free(unsafe.Pointer(cDst)) cErr := C.malloc(errSize) defer C.free(cErr) cRet := C.bunsan_pm_repository_update(r.repo, cPkg, cDst, C.time_t(lifetime.Seconds()+0.5 /*round non-negative*/), (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil } func (r *cRepository) NeedUpdate(pkg, destination string, lifetime time.Duration) (bool, error) { cPkg := C.CString(pkg) defer C.free(unsafe.Pointer(cPkg)) cDst := C.CString(destination) defer C.free(unsafe.Pointer(cDst)) cErr := C.malloc(errSize) defer C.free(cErr) var cNeed C._Bool cRet := C.bunsan_pm_repository_need_update(r.repo, cPkg, cDst, C.time_t(lifetime.Seconds()+0.5 /*round non-negative*/), &cNeed, (*C.char)(cErr), errSize) if cRet != 0 { return bool(cNeed), &cError{C.GoString((*C.char)(cErr))} } return bool(cNeed), nil } func (r *cRepository) CleanCache() error { cErr := C.malloc(errSize) defer C.free(unsafe.Pointer(cErr)) cRet := C.bunsan_pm_repository_clean_cache(r.repo, (*C.char)(cErr), errSize) if cRet != 0 { return &cError{C.GoString((*C.char)(cErr))} } return nil }
go
17
0.684991
77
24.376543
162
starcoderdata
using OilStationCoreAPI.IServices; using OilStationCoreAPI.Models; using OilStationCoreAPI.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static OilStationCoreAPI.ViewModels.CodeEnum; namespace OilStationCoreAPI.Services { public class LeaveServices : ILeaveServices { private readonly OSMSContext _db; public LeaveServices(OSMSContext db) { _db = db; } public ResponseModel Leave_Get() { var list = _db.LeaveOffice.Where(x => true); var joblist = _db.Job.Where(x => true); List reList = new List foreach (var item in list) { LeaveViewModel leave = new LeaveViewModel { Id = item.Id.ToString(), StaffName = item.StaffName, JobId = joblist.Where(x => x.Id.ToString().ToLower() == item.JobId.ToString().ToLower()) .FirstOrDefault().Name, LeaveType = item.LeaveType == "0" ? "离职" : "辞退", ApplyTime = Convert.ToDateTime(item.ApplyDate), Reason = item.Reason, No = item.No, CreateTime = Convert.ToDateTime(item.CreateTime) }; reList.Add(leave); } return new ResponseModel { code = (int)code.Success, data = reList, message = ""//获取离职信息成功 }; } public ResponseModel Leave_CheckGet() { var list = _db.LeaveOffice.Where(x => x.No == "0"); var joblist = _db.Job.Where(x => true); List reList = new List foreach (var item in list) { LeaveViewModel leave = new LeaveViewModel { Id = item.Id.ToString(), StaffName = item.StaffName, JobId = joblist.Where(x => x.Id.ToString().ToLower() == item.JobId.ToString().ToLower()) .FirstOrDefault().Name, LeaveType = item.LeaveType, ApplyTime = Convert.ToDateTime(item.ApplyDate), Reason = item.Reason, No = item.No, CreateTime = Convert.ToDateTime(item.CreateTime) }; reList.Add(leave); } return new ResponseModel { code = (int)code.Success, data = reList, message = ""//获取未审核离职信息成功 }; } public ResponseModel Leave_Add(LeaveViewModel model) { LeaveOffice leave = new LeaveOffice { Id = Guid.NewGuid(), StaffName = model.StaffName, No = "0", JobId = new Guid(model.JobId), LeaveType = model.LeaveType == "离职" ? "0" : "1", CreateTime = DateTime.Now, UpdateTime = DateTime.Now, ApplyDate = model.ApplyTime, Reason = model.Reason }; _db.LeaveOffice.Add(leave); int num = _db.SaveChanges(); if (num > 0) { return new ResponseModel { code = (int)code.Success, data = true, message = "添加离职信息成功" }; } return new ResponseModel { code = (int)code.AddLeaveFail, data = false, message = "添加离职信息失败" }; } public ResponseModel Leave_Check(CheckViewModel model) { var leave = _db.LeaveOffice.Where(x => x.Id.ToString().ToLower() == model.Id).FirstOrDefault(); leave.No = model.CheckNo; _db.LeaveOffice.Update(leave); int num = _db.SaveChanges(); if (num > 0) { return new ResponseModel { code = (int)code.Success, data = true, message = "审核离职信息成功" }; } return new ResponseModel { code = (int)code.UpdaateCheckLeaveFail, data = false, message = "审核离职信息失败" }; } public ResponseModel Leave_Delete(string id) { var leave = _db.LeaveOffice.Where(x => x.Id.ToString().ToLower() == id).FirstOrDefault(); _db.LeaveOffice.Remove(leave); int num = _db.SaveChanges(); if (num > 0) { return new ResponseModel { code = (int)code.Success, data = true, message = "删除离职信息成功" }; } return new ResponseModel { code = (int)code.DeleteLeaveFail, data = false, message = "删除离职信息失败" }; } } }
c#
29
0.509701
122
37.65625
128
starcoderdata
// Code generated by MockGen. DO NOT EDIT. // Source: internal/domain/exchange/repository.go // Package mock_exchange is a generated GoMock package. package mock_exchange import ( context "context" exchange "github.com/calmato/presto-pay/api/calc/internal/domain/exchange" gomock "github.com/golang/mock/gomock" reflect "reflect" ) // MockExchangeRepository is a mock of ExchangeRepository interface type MockExchangeRepository struct { ctrl *gomock.Controller recorder *MockExchangeRepositoryMockRecorder } // MockExchangeRepositoryMockRecorder is the mock recorder for MockExchangeRepository type MockExchangeRepositoryMockRecorder struct { mock *MockExchangeRepository } // NewMockExchangeRepository creates a new mock instance func NewMockExchangeRepository(ctrl *gomock.Controller) *MockExchangeRepository { mock := &MockExchangeRepository{ctrl: ctrl} mock.recorder = &MockExchangeRepositoryMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockExchangeRepository) EXPECT() *MockExchangeRepositoryMockRecorder { return m.recorder } // Index mocks base method func (m *MockExchangeRepository) Index(ctx context.Context) (*exchange.ExchangeRates, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Index", ctx) ret0, _ := ret[0].(*exchange.ExchangeRates) ret1, _ := ret[1].(error) return ret0, ret1 } // Index indicates an expected call of Index func (mr *MockExchangeRepositoryMockRecorder) Index(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Index", reflect.TypeOf((*MockExchangeRepository)(nil).Index), ctx) } // Show mocks base method func (m *MockExchangeRepository) Show(ctx context.Context, currency string) (float64, string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Show", ctx, currency) ret0, _ := ret[0].(float64) ret1, _ := ret[1].(string) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // Show indicates an expected call of Show func (mr *MockExchangeRepositoryMockRecorder) Show(ctx, currency interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Show", reflect.TypeOf((*MockExchangeRepository)(nil).Show), ctx, currency) }
go
13
0.763932
130
33.530303
66
starcoderdata
/* ** @author Software, LLC ** @created 9/28/2021 */ import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PublicKeyTests { @Test public void testDefaultConstructor() { PublicKey key = new PublicKey(); int n = key.getN(); int e = key.getE(); assertTrue(!Maths.isPrime(n)); assertTrue(Maths.isPrime(e)); } @Test public void testPublicKeyConstructor() { PublicKey key = new PublicKey(); int n = key.getN(); int e = key.getE(); PublicKey key_1 = new PublicKey(key); int n_1 = key.getN(); int e_1 = key.getE(); assertEquals(n, n_1); assertEquals(e, e_1); } @Test public void testPQConstructor() { int p = 19; int q = 43; PublicKey key = new PublicKey(19, 43); int n = key.getN(); int e = key.getE(); assertEquals(p * q, n); assertTrue(Maths.isPrime(e)); } }
java
11
0.558348
46
18.54386
57
starcoderdata
package com.yyxnb.what.download; import com.yyxnb.what.okhttp.AbsOkHttp; public class DownloadOkHttp extends AbsOkHttp { private static volatile DownloadOkHttp mInstance = null; private DownloadOkHttp() { } public static DownloadOkHttp getInstance() { if (null == mInstance) { synchronized (DownloadOkHttp.class) { if (null == mInstance) { mInstance = new DownloadOkHttp(); } } } return mInstance; } @Override protected String baseUrl() { return ""; } }
java
15
0.572139
60
19.1
30
starcoderdata
import java.util.*; class Main { public static void main(String args[]){ Main main = new Main(); } public Main(){ Scanner SC = new Scanner(System.in); int N = Integer.parseInt(SC.next()); int M = Integer.parseInt(SC.next()); int[] NUM = new int[N]; boolean[] T = new boolean[N]; for(int i=0;i<N;i++) T[i] = false; int A = 0; int P = 0; for(int i=0;i<M;i++){ int p = Integer.parseInt(SC.next())-1; boolean S = SC.next().equals("AC"); if(T[p]) continue; if(S){ A++; P += NUM[p]; } else { NUM[p]++; } T[p] = S; } System.out.println(A + " " + P); } }
java
14
0.399015
50
19.820513
39
codenet
<?php /** * Copyright 2014-2016 Horde LLC (http://www.horde.org/) * * @category Horde * @license http://www.horde.org/licenses/lgpl21 LGPL 2.1 * @package Css_Parser * @subpackage UnitTests */ /** * @author * @category Horde * @license http://www.horde.org/licenses/lgpl21 LGPL 2.1 * @ignore * @package Css_Parser * @subpackage UnitTests */ class Horde_Css_Parser_ParserTest extends PHPUnit_Framework_TestCase { public function testDoubleAsteriskAtBeginningOfComment() { $a = '/** Foo */#bar{width:1px;}'; $css = new Horde_Css_Parser($a); $this->assertEquals( '#bar{width:1px}', $css->compress() ); } /** * @small */ public function testEmptyDocument() { $css = new Horde_Css_Parser(''); $this->assertEquals('', $css->compress()); } }
php
11
0.589452
68
22.02381
42
starcoderdata
package tlb.service; import tlb.TlbSuiteFile; import tlb.domain.SuiteResultEntry; import tlb.domain.SuiteTimeEntry; import tlb.splitter.correctness.ValidationResult; import java.util.List; /** * @understands talking to an external service to get and post data */ public interface Server { //TODO: this is horrible api, make it accept SuiteTimeEntry void testClassTime(String className, long time); //TODO: this is horrible api, make it accept SuiteResultEntry void testClassFailure(String className, boolean hasFailed); List getLastRunTestTimes(); List getLastRunFailedTests(); void publishSubsetSize(int size); int partitionNumber(); int totalPartitions(); ValidationResult validateUniversalSet(List universalSet, String moduleName); ValidationResult validateSubSet(List subSet, String moduleName); ValidationResult verifyAllPartitionsExecutedFor(String moduleName); String partitionIdentifier(); }
java
8
0.774379
94
26.526316
38
starcoderdata
// // PushButton.h // Reuse0 // // Created by Ben on 16/3/31. // Copyright © 2016年 Ben. All rights reserved. // #import @interface PushButtonData : NSObject @property (nonatomic, strong) NSString *actionString; @property (nonatomic, unsafe_unretained) id target; //@property (nonatomic, strong) NSString *title; //@property (nonatomic, assign) NSInteger typeLayout; //图文类型. 单图. 单文. 左图右文. 左文右图. 上图下文. 上文下图. //@property (nonatomic, assign) UIEdgeInsets edgeImage; //根据类型, 只取部分参数. //@property (nonatomic, assign) UIEdgeInsets edgeTitleLabel; //根据类型, 只取部分参数. //@property (nonatomic, assign) NSDictionary *additonalInfo; //Normal. @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) UIColor *titleColor; @property (nonatomic, strong) NSString *titleShadowColor; @property (nonatomic, strong) NSString *imageName; @property (nonatomic, strong) NSString *backgroundImageName; @property (nonatomic, strong) NSAttributedString *attributedTitle; @end @interface PushButton : UIButton @property (nonatomic, strong) PushButtonData* buttonData; @end @interface UIButton (UIButtonImageWithLable) - (void) setImage:(UIImage *)image withTitle:(NSString *)title titleFont:(UIFont*)font forState:(UIControlState)stateType; @end
c
8
0.664355
122
15.964706
85
starcoderdata
const sample = require('lodash/sample'); const fortunes = [ 'Conquer your fears or they will conquer you.', 'Rivers need springs.', 'Do not fear what you don\'t know.', 'You will have a pleasant surprise.', 'Whenever possible, keep it simple.', ]; function getFortune() { return sample(fortunes); } exports.getFortune = getFortune;
javascript
5
0.693593
49
21.4375
16
starcoderdata
import komand from .schema import LabelingInput, LabelingOutput # Custom imports below class Labeling(komand.Action): def __init__(self): super(self.__class__, self).__init__( name='labeling', description='Looks for exposed secrets in the git commit history and branches', input=LabelingInput(), output=LabelingOutput()) self.grrapi = None def run(self, params={}): self.grrapi = self.connection.grrapi query = params.get('query') label = params.get('label') label = [str(x) for x in label] search_results = self.grrapi.SearchClients(query) try: for client in search_results: type_client = type(client) if type(client) is not type_client: return {'result': "No clients found with the given query"} client.AddLabels(label) except Exception as e: self.logger.error(e) return {'results': 'All clients have been labeled'} def test(self): self.grrapi = self.connection.grrapi if self.grrapi: return {'results': 'Ready to label'} if not self.grrapi: return {'results': 'Not ready. Please check your connection with the GRR Client'}
python
15
0.594277
93
33.075
40
starcoderdata
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\Medico; use Carbon\Carbon; use Illuminate\Support\Facades\DB; class MedicoSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('medicos')->insert(['nome' => ' 'crm' => 90654, 'telefone' => '(38) 99993-4082', 'nascimento' => Carbon::create('1997', '15', '07'), 'endereco' => 'Rua Conceição, 95, Centro', 'especialidade' => 'Cardiologista' ]); DB::table('medicos')->insert(['nome' => 'Joana', 'crm' => 14654, 'telefone' => '(38) 99783-4082', 'nascimento' => Carbon::create('1997','05','01'), 'endereco' => 'Rua B, 100, Alameda', 'especialidade' => 'Pediatria' ]); DB::table('medicos')->insert(['nome' => ' 'crm' => 12564, 'telefone' => '(38) 99983-1452', 'nascimento' => Carbon::create('1996','06','26'), 'endereco' => 'Rua Conceição, 333, Centro', 'especialidade' => 'Dermatologia' ]); DB::table('medicos')->insert(['nome' => ' 'crm' => 14596, 'telefone' => '(38) 99873-1205', 'nascimento' => Carbon::create('1997','07','27'), 'endereco' => 'Rua A, 95, Sagrada Familia', 'especialidade' => 'Ginecologia' ]); } }
php
15
0.525136
59
24.824561
57
starcoderdata
import os, collections import networkx as nx import numpy as np import torch, dgl import random, pickle class synthetic_graph_cls: # generate several graphs with different paterns and union them # labels is whether the union graph contains speicific pattern def __init__(self, args): self.args = args self.saved_file = f'./data/synthetic/synthetic_graph_cls_data_{args.num_factors}.pkl' os.makedirs(os.path.dirname(self.saved_file), exist_ok=True) def gen_union_graph(self, graph_size=15, num_graph=20000): if os.path.isfile(self.saved_file): print(f"load synthetic graph cls data from {self.saved_file}") with open(self.saved_file, 'rb') as f: return pickle.load(f) graph_list = synthetic_graph_cls.get_graph_list(self.args.num_factors) samples = [] for _ in range(num_graph): union_adj = np.zeros((graph_size, graph_size)) factor_adjs = [] labels = np.zeros((1, len(graph_list))) id_index = list(range(len(graph_list))) random.shuffle(id_index) for i in range((len(id_index)+1)//2): # get random half adj id = id_index[i] labels[0, id] = 1 single_adj = graph_list[id] padded_adj = np.zeros((graph_size, graph_size)) padded_adj[:single_adj.shape[0], :single_adj.shape[0]] = single_adj random_index = np.arange(padded_adj.shape[0]) np.random.shuffle(random_index) padded_adj = padded_adj[random_index] padded_adj = padded_adj[:, random_index] union_adj += padded_adj factor_adjs.append((padded_adj, id)) g = dgl.DGLGraph() g.from_networkx(nx.DiGraph(union_adj)) g = dgl.transform.add_self_loop(g) g.ndata['feat'] = torch.tensor(union_adj) labels = torch.tensor(labels) samples.append((g, labels, factor_adjs)) with open(self.saved_file, 'wb') as f: pickle.dump(samples, f) print(f"dataset saved to {self.saved_file}") return samples @staticmethod def get_graph_list(num_factors): graph_list = [] # 2, 3 bipartite graph g = nx.turan_graph(n=5, r=2) graph_list.append(nx.to_numpy_array(g)) g = nx.house_x_graph() graph_list.append(nx.to_numpy_array(g)) g = nx.balanced_tree(r=3, h=2) graph_list.append(nx.to_numpy_array(g)) g = nx.grid_2d_graph(m=3, n=3) graph_list.append(nx.to_numpy_array(g)) g = nx.hypercube_graph(n=3) graph_list.append(nx.to_numpy_array(g)) g = nx.octahedral_graph() graph_list.append(nx.to_numpy_array(g)) return graph_list[:num_factors]
python
15
0.552234
93
35.304878
82
starcoderdata
<?php namespace p4scu41\BaseCRUDApi\Http\Middleware; use p4scu41\BaseCRUDApi\Support\ReflectionSupport; use Closure; /** * PerformanceLoggerFinish Middleware * * @category Middleware * @package p4scu41\BaseCRUDApi\Http\Middleware * @author * @created 2018-07-27 */ class PerformanceLoggerFinish extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); $route = $request->route(); if (!empty($route)) { $action = $route->getAction(); // $route->action (array) $controller = $route->controller; // $route->getController() (instance of current Controller) if (!empty($controller)) { if (ReflectionSupport::hasProperty($controller, 'is_tracking_performance') && ReflectionSupport::hasProperty($controller, 'except_track_performance')) { // $controller[0] => class, $controller[1] => method $method = isset($action['controller']) ? explode('@', $action['controller']) : 'laravel'; if ($controller->is_tracking_performance && !in_array($method[1] ?: $method, $controller->except_track_performance)) { $controller->performance->finish(); $controller->performance->getInfo(); $controller->performance->saveAll(); } } } } return $response; } }
php
21
0.556659
109
31.923077
52
starcoderdata
def create_alert(self, **kwargs) -> pai.alert.Alert: """Create a new alert for this equipment. See Also -------- :meth:`sailor.pai.alert.create_alert` """ fixed_kwargs = {'equipment_id': self.id} request = pai.alert._AlertWriteRequest(**fixed_kwargs) request.insert_user_input(kwargs, forbidden_fields=['id', 'equipment_id']) return pai.alert._create_alert(request)
python
9
0.600457
82
38.909091
11
inline
class EventLoop : nocopyable { public: typedef std::function<void ()> Functor; EventLoop(); ~EventLoop(); void loop(); void quit(); // runs callback imediately in this thread void runInLoop(Functor cb); // queues callback in the loop thread void queueInLoop(Functor cb); // run callback at time // safe to call from other threads TimerId runAt(Timestamp time, TimerCallback cb); // run callback after delay seconds // safe to call from other threads TimerId runAfter(double delay, TimerCallback cb); // run callback every interval seconds // safe to call from other threads TimerId runEvery(double interval, TimerCallback cb); void assertInLoopThread() { if (!isInLoopThread()) { abortNotInLoopThread(); } } bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); } static EventLoop *getEventLoopOfCurrentThread(); void cancel(TimerId timerId); // Channel, internal usage void wakeup(); void updateChannel(Channel *channel); void removeChannel(Channel *Channel); bool hasChannel(Channel* channel); private: void abortNotInLoopThread(); void handleRead(); // wake up void doPendingFunctors(); typedef std::vector<Channel*> ChannelList; bool EventHandling_; // atomic bool callingPendingFunctors_; // atomic bool quit_; ChannelList activeChannels_; std::unique_ptr<Poller> poller_; std::unique_ptr<TimerQueue> timerQueue_; bool looping_; // atomic const pid_t threadId_; Timestamp pollReturnTime_; Channel* currentActiveChannel_; int wakeupFd_; // unlike in TimerQueue, whis is an internal class, // we don't expose Channel to client. std::unique_ptr<Channel> wakeupChannel_; mutable MutexLock mutex_; std::vector<Functor> pendingFunctors_; }
c
10
0.597933
81
28.178082
73
inline
/*----------------------------------------------------------------------------*/ /* Xymon monitor library. */ /* */ /* This is a library module, part of libxymon. */ /* It contains a "mergesort" implementation for sorting linked lists. */ /* */ /* Based on http://en.wikipedia.org/wiki/Merge_sort pseudo code, adapted for */ /* use in a generic library routine. */ /* */ /* Copyright (C) 2009-2011 */ /* */ /* This program is released under the GNU General Public License (GPL), */ /* version 2. See the file "COPYING" for details. */ /* */ /*----------------------------------------------------------------------------*/ static char rcsid[] = "$Id$"; #include #include #include #include #include #include "libxymon.h" #if 0 static void *merge(void *left, void *right, msortcompare_fn_t comparefn, msortgetnext_fn_t getnext, msortsetnext_fn_t setnext) { void *head, *tail; head = tail = NULL; while (left && right) { if (comparefn(left, right) < 0) { /* Add the left item to the resultlist */ if (tail) { setnext(tail, left); } else { head = left; } tail = left; left = getnext(left); } else { /* Add the right item to the resultlist */ if (tail) { setnext(tail, right); } else { head = right; } tail = right; right = getnext(right); } } /* One or both lists have ended. Add whatever elements may remain */ if (left) { if (tail) setnext(tail, left); else head = tail = left; } if (right) { if (tail) setnext(tail, right); else head = tail = right; } return head; } void *msort(void *head, msortcompare_fn_t comparefn, msortgetnext_fn_t getnext, msortsetnext_fn_t setnext) { void *left, *right, *middle, *walk, *walknext; /* First check if list is empty or has only one element */ if ((head == NULL) || (getnext(head) == NULL)) return head; /* * Find the middle element of the list. * We do this by walking the list until we reach the end. * "middle" takes one step at a time, whereas "walk" takes two. */ middle = head; walk = getnext(middle); /* "walk" must be ahead of "middle" */ while (walk && (walknext = getnext(walk))) { middle = getnext(middle); walk = getnext(walknext); } /* Split the list in two halves, and sort each of them. */ left = head; right = getnext(middle); setnext(middle, NULL); left = msort(left, comparefn, getnext, setnext); right = msort(right, comparefn, getnext, setnext); /* We have sorted the two halves, now we must merge them together */ return merge(left, right, comparefn, getnext, setnext); } #endif void *msort(void *head, msortcompare_fn_t comparefn, msortgetnext_fn_t getnext, msortsetnext_fn_t setnext) { void *walk; int len, i; void **plist; for (walk = head, len=0; (walk); walk = getnext(walk)) len++; plist = malloc((len+1) * sizeof(void *)); for (walk = head, i=0; (walk); walk = getnext(walk)) plist[i++] = walk; plist[len] = NULL; qsort(plist, len, sizeof(plist[0]), comparefn); for (i=0, head = plist[0]; (i < len); i++) setnext(plist[i], plist[i+1]); xfree(plist); return head; } #ifdef STANDALONE typedef struct rec_t { struct rec_t *next; char *key; char *val; } rec_t; void dumplist(rec_t *head) { rec_t *walk; walk = head; while (walk) { printf("%p : %-15s:%3s\n", walk, walk->key, walk->val); walk = walk->next; } printf("\n"); printf("\n"); } int record_compare(void **a, void **b) { rec_t **reca = (rec_t **)a; rec_t **recb = (rec_t **)b; return strcasecmp((*reca)->key, (*recb)->key); } void * record_getnext(void *a) { return ((rec_t *)a)->next; } void record_setnext(void *a, void *newval) { ((rec_t *)a)->next = (rec_t *)newval; } /* 50 most popular US babynames in 2006: http://www.ssa.gov/OACT/babynames/ */ char *tdata[] = { "Jacob", "Emily", "Michael", "Emma", "Joshua", "Madison", "Ethan", "Isabella", "Matthew", "Ava", "Daniel", "Abigail", "Christopher", "Olivia", "Andrew", "Hannah", "Anthony", "Sophia", "William", "Samantha", "Joseph", "Elizabeth", "Alexander", "Ashley", "David", "Mia", "Ryan", "Alexis", "Noah", "Sarah", "James", "Natalie", "Nicholas", "Grace", "Tyler", "Chloe", "Logan", "Alyssa", "John", "Brianna", "Christian", "Ella", "Jonathan", "Taylor", "Nathan", "Anna", "Benjamin", "Lauren", "Samuel", "Hailey", "Dylan", "Kayla", "Brandon", "Addison", "Gabriel", "Victoria", "Elijah", "Jasmine", "Aiden", "Savannah", "Angel", "Julia", "Jose", "Jessica", "Zachary", "Lily", "Caleb", "Sydney", "Jack", "Morgan", "Jackson", "Katherine", "Kevin", "Destiny", "Gavin", "Lillian", "Mason", "Alexa", "Isaiah", "Alexandra", "Austin", "Kaitlyn", "Evan", "Kaylee", "Luke", "Nevaeh", "Aidan", "Brooke", "Justin", "Makayla", "Jordan", "Allison", "Robert", "Maria", "Isaac", "Angelina", "Landon", "Rachel", "Jayden", "Gabriella", NULL }; int main(int argc, char *argv[]) { int i; rec_t *head, *newrec, *tail; head = tail = NULL; for (i=0; (tdata[i]); i++) { char numstr[10]; newrec = (rec_t *)calloc(1, sizeof(rec_t)); newrec->key = strdup(tdata[i]); sprintf(numstr, "%d", i+1); newrec->val = strdup(numstr); if (tail) { tail->next = newrec; tail = newrec; } else { head = tail = newrec; } } dumplist(head); head = msort(head, record_compare, record_getnext, record_setnext); dumplist(head); return 0; } #endif
c
14
0.543256
119
19.111486
296
starcoderdata
void Engine::UpdatePlayerScore(std::string const & endpoint_id, int score, bool final) { auto player = players_score_.find(endpoint_id); if (player == players_score_.end()) { LOGE("Error: player(%s) is not in my cache", player->first.c_str()); DebugDumpConnections(); return; } if (player->second.score_ > score) { LOGI("Score (%d) is lower than saved one(%d), no action", score, player->second.score_); return; } player->second.score_ = score; player->second.finished_ = final; if (!player->second.is_host_) { // I am not a host for this link, done return; } //broadcast the score to all others connected to me std::vector<uint8_t> payload; if (BuildScorePayload(payload, score, endpoint_id, final) == false) { LOGE("failed to build payload for player %s:", endpoint_id.c_str()); return; } auto *this_player = &player->second; for (player = players_score_.begin(); player != players_score_.end(); ++player) { if (player->first == this_player->endpoint_id_ || !player->second.is_direct_connection_ || !player->second.is_host_) { continue; // do not send back for his own score } LOGV("Sending(%s) for %s score = %d", player->first.c_str(), endpoint_id.c_str(), this_player->score_); nearby_connection_->SendUnreliableMessage(player->first, payload); } }
c++
12
0.617293
76
34.3
40
inline
import java.util.*; import static java.lang.Math.*; import static java.lang.System.*; import java.util.stream.*; /* Problem name: 253 Cube painting Problem url: https://uva.onlinejudge.org/external/2/253.pdf Author: */ public class _253_CubePainting { public static void main(String[] args){ Scanner s = new Scanner(in); while(s.hasNext()){ String cubes = s.next(); if(cubesEqual(cubes.substring(0, 6), cubes.substring(6))){ System.out.println("TRUE"); }else System.out.println("FALSE"); } } static boolean cubesEqual(String cube1, String cube2){ String rotatedCube1 = cube1; for(int x = 0; x < 4; x++){ rotatedCube1 = rotateAroundXAxis(rotatedCube1); for(int y = 0; y < 4; y++){ rotatedCube1 = rotateAroundYAxis(rotatedCube1); for(int z = 0; z < 4; z++){ rotatedCube1 = rotateAroundZAxis(rotatedCube1); if(rotatedCube1.equals(cube2)) return true; } } } return false; } static String rotateAroundZAxis(String cube){ return rotate(cube, new int[] {4, 2, 1, 6, 5, 3}); } static String rotateAroundXAxis(String cube){ return rotate(cube, new int[] {5, 1, 3, 4, 6, 2}); } static String rotateAroundYAxis(String cube){ return rotate(cube, new int[] {1, 4, 2, 5, 3, 6}); } static String rotate(String cube, int[] colorsAfterRotation){ StringBuilder rotatedCube = new StringBuilder(); for(int i = 0; i < colorsAfterRotation.length; i++){ rotatedCube.append(cube.charAt(colorsAfterRotation[i] - 1)); } return rotatedCube.toString(); } }
java
15
0.636757
66
27.857143
56
starcoderdata
/* * This file is part of the optimized implementation of the Picnic signature scheme. * See the accompanying documentation for complete details. * * The code is provided under the MIT license, see LICENSE for * more details. * SPDX-License-Identifier: MIT */ #ifndef IO_H #define IO_H #include #include #include "oqs_picnic_macros.h" #include "mzd_additional.h" void mzd_to_char_array(uint8_t* dst, const mzd_local_t* data, size_t numbytes); void mzd_from_char_array(mzd_local_t* result, const uint8_t* data, size_t len); /* Get one bit from a byte array */ static inline uint8_t getBit(const uint8_t* array, size_t bitNumber) { return (array[bitNumber / 8] >> (7 - (bitNumber % 8))) & 0x01; } /* Set a specific bit in a byte array to a given value */ static inline void setBit(uint8_t* bytes, size_t bitNumber, uint8_t val) { bytes[bitNumber / 8] = (bytes[bitNumber >> 3] & ~(1 << (7 - (bitNumber % 8)))) | (val << (7 - (bitNumber % 8))); } static inline int check_padding_bits(const uint8_t byte, const unsigned int diff) { return byte & ~(UINT8_C(0xff) << diff); } #if defined(PICNIC_STATIC) || !defined(NDEBUG) void print_hex(FILE* out, const uint8_t* data, size_t len); #endif #endif
c
16
0.679936
95
28.904762
42
starcoderdata
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class MY_Admin extends CI_Controller { protected $userData = ""; protected $id_prov_selected; protected $id_group_admin; protected $id_group_koordinator; protected $id_group_kel_wilayah; public function __construct() { parent::__construct(); $this->load->model("m_template"); $setting = $this->m_template->get_setting(); foreach ($setting as $key => $value) { if ($value->key == 'id_prov_selected') { $this->id_prov_selected = $value->value; } else if ($value->key == 'id_group_admin') { $this->id_group_admin = $value->value; } else if ($value->key == 'id_group_koordinator') { $this->id_group_koordinator = $value->value; } else if ($value->key == 'id_group_kel_wilayah') { $this->id_group_kel_wilayah = $value->value; } } if (!$this->session->userdata('user_id')) { redirect('loginadm'); } } public function theme($dat) { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: PUT, GET, POST"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); // buat template if (!array_key_exists("title", $dat)) { $dat['title'] = ''; } if (!array_key_exists("konten", $dat)) { $dat['konten'] = ''; } $user_id = $this->session->userdata('user_id'); $dmenu['tmp_menu'] = $this->m_template->buat_menu($user_id); $dat['menu'] = $this->load->view('template/menu', $dmenu, TRUE);; $dheader['nama_user'] = ''; $dat['header'] = $this->load->view('template/header', $dheader, TRUE);; $dfooter = array(); $dat['footer'] = $this->load->view('template/footer', $dfooter, TRUE); $this->load->view('template/index', $dat, FALSE); } }
php
19
0.531373
95
36.090909
55
starcoderdata
/* * 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 io.reactivesocket.client; import io.reactivesocket.Payload; import io.reactivesocket.client.ReactiveSocketClient.SocketAcceptor; import io.reactivesocket.lease.DefaultLeaseHonoringSocket; import io.reactivesocket.DuplexConnection; import io.reactivesocket.Frame; import io.reactivesocket.Frame.Setup; import io.reactivesocket.lease.DisableLeaseSocket; import io.reactivesocket.lease.LeaseHonoringSocket; import io.reactivesocket.ReactiveSocket; import io.reactivesocket.frame.SetupFrameFlyweight; import io.reactivesocket.util.PayloadImpl; import org.reactivestreams.Publisher; import java.util.function.Function; /** * A provider for ReactiveSocket setup from a client. */ public interface SetupProvider { int DEFAULT_FLAGS = SetupFrameFlyweight.FLAGS_WILL_HONOR_LEASE | SetupFrameFlyweight.FLAGS_STRICT_INTERPRETATION; int DEFAULT_MAX_KEEP_ALIVE_MISSING_ACK = 3; String DEFAULT_METADATA_MIME_TYPE = "application/x.reactivesocket.meta+cbor"; String DEFAULT_DATA_MIME_TYPE = "application/binary"; /** * Accept a {@link DuplexConnection} and does the setup to produce a {@code ReactiveSocket}. * * @param connection To setup. * @param acceptor of the newly created {@code ReactiveSocket}. * * @return Asynchronous source for the created {@code ReactiveSocket} */ Publisher accept(DuplexConnection connection, SocketAcceptor acceptor); /** * Creates a new {@code SetupProvider} by modifying the mime type for data payload of this {@code SetupProvider} * * @param dataMimeType Mime type for data payloads for all created {@code ReactiveSocket} * * @return A new {@code SetupProvider} instance. */ SetupProvider dataMimeType(String dataMimeType); /** * Creates a new {@code SetupProvider} by modifying the mime type for metadata payload of this {@code SetupProvider} * * @param metadataMimeType Mime type for metadata payloads for all created {@code ReactiveSocket} * * @return A new {@code SetupProvider} instance. */ SetupProvider metadataMimeType(String metadataMimeType); /** * Creates a new {@code SetupProvider} that honors leases sent from the server. * * @param leaseDecorator A factory that decorates a {@code ReactiveSocket} to honor leases. * * @return A new {@code SetupProvider} instance. */ SetupProvider honorLease(Function<ReactiveSocket, LeaseHonoringSocket> leaseDecorator); /** * Creates a new {@code SetupProvider} that does not honor leases. * * @return A new {@code SetupProvider} instance. */ SetupProvider disableLease(); /** * Creates a new {@code SetupProvider} that does not honor leases. * * @param socketFactory A factory to create {@link DisableLeaseSocket} for each accepted socket. * * @return A new {@code SetupProvider} instance. */ SetupProvider disableLease(Function<ReactiveSocket, DisableLeaseSocket> socketFactory); /** * Creates a new {@code SetupProvider} that uses the passed {@code setupPayload} as the payload for the setup frame. * Default instances, do not have any payload. * * @return A new {@code SetupProvider} instance. */ SetupProvider setupPayload(Payload setupPayload); /** * Creates a new {@link SetupProvider} using the passed {@code keepAliveProvider} for keep alives to be sent on the * {@link ReactiveSocket}s created by this provider. * * @param keepAliveProvider Provider for keep-alive. * * @return A new {@code SetupProvider}. */ static SetupProvider keepAlive(KeepAliveProvider keepAliveProvider) { int period = keepAliveProvider.getKeepAlivePeriodMillis(); Frame setupFrame = Setup.from(DEFAULT_FLAGS, period, keepAliveProvider.getMissedKeepAliveThreshold() * period, DEFAULT_METADATA_MIME_TYPE, DEFAULT_DATA_MIME_TYPE, PayloadImpl.EMPTY); return new SetupProviderImpl(setupFrame, reactiveSocket -> new DefaultLeaseHonoringSocket(reactiveSocket), keepAliveProvider, Throwable::printStackTrace); } }
java
12
0.715265
120
38.793388
121
starcoderdata
import React, { useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { profitsPageAnimationOnMount } from './ProfitsPageAnimations.js'; import { StyledProfitsSectionWrapper } from './ProfitsSection.css.js'; import { StyledNextSectionButtonWrapper, StyledPrevSectionButtonWrapper, } from 'components/SectionsContainer/SectionsContainer.css.js'; //material kit react import Button from 'MaterialComponents/CustomButtons/Button.js'; import GridContainer from 'MaterialComponents/Grid/GridContainer.js'; import GridItem from 'MaterialComponents/Grid/GridItem.js'; import InfoArea from 'MaterialComponents/InfoArea/InfoArea.js'; const ProfitsSection = ({ handleChangePage }) => { const { t } = useTranslation(); useEffect(() => { profitsPageAnimationOnMount(); }, []); return ( <StyledProfitsSectionWrapper className='profits-container'> <StyledPrevSectionButtonWrapper className='prev-page-button-container'> <Button color='github' size='lg' onClick={() => handleChangePage(2)} simple round > <div className='button-icon'> <i className='fas fa-chevron-left'> <div className='button-text'> <GridContainer className='profits-grid'> <GridItem xs={12} sm={6} lg={4}> <InfoArea title={t('profits.box1.title')} description={t('profits.box1.text')} icon={<i className='fas fa-graduation-cap'> iconColor='primary' /> <GridItem xs={12} sm={6} lg={4}> <InfoArea title={t('profits.box2.title')} description={t('profits.box2.text')} icon={<i className='fas fa-calculator'> iconColor='primary' /> <GridItem xs={12} sm={6} lg={4}> <InfoArea title={t('profits.box3.title')} description={t('profits.box3.text')} icon={<i className='fas fa-sliders-h'> iconColor='primary' /> <GridItem xs={12} sm={6} lg={4}> <InfoArea title={t('profits.box4.title')} description={t('profits.box4.text')} icon={<i className='fas fa-umbrella'> iconColor='primary' /> <GridItem xs={12} sm={6} lg={4}> <InfoArea title={t('profits.box5.title')} description={t('profits.box5.text')} icon={<i className='fas fa-umbrella'> iconColor='primary' /> <GridItem xs={12} sm={6} lg={4}> <InfoArea title={t('profits.box6.title')} description={t('profits.box6.text')} icon={<i className='fas fa-umbrella'> iconColor='primary' /> <StyledNextSectionButtonWrapper className='next-page-button-wrapper'> <Button color='github' size='lg' onClick={() => handleChangePage(4)} simple round > <div className='button-text'> <div className='button-icon'> <i className='fas fa-chevron-right'> ); }; export default ProfitsSection;
javascript
12
0.504708
80
36.263158
114
starcoderdata
public static DateTime UpdateDate(DateTime dateToUpdate, Double increment, IntervalTypes intervalType) { switch (intervalType) { case IntervalTypes.Years: dateToUpdate = dateToUpdate.AddYears((int)Math.Floor(increment)); TimeSpan span = TimeSpan.FromDays(365.0 * (increment - Math.Floor(increment))); dateToUpdate = dateToUpdate.Add(span); return dateToUpdate; case IntervalTypes.Months: // Special case handling when current date point // to the last day of the month bool lastMonthDay = false; if (dateToUpdate.Day == DateTime.DaysInMonth(dateToUpdate.Year, dateToUpdate.Month)) { lastMonthDay = true; } // Add specified amount of months dateToUpdate = dateToUpdate.AddMonths((int)Math.Floor(increment)); span = TimeSpan.FromDays(30.0 * (increment - Math.Floor(increment))); // Check if last month of the day was used if (lastMonthDay && span.Ticks == 0) { // Make sure the last day of the month is selected int daysInMobth = DateTime.DaysInMonth(dateToUpdate.Year, dateToUpdate.Month); dateToUpdate = dateToUpdate.AddDays(daysInMobth - dateToUpdate.Day); } dateToUpdate = dateToUpdate.Add(span); return dateToUpdate; case IntervalTypes.Weeks: return dateToUpdate.AddDays(7 * increment); case IntervalTypes.Hours: return dateToUpdate.AddHours(increment); case IntervalTypes.Minutes: return dateToUpdate.AddMinutes(increment); case IntervalTypes.Seconds: return dateToUpdate.AddSeconds(increment); case IntervalTypes.Milliseconds: return dateToUpdate.AddMilliseconds(increment); default: return dateToUpdate.AddDays(increment); } }
c#
20
0.521739
104
39.465517
58
inline
package au.gov.digitalhealth.medserve.server.indexbuilder; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.core.LowerCaseFilterFactory; import org.apache.lucene.analysis.core.WhitespaceTokenizerFactory; import org.apache.lucene.analysis.custom.CustomAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.IntPoint; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.DomainResource; import org.hl7.fhir.dstu3.model.Medication.MedicationIngredientComponent; import org.hl7.fhir.dstu3.model.Medication.MedicationPackageContentComponent; import org.hl7.fhir.dstu3.model.Organization; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.dstu3.model.Resource; import org.hl7.fhir.dstu3.model.Substance; import org.hl7.fhir.exceptions.FHIRException; import au.gov.digitalhealth.medserve.extension.ExtendedMedication; import au.gov.digitalhealth.medserve.extension.ExtendedSubstance; import au.gov.digitalhealth.medserve.extension.MedicationParentExtension; import au.gov.digitalhealth.medserve.extension.ParentExtendedElement; import au.gov.digitalhealth.medserve.extension.SubsidyExtension; import au.gov.digitalhealth.medserve.server.indexbuilder.constants.FieldNames; import au.gov.digitalhealth.medserve.server.indexbuilder.constants.ResourceTypes; import au.gov.digitalhealth.medserve.transform.processor.MedicationResourceProcessor; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.parser.IParser; public class IndexBuildingResourceProcessor implements MedicationResourceProcessor { private IndexWriter writer; private IParser parser; private Map<String, CodeableConcept> formCache = new HashMap<>(); private Map<String, Set ingredientCache = new HashMap<>(); public IndexBuildingResourceProcessor(File outputDirectory) throws IOException { parser = FhirContext.forDstu3().newJsonParser(); parser.setPrettyPrint(false); Directory dir = FSDirectory.open(outputDirectory.toPath()); Analyzer analyzer = CustomAnalyzer.builder() .withTokenizer(WhitespaceTokenizerFactory.class) .addTokenFilter(LowerCaseFilterFactory.class) .build(); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE); this.writer = new IndexWriter(dir, iwc); } @Override public void processResources(List<? extends Resource> resources) throws IOException { for (Resource resource : resources) { Document document = new Document(); document.add(new StringField(FieldNames.ID, resource.getId(), Store.YES)); document.add( new StringField(FieldNames.RESOURCE_TYPE, resource.getResourceType().name().toLowerCase(), Store.NO)); String text = ((DomainResource) resource).getText().getDiv().allText(); document.add(new TextField(FieldNames.DISPLAY, text, Store.NO)); if (resource instanceof ExtendedMedication) { indextMedicationResource(resource, document); } else if (resource instanceof Substance) { ExtendedSubstance substance = ExtendedSubstance.class.cast(resource); document.add( new StringField(FieldNames.STATUS, substance.getStatus().toCode(), Store.NO)); document.add( new StringField(FieldNames.LAST_MODIFIED, substance.getLastModified().asStringValue(), Store.NO)); indexCodeableConcept(document, substance.getCode(), FieldNames.CODE); } else if (resource instanceof Organization) { document.add(new StringField(FieldNames.STATUS, "active", Store.NO)); } else { throw new RuntimeException("Unknown resource type " + resource.getClass().getCanonicalName()); } document.add(new StoredField(FieldNames.JSON, parser.encodeResourceToString(resource))); writer.addDocument(document); } writer.commit(); } private void indextMedicationResource(Resource resource, Document document) { ExtendedMedication medication = ExtendedMedication.class.cast(resource); document.add( new StringField(FieldNames.STATUS, medication.getStatus().toCode(), Store.NO)); document.add( new StringField(FieldNames.LAST_MODIFIED, medication.getLastModified().asStringValue(), Store.NO)); indexCodeableConcept(document, medication.getCode(), FieldNames.CODE); document.add(new StringField(FieldNames.MEDICATION_RESOURCE_TYPE, medication.getMedicationResourceType().getCode(), Store.NO)); indexParents(document, medication, FieldNames.ANCESTOR); indexParents(document, medication, FieldNames.PARENT); if (medication.hasIsBrand()) { document.add(new StringField(FieldNames.IS_BRAND, Boolean.toString(medication.getIsBrand()), Store.NO)); if (medication.getBrand() != null) { indexCodeableConcept(document, medication.getBrand(), FieldNames.BRAND); } } if (medication.getForm() != null && !medication.getForm().isEmpty()) { indexCodeableConcept(document, medication.getForm(), FieldNames.FORM); formCache.put(resource.getId(), medication.getForm()); } if (medication.getIngredient() != null && !medication.getIngredient().isEmpty()) { for (MedicationIngredientComponent ingredient : medication.getIngredient()) { try { indexReference(document, ingredient.getItemReference(), FieldNames.INGREDIENT, ResourceTypes.SUBSTANCE_RESOURCE_TYPE_VALUE); cacheIngredient(resource.getId(), ingredient.getItemReference()); } catch (FHIRException e) { throw new RuntimeException("Cannot get reference for ingredient " + ingredient); } } document.add(new IntPoint(FieldNames.INGREDIENT_COUNT, medication.getIngredient().size())); } if (medication.getPackage() != null) { if (medication.getPackage().getContainer() != null && !medication.getPackage().getContainer().isEmpty()) { indexCodeableConcept(document, medication.getPackage().getContainer(), FieldNames.CONTAINER); } if (medication.getPackage().getContent() != null && !medication.getPackage().getContent().isEmpty()) { Set distinctIngredientSet = new HashSet<>(); for (MedicationPackageContentComponent content : medication.getPackage().getContent()) { try { indexReference(document, content.getItemReference(), FieldNames.PACKAGE_ITEM, ResourceTypes.MEDICATION_RESOURCE_TYPE_VALUE); indexCodeableConcept(document, formCache.get(getIdFromReference(content.getItemReference(), ResourceTypes.MEDICATION_RESOURCE_TYPE_VALUE)), FieldNames.FORM); formCache.put(resource.getId(), formCache.get(getIdFromReference(content.getItemReference(), ResourceTypes.MEDICATION_RESOURCE_TYPE_VALUE))); Set ingredientSet = ingredientCache.get(getIdFromReference(content.getItemReference(), ResourceTypes.MEDICATION_RESOURCE_TYPE_VALUE)); distinctIngredientSet .addAll(ingredientSet.stream().map(r -> r.getId()).collect(Collectors.toSet())); for (Reference ingredientReference : ingredientSet) { indexReference(document, ingredientReference, FieldNames.INGREDIENT, ResourceTypes.SUBSTANCE_RESOURCE_TYPE_VALUE); cacheIngredient(resource.getId(), ingredientReference); } } catch (FHIRException e) { throw new RuntimeException("Cannot get reference for package-item " + content); } } document.add(new IntPoint(FieldNames.INGREDIENT_COUNT, distinctIngredientSet.size())); } } if (medication.hasManufacturer()) { try { indexReference(document, medication.getManufacturer(), FieldNames.MANUFACTURER, ResourceTypes.ORGANIZATION_RESOURCE_TYPE_VALUE); } catch (FHIRException e) { throw new RuntimeException("Can't get manufacturer for meducation " + medication.getId()); } } if (medication.getSubsidies() != null && !medication.getSubsidies().isEmpty()) { for (SubsidyExtension subsidy : medication.getSubsidies()) { indexCoding(document, FieldNames.SUBSIDY_CODE, subsidy.getSubsidyCode()); } } } private void cacheIngredient(String id, Reference itemReference) { Set ingredients = ingredientCache.get(id); if (ingredients == null) { ingredients = new HashSet<>(); ingredientCache.put(id, ingredients); } if (!ingredients.stream().anyMatch(r -> r.getReference().equals(itemReference.getReference()))) { ingredients.add(itemReference); } } private void indexParents(Document document, ParentExtendedElement medication, String fieldName) { for (MedicationParentExtension parent : medication.getParentMedicationResources()) { try { indexReference(document, parent.getParentMedication(), fieldName, ResourceTypes.MEDICATION_RESOURCE_TYPE_VALUE); if (fieldName.equals(FieldNames.ANCESTOR)) { indexParents(document, parent, fieldName); } } catch (FHIRException e) { throw new RuntimeException("Cannot get reference for medication abstraction " + parent, e); } } } private void indexReference(Document document, Reference reference, String fieldName, String referenceType) throws FHIRException { document.add(new StringField(fieldName, getIdFromReference(reference, referenceType), Store.NO)); document.add(new TextField(fieldName + FieldNames.TEXT_FIELD_SUFFIX, reference.getDisplay(), Store.NO)); } private String getIdFromReference(Reference reference, String referenceType) { return reference.getReference().replace(referenceType + "/", ""); } private void indexCodeableConcept(Document document, CodeableConcept codableConcept, String fieldName) { for (Coding code : codableConcept.getCoding()) { indexCoding(document, fieldName, code); } if (codableConcept.getText() != null && !codableConcept.getText().isEmpty()) { document.add(new TextField(fieldName + FieldNames.TEXT_FIELD_SUFFIX, codableConcept.getText(), Store.NO)); } } private void indexCoding(Document document, String fieldName, Coding code) { document.add(new StringField(fieldName, code.getCode() + "|" + code.getSystem(), Store.NO)); if (code.getDisplay() != null && !code.getDisplay().isEmpty()) { document.add(new TextField(fieldName + FieldNames.TEXT_FIELD_SUFFIX, code.getDisplay(), Store.NO)); } } }
java
20
0.664231
118
48.063745
251
starcoderdata
package com.englishtown.promises.integration; import com.englishtown.promises.Deferred; import com.englishtown.promises.Done; import com.englishtown.promises.Fail; import com.englishtown.promises.Promise; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.assertEquals; /** * Integration test for when.race() */ public class RaceTest extends AbstractIntegrationTest { private Sentinel sentinel = new Sentinel(); private Throwable reason = new RuntimeException(); private Promise never; private Promise fulfilled; private Promise rejected; private Done done = new Done<>(); private Fail fail = new Fail<>(); @Override public void setUp() throws Exception { super.setUp(); never = helper.never(); fulfilled = when.resolve(sentinel); rejected = when.reject(reason); } @Test public void testRace_should_return_empty_race_for_length_0() throws Exception { assertEquals(never, when.race(new ArrayList<>())); } @Test public void testRace_should_be_identity_for_length_1_when_fulfilled_via_promise() throws Exception { when.race(Collections.singletonList(fulfilled)) . -> { assertEquals(sentinel, x); return null; }) .then(done.onFulfilled, done.onRejected); done.assertFulfilled(); } @Test public void testRace_should_be_identity_for_length_1_when_rejected() throws Exception { when.race(Collections.singletonList(rejected)) .then(fail.onFulfilled, x -> { assertEquals(reason, x); return null; }).then(done.onFulfilled, done.onRejected); done.assertFulfilled(); } @Test public void testRace_should_be_commutative_when_fulfilled() throws Exception { when.race(Arrays.asList(fulfilled, never)) . -> { return when.race(Arrays.asList(never, fulfilled)) .then(y -> { assertEquals(x, y); return null; }); }).then(done.onFulfilled, done.onRejected); done.assertFulfilled(); } @Test public void testRace_should_be_commutative_when_rejected() throws Exception { when.race(Arrays.asList(rejected, never)) .then(fail.onFulfilled, x -> { return when.race(Arrays.asList(never, rejected)).then(fail.onFulfilled, y -> { assertEquals(x, y); return null; }); }).then(done.onFulfilled, done.onRejected); done.assertFulfilled(); } @Test public void testRace_should_fulfill_when_winner_fulfills() throws Exception { Deferred d1 = when.defer(); Deferred d2 = when.defer(); when.race(Arrays.asList(d1.getPromise(), d2.getPromise(), fulfilled)) .then(x -> { assertEquals(sentinel, x); return null; }, fail.onRejected) .then(done.onFulfilled, done.onRejected); done.assertFulfilled(); } @Test public void testRace_should_reject_when_winner_rejects() throws Exception { Deferred d1 = when.defer(); Deferred d2 = when.defer(); when.race(Arrays.asList(d1.getPromise(), d2.getPromise(), rejected)) .then(fail.onFulfilled, x -> { assertEquals(reason, x); return null; }).then(done.onFulfilled, done.onRejected); done.assertFulfilled(); } }
java
19
0.583396
104
30.204724
127
starcoderdata
/* SPDX-License-Identifier: MIT * * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved. */ package device import ( "log" "os" ) // A Logger provides logging for a Device. // The functions are Printf-style functions. // They must be safe for concurrent use. // They do not require a trailing newline in the format. // If nil, that level of logging will be silent. type Logger struct { Verbosef func(format string, args ...interface{}) Errorf func(format string, args ...interface{}) } // Log levels for use with NewLogger. const ( LogLevelSilent = iota LogLevelError LogLevelVerbose ) // Function for use in Logger for discarding logged lines. func DiscardLogf(format string, args ...interface{}) {} // NewLogger constructs a Logger that writes to stdout. // It logs at the specified log level and above. // It decorates log lines with the log level, date, time, and prepend. func NewLogger(level int, prepend string) *Logger { logger := &Logger{DiscardLogf, DiscardLogf} logf := func(prefix string) func(string, ...interface{}) { // 使用标准log的接口 return log.New(os.Stdout, prefix+": "+prepend, log.Ldate|log.Ltime).Printf } if level >= LogLevelVerbose { // 设置debug级别 logger.Verbosef = logf("DEBUG") } if level >= LogLevelError { // 实现相关实例 logger.Errorf = logf("ERROR") } return logger }
go
15
0.711278
76
25.078431
51
starcoderdata
<?php /* file: php/getSocPick.php pvm: 9.5.2019 auth: desc: Updates users current societies */ header("Access-Control-Allow-Origin: * "); if(empty($_POST)) echo '{"status":"fail"}'; else { $userID = $_POST['userID']; $socID = $_POST['socID']; include ('dbConnect.php'); $sql = "INSERT INTO jasenyys(JasenID,YhdistysID) VALUES ($userID,$socID)"; if($conn->query($sql)===TRUE) echo '{"status":"ok"}'; else echo '{"status":"fail"}'; } ?>
php
11
0.603412
78
25.111111
18
starcoderdata
using System; using Newtonsoft.Json; namespace iovation.LaunchKey.Sdk.Transport.Domain { public class DirectoryV3TotpPostRequest { public DirectoryV3TotpPostRequest(string identifier) { Identifier = identifier; } [JsonProperty("identifier")] public string Identifier { get; } } }
c#
11
0.660668
60
21.941176
17
starcoderdata
// Copyright 2020 The VGC Developers // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/vgc/vgc/blob/master/COPYRIGHT // // 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. // Implementation Notes // -------------------- // // This is basically like a complex QSplitter allowing you to split and resize // in both directions. See the following for inspiration on how to implement // missing features: // // https://github.com/qt/qtbase/blob/5.12/src/widgets/widgets/qsplitter.cpp // #include #include #include namespace vgc { namespace widgets { PanelArea::PanelArea(QWidget* parent) : QFrame(parent) { layout_ = new QVBoxLayout(); layout_->setAlignment(Qt::AlignTop); setLayout(layout_); updateVisibility_(); } PanelArea::~PanelArea() { } widgets::Panel* PanelArea::addPanel(const QString& title, QWidget* widget) { // Create new panel. // Note: we need to set `this` as parent in the constructor (rather than // relying on layout->addWidget()), otherwise its toggleViewAction() won't // be initialized to the correct check-state. See comment in the // implementation of ToggleViewAction::ToggleViewAction(). widgets::Panel* panel = new widgets::Panel(title, widget, this); panels_.push_back(panel); // Listen to panel's visibility change connect(panel, &widgets::Panel::visibleToParentChanged, this, &PanelArea::onPanelVisibleToParentChanged_); // Add to layout and return layout_->addWidget(panel); updateVisibility_(); return panel; } widgets::Panel* PanelArea::panel(QWidget* widget) { if (widget) { for (widgets::Panel* panel: panels_) { if (panel->widget() == widget) { return panel; } } } return nullptr; } bool PanelArea::event(QEvent* event) { QEvent::Type type = event->type(); if (type == QEvent::ShowToParent || type == QEvent::HideToParent) { Q_EMIT visibleToParentChanged(); } return QFrame::event(event); } void PanelArea::onPanelVisibleToParentChanged_() { updateVisibility_(); } void PanelArea::updateVisibility_() { // Check whether any of the panels is visible bool hasVisibleChildren = false; for (widgets::Panel* panel: panels_) { if (panel->isVisibleTo(this)) { hasVisibleChildren = true; } } // Show this PanelArea if at least one panel is visible, and // hide this PanelArea if no more panels are visible. if (isVisibleTo(parentWidget()) != hasVisibleChildren) { setVisible(hasVisibleChildren); } } } // namespace widgets } // namespace vgc
c++
16
0.679392
110
27.767857
112
starcoderdata
package it.polimi.ingsw.common.models; import org.junit.jupiter.api.RepeatedTest; import java.security.SecureRandom; import static org.junit.jupiter.api.Assertions.*; class CellTest { @RepeatedTest(value = 100) void testCell() { SecureRandom rand = new SecureRandom(); Cell cell = Cell.Creator.withBounds("_ | ").color(Cell.Color.values()[rand.nextInt(Cell.Color.values().length)]).spawnPoint().create(); Cell cell1 = Cell.Creator.withBounds("| _").color(Cell.Color.values()[rand.nextInt(Cell.Color.values().length)]).create(); Cell cell2 = Cell.Creator.withBounds("||||").color(Cell.Color.values()[rand.nextInt(Cell.Color.values().length)]).spawnPoint().create(); AmmoCard ammoCard = new AmmoCard(AmmoCard.Type.values()[rand.nextInt(AmmoCard.Type.values().length)], AmmoCard.Color.values()[rand.nextInt(AmmoCard.Color.values().length)], AmmoCard.Color.values()[rand.nextInt(AmmoCard.Color.values().length)]); assertTrue(cell != null && cell1 != null && cell2 != null); cell1.setAmmoCard(ammoCard); assertNull(cell.getAmmoCard()); assertNull(cell2.getAmmoCard()); assertNotNull(cell1.getAmmoCard()); assertNotNull(cell.getBounds()); assertNotNull(cell.getColor()); cell1.removeAmmoCard(); assertNull(cell1.getAmmoCard()); assertFalse(cell1.isSpawnPoint()); assertTrue(cell.isSpawnPoint()); assertNotNull(cell.getColor().escape()); } }
java
15
0.670426
144
45.941176
34
starcoderdata
package com.legyver.utils.graphrunner; import com.legyver.core.exception.CoreException; import com.legyver.utils.graphrunner.ctx.shared.SharedMapCtx; /** * Command attached to a graph to be run on all nodes in that graph as soon as they meet the evaluable prerequisites * @param Current value associated with the graph node. See {@link SharedMapCtx} for an example where the value is a map common to all nodes but where getValue() only returns the value of that node. */ @FunctionalInterface public interface GraphExecutedCommand { /** * Command to execute on nodes in a graph * @param nodeName the name of the current node * @param object the value associated with the current node * @throws CoreException if the implementation throws a CoreException */ void execute(String nodeName, T object) throws CoreException; }
java
8
0.773697
203
43.421053
19
starcoderdata
import cv2 import numpy as np def alpha_blend(foreground, background, alpha): # foreground = cv2.imread("puppets.png") # background = cv2.imread("ocean.png") # alpha = cv2.imread("puppets_alpha.png") # Convert uint8 to float # print(type(foreground.dtype)) foreground = foreground.astype(float) background = background.astype(float) print(alpha.shape) alpha = cv2.cvtColor(alpha, cv2.COLOR_GRAY2BGR) # Normalize the alpha mask to keep intensity between 0 and 1 alpha = alpha.astype(float) / 255 # print(alpha.shape) # Multiply the foreground with the alpha matte foreground = cv2.multiply(alpha, foreground) # Multiply the background with ( 1 - alpha ) background = cv2.multiply(1.0 - alpha, background) # Add the masked foreground and background. outImage = cv2.add(foreground, background) return outImage / 255 def denoise(frame): frame = cv2.medianBlur(frame, 5) frame = cv2.GaussianBlur(frame, (5, 5), 0) return frame frame1 = cv2.imread('frame1.png') cap = cv2.VideoCapture('video1.avi') ret, frame = cap.read() cap2 = cv2.VideoCapture('video2.avi') ret2, frame2 = cap2.read() cap3 = cv2.VideoCapture('video3.avi') ret3, frame3 = cap3.read() frame_array = [] frame1 = cv2.imread("frame1.png") fps = 30.0 size = frame.shape size = (size[1], size[0]) print(size) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi', fourcc, fps, size) if not cap.isOpened: print('Unable to open: ') exit(0) ## [capture] backSub = cv2.createBackgroundSubtractorMOG2() kernel = np.ones((8, 8), np.uint8) while True: if (ret == None or ret2 == None or ret3 == None): break ret, frame = cap.read() ret2, frame2 = cap2.read() ret3, frame3 = cap3.read() if (frame is None or frame2 is None or frame3 is None): break ## [apply] # update the background model fgMask = backSub.apply(denoise(frame)) ## [apply] fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_OPEN, kernel) ret, fgMask = cv2.threshold(fgMask, 80, 255, cv2.THRESH_BINARY) fgMask = cv2.dilate(fgMask, None, iterations=2) fgMask2 = backSub.apply(denoise(frame2)) ## [apply] fgMask2 = cv2.morphologyEx(fgMask2, cv2.MORPH_OPEN, kernel) ret2, fgMask2 = cv2.threshold(fgMask2, 80, 255, cv2.THRESH_BINARY) fgMask2 = cv2.dilate(fgMask2, None, iterations=2) fgMask3 = backSub.apply(denoise(frame3)) ## [apply] fgMask3 = cv2.morphologyEx(fgMask3, cv2.MORPH_OPEN, kernel) ret, fgMask3 = cv2.threshold(fgMask3, 80, 255, cv2.THRESH_BINARY) fgMask3 = cv2.dilate(fgMask3, None, iterations=2) print(fgMask.dtype) image = alpha_blend(frame, frame1, fgMask) image = alpha_blend(frame2, image * 255, fgMask2) image = alpha_blend(frame3, image * 255, fgMask3) data = image * 255 img = np.uint8(data) out.write(img) ## [display_frame_number] # get the frame number and write it on the current frame cv2.rectangle(frame, (10, 2), (100, 20), (255, 255, 255), -1) cv2.putText(frame, str(cap.get(cv2.CAP_PROP_POS_FRAMES)), (15, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) ## [display_frame_number] ## [show] # show the current frame and the fg masks # cv2.imshow('Frame', frame) cv2.imshow('FG Mask', fgMask) ## [show] keyboard = cv2.waitKey(30) if keyboard == 'q' or keyboard == 27: break out.release() cap.release() cap2.release() cap3.release()
python
11
0.654514
71
28.016529
121
starcoderdata
using System; using System.Linq; using System.Collections.Generic; using UnityEngine; /* ***************************************************************************** * File: UnityMathExtensions.cs * Author: - Friday, September 26, 2014 * Description: * Unity extensions for math * * History: * Friday, September 26, 2014 - Created * ****************************************************************************/ /// /// Unity extensions for math /// public static class UnityMathExtensions { #region DistanceTo /// /// Returns the Vector3 distance between these two GameObjects /// /// <param name="go"> /// <param name="otherGO"> /// public static float DistanceTo(this GameObject go, GameObject otherGO) { return Vector3.Distance(go.transform.position, otherGO.transform.position); } /// /// Returns the Vecto3 distance between these two points /// /// <param name="go"> /// <param name="pos"> /// public static float DistanceTo(this GameObject go, Vector3 pos) { return Vector3.Distance(go.transform.position, pos); } /// /// Returns the Vecto3 distance between these two points /// /// <param name="start"> /// <param name="dest"> /// public static float DistanceTo(this Vector3 start, Vector3 dest) { return Vector3.Distance(start, dest); } /// /// Returns the Vecto3 distance between these two transforms /// /// <param name="start"> /// <param name="dest"> /// /// Suggested by: Vipsu /// Link: http://forum.unity3d.com/members/vipsu.138664/ /// public static float DistanceTo(this Transform start, Transform dest) { return Vector3.Distance(start.position, dest.position); } // DistanceTo #endregion #region Add /// /// Adds two Vector3s /// /// <param name="v3">source vector3 /// <param name="value">second vector3 /// /// Suggested by: aaro4130 /// Link: http://forum.unity3d.com/members/aaro4130.22011/ /// public static Vector3 Add(this Vector3 v3, Vector3 value) { return v3 + value; } /// /// Adds the values to a vector3 /// /// <param name="v3">source vector3 /// <param name="x"> /// <param name="y"> /// <param name="z"> /// /// Suggested by: aaro4130 /// Link: http://forum.unity3d.com/members/aaro4130.22011/ /// public static Vector3 Add(this Vector3 v3, float x, float y, float z) { return v3 + new Vector3(x, y, z); } // Add #endregion #region Subtract /// /// Subtracts two Vector3s /// /// <param name="v3">source vector3 /// <param name="value">second vector3 /// /// /// Suggested by: aaro4130 /// Link: http://forum.unity3d.com/members/aaro4130.22011/ /// public static Vector3 Subtract(this Vector3 v3, Vector3 value) { return v3 - value; } /// /// Subtracts the values from a vector 3 /// /// <param name="v3">source vector3 /// <param name="x"> /// <param name="y"> /// <param name="z"> /// /// /// Suggested by: aaro4130 /// Link: http://forum.unity3d.com/members/aaro4130.22011/ /// public static Vector3 Subtract(this Vector3 v3, float x, float y, float z) { return v3 - new Vector3(x, y, z); } // Subtract #endregion }
c#
11
0.568978
83
26.751724
145
starcoderdata
using CommandPattern.Core; using CommandPattern.Core.Contracts; namespace CommandPattern { public class StartUp { public static void Main(string[] args) { // var asd = typeof(string).GetCustomAttributes(); // var personType = typeof(Person); // typeof(StartUp).GetMethod("Main").Invoke(null, new object[] { "hi" }); // FieldInfo[] fInfo = personType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); // PropertyInfo pInfo = personType.GetProperty("Name"); ICommandInterpreter command = new CommandInterpreter(); IEngine engine = new Engine(command); engine.Run(); } } }
c#
14
0.585897
104
28.038462
26
starcoderdata
from pydantic.error_wrappers import ValidationError from pytest import raises from app.api.schemas import RecordCreate, RecordRead, RecordUpdate new_record = { "amount": 12.34, "title": "title", "description": "description", "happened_at": "2020-05-16T18:00:00", } def test_record_create_must_have_amount(): new_record_without_amount = {**new_record} del new_record_without_amount["amount"] with raises(ValidationError): RecordCreate(**new_record_without_amount) def test_record_update_has_no_required_args(): record_update = RecordUpdate() assert record_update.dict(exclude_unset=True) == {} def test_read_must_have_id(): with raises(ValidationError): RecordRead(**new_record) def test_record_title_must_be_shorter_than_51(): long_title = 51 * "a" with raises(ValidationError): RecordUpdate(title=long_title) def test_record_title_must_be_longer_than_2(): short_title = 2 * "a" with raises(ValidationError): RecordUpdate(title=short_title) def test_record_description_must_be_shorter_than_141(): long_description = 141 * "a" with raises(ValidationError): RecordUpdate(description=long_description) def test_record_amount_must_have_2_decimal_places(): amount = 12.345 with raises(ValidationError): RecordUpdate(amount=amount) def test_record_happened_at_must_have_datetime_format(): happened_at = "abc" with raises(ValidationError): RecordUpdate(happened_at=happened_at)
python
9
0.694426
66
25.293103
58
starcoderdata
<?php namespace App; use Illuminate\Database\Eloquent\Model; /** * @SWG\Definition( * definition="Vouchers", * @SWG\Property( * property="currency", * description="currency", * type="string" * ), * @SWG\Property( * property="value", * description="value", * type="number", * format="float" * ), * @SWG\Property( * property="max_value", * description="max_value", * type="number", * format="float" * ), * @SWG\Property( * property="expiry", * description="expiry", * type="string" * ), * @SWG\Property( * property="owner", * description="owner", * type="string" * ), * @SWG\Property( * property="is_percentage", * description="is_percentage", * type="boolean", * ), * @SWG\Property( * property="is_partial", * description="is_partial", * type="boolean", * ), * ) */ class Voucher extends Model { // }
php
6
0.455674
40
20.692308
52
starcoderdata
fn main() { let my_vector = vec![2, 5, 1, 0, 4, 3]; let sum_thread = thread::spawn(|| { expensive_sum(my_vector) }); // While the child thread is running, the main thread will also do some work for letter in vec!["a", "b", "c", "d", "e", "f"] { println!("Main thread: Letter {}", letter); pause_ms(200); } let sum = sum_thread.join().unwrap(); println!("The child thread's expensive sum is {}", sum); let (tx, rx) = channel::unbounded(); // Cloning a channel makes another variable connected to that end of the // channel so that you can send it to another thread. let tx2 = tx.clone(); let handle_a = thread::spawn(move || { pause_ms(0); tx2.send("Thread A: 1").unwrap(); pause_ms(300); tx2.send("Thread A: 2").unwrap(); }); let handle_b = thread::spawn(move || { pause_ms(0); tx.send("Thread B: 1").unwrap(); pause_ms(100); tx.send("Thread B: 2").unwrap(); }); // Using a Receiver channel as an iterator is a convenient way to get values until the channel // gets closed. A Receiver channel is automatically closed once all Sender channels have been // closed. Both our threads automatically close their Sender channels when they exit and the // destructors for the channels get automatically called. for msg in rx { println!("Main thread: Received {}", msg); } // Join the child threads for good hygiene. handle_a.join().unwrap(); handle_b.join().unwrap(); // Challenge: Make two child threads and give them each a receiving end to a channel. From the // main thread loop through several values and print each out and then send it to the channel. // On the child threads print out the values you receive. Close the sending side in the main // thread by calling `drop(tx)` (assuming you named your sender channel variable `tx`). Join // the child threads. let (t, r) = channel::unbounded(); let r2 = r.clone(); let handle1 = thread::spawn(move || { for msg in r { println!("Thread 1: {}", msg); } }); let handle2 = thread::spawn(move || { for msg in r2 { println!("Thread 2: {}", msg); } }); for val in 1..=10 { println!("Sending {}", val); t.send(val).unwrap(); } drop(t); handle1.join().unwrap(); handle2.join().unwrap(); println!("Main thread: Exiting.") }
rust
15
0.588494
99
32.386667
75
inline
<?php namespace App\Services; use App\Models\User; class UserService { /** * This function returns the user detail * @param $userId * @return object */ public static function getUserData($userId) { return User::findOrFail($userId); } }
php
10
0.635802
47
14.428571
21
starcoderdata
public ServletResourceProvider create(ServiceReference ref) { Set<String> pathSet = new HashSet<String>(); // check whether explicit paths are set addByPath(pathSet, ref); // now, we handle resource types, extensions and methods addByType(pathSet, ref); if (pathSet.isEmpty()) { if (log.isDebugEnabled()) { log.debug("create({}): ServiceReference has no registration settings, ignoring", getServiceIdentifier(ref)); } return null; } if (log.isDebugEnabled()) { log.debug("create({}): Registering servlet for paths {}", getServiceIdentifier(ref), pathSet); } return new ServletResourceProvider(pathSet); }
java
12
0.609043
124
43.294118
17
inline
private void cleanUp(Object oldVO, Object newVO) { try { final Method m = getClass().getMethod("cleanUp", oldVO.getClass(), newVO.getClass()); m.invoke(this, oldVO, newVO); } catch (NoSuchMethodException ex) { // no clean up needed! } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
12
0.572496
78
40.875
16
inline
public static AnimationDrawable runKeyframeAnimation(Activity act, int viewId, int animationFile) { // Find View by its id attribute ImageView theView = (ImageView) act.findViewById(viewId); theView.setBackgroundResource(animationFile); AnimationDrawable theAnimation = (AnimationDrawable) theView.getBackground(); theAnimation.start(); return theAnimation; }
java
8
0.789894
100
40.888889
9
inline
// The code is from https://www.w3schools.com/howto/howto_js_slideshow.asp try { carousel(); } catch (error) { console.error(error); } var myIndex = 0; function carousel() { var i; var x = document.getElementsByClassName("mySlides"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } myIndex++; if (myIndex > x.length) {myIndex = 1} x[myIndex-1].style.display = "block"; setTimeout(carousel, 2500); } //////////////////////////////////////////// //The code is from https://www.w3schools.com/howto/howto_js_navbar_sticky.asp window.onscroll = function() {stickynavbar()}; var navbar = document.getElementById("site-navigation"); var sticky = navbar.offsetTop; function stickynavbar() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky-nav") } else { navbar.classList.remove("sticky-nav"); } } ////////////////////////////////////////////
javascript
10
0.59695
77
26.029412
34
starcoderdata
package org.talend.logging.audit.impl; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import org.talend.logging.audit.LogAppenders; /** * */ public class AuditConfigurationMapImpl extends EnumMap<AuditConfiguration, Object> implements AuditConfigurationMap { public AuditConfigurationMapImpl() { super(AuditConfiguration.class); } public AuditConfigurationMapImpl(AuditConfigurationMap map) { super(map); } private static String getAppenderName(String configName) { final String appenderPrefix = "APPENDER_"; if (!configName.startsWith(appenderPrefix)) { return null; } final int nameStart = appenderPrefix.length(); final int nameEnd = configName.indexOf('_', nameStart); if (nameEnd == -1) { return null; } return configName.substring(nameStart, nameEnd); } public void validateConfiguration() { List missingFields = null; LogAppendersSet appenders = getValue(AuditConfiguration.LOG_APPENDER, LogAppendersSet.class); if (appenders == null || appenders.isEmpty()) { throw new IllegalArgumentException("List of appenders is not configured"); } for (AuditConfiguration conf : AuditConfiguration.values()) { if (!isValid(conf)) { String appenderName = getAppenderName(conf.name()); if (appenderName != null && !appenders.contains(LogAppenders.valueOf(appenderName))) { // don't validate appenders which are not configured continue; } if (missingFields == null) { missingFields = new ArrayList<>(); } missingFields.add(conf.toString()); } } if (missingFields != null && !missingFields.isEmpty()) { throw new IllegalArgumentException("These mandatory audit logging properties were not configured: " + missingFields); } } public String getString(AuditConfiguration config) { return getValue(config, String.class); } public Integer getInteger(AuditConfiguration config) { return getValue(config, Integer.class); } public Long getLong(AuditConfiguration config) { return getValue(config, Long.class); } public Boolean getBoolean(AuditConfiguration config) { return getValue(config, Boolean.class); } public boolean isValid(AuditConfiguration config) { return (getValue(config) != null || config.canBeNull()); } public Object getValue(AuditConfiguration config) { return containsKey(config) ? get(config) : config.getDefaultValue(); } public T getValue(AuditConfiguration config, Class clz) { if (!config.getClz().equals(clz)) { throw new IllegalArgumentException("Wrong class type " + clz.getName() + ", expected " + config.getClz().getName()); } Object value = getValue(config); if (value == null && !config.canBeNull()) { throw new IllegalStateException( "Value for property " + config.toString() + " is not set and it has no default value"); } return clz.cast(value); } public void setValue(AuditConfiguration config, T value, Class<? extends T> clz) { if (!config.getClz().equals(clz)) { throw new IllegalArgumentException("Wrong class type " + clz.getName() + ", expected " + config.getClz().getName()); } if (containsKey(config)) { throw new IllegalStateException("Parameter " + config.toString() + " cannot be set twice"); } put(config, value); } }
java
17
0.627931
129
33.121739
115
starcoderdata
from nmigen import * class UpCounter(Elaboratable): """ A 16-bit up counter with a fixed limit. Parameters ---------- limit : int The value at which the counter overflows. Attributes ---------- en : Signal, in The counter is incremented if ``en`` is asserted, and retains its value otherwise. ovf : Signal, out ``ovf`` is asserted when the counter reaches its limit. """ def __init__(self, limit): self.limit = limit # Ports self.en = Signal() self.ovf = Signal() # State self.count = Signal(16) def elaborate(self, platform): m = Module() m.d.comb += self.ovf.eq(self.count == self.limit) with m.If(self.en): with m.If(self.ovf): m.d.sync += self.count.eq(0) with m.Else(): m.d.sync += self.count.eq(self.count + 1) return m # --- TEST --- from nmigen.sim import Simulator dut = UpCounter(25) def bench(): # Disabled counter should not overflow. yield dut.en.eq(0) for _ in range(30): yield assert not (yield dut.ovf) # Once enabled, the counter should overflow in 25 cycles. yield dut.en.eq(1) for _ in range(25): yield assert not (yield dut.ovf) yield assert (yield dut.ovf) # The overflow should clear in one cycle. yield assert not (yield dut.ovf) sim = Simulator(dut) sim.add_clock(1e-6) # 1 MHz sim.add_sync_process(bench) with sim.write_vcd("up_counter.vcd"): sim.run() # --- CONVERT --- from nmigen.back import verilog top = UpCounter(25) with open("up_counter.v", "w") as f: f.write(verilog.convert(top, ports=[top.en, top.ovf]))
python
15
0.57021
69
21.265823
79
starcoderdata
package com.cs4374.finalproject.controllers; import com.cs4374.finalproject.dataTransferObject.LoginRequest; import com.cs4374.finalproject.dataTransferObject.RegisterRequest; import com.cs4374.finalproject.services.AuthService; import com.cs4374.finalproject.services.AuthenticationResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired private AuthService authService; // Here is where we create new users. This endpoint is to create users @PostMapping("/signup") public ResponseEntity signup(@RequestBody RegisterRequest registerRequest){ System.out.println(registerRequest); authService.signup(registerRequest); // This will return status code 200 for our api return new ResponseEntity(HttpStatus.OK); } // Once a user account has been created then we want to be able to // authenticate these users. @PostMapping("/login") public AuthenticationResponse login(@RequestBody LoginRequest loginRequest){ return authService.login(loginRequest); } }
java
9
0.774319
80
34.694444
36
starcoderdata
/* Copyright (c) 2017 - 2019 LiteSpeed Technologies Inc. See LICENSE. */ #ifndef LSQUIC_PARSE_H #define LSQUIC_PARSE_H 1 #include #include "lsquic_packet_common.h" struct lsquic_packet_in; struct lsquic_packet_out; struct packin_parse_state; struct stream_frame; enum packet_out_flags; #define LSQUIC_PARSE_ACK_TIMESTAMPS 0 typedef struct ack_info { unsigned n_timestamps; /* 0 to 255 */ unsigned n_ranges; /* This is at least 1 */ /* Largest acked is ack_info.ranges[0].high */ lsquic_time_t lack_delta; struct lsquic_packno_range ranges[256]; #if LSQUIC_PARSE_ACK_TIMESTAMPS struct { /* Currently we just read these timestamps in (assuming it is * compiled in, of course), but do not do anything with them. * When we do, the representation of these fields should be * switched to whatever is most appropriate/efficient. */ unsigned char packet_delta; uint64_t delta_usec; } timestamps[255]; #endif } ack_info_t; struct short_ack_info { unsigned sai_n_timestamps; lsquic_time_t sai_lack_delta; struct lsquic_packno_range sai_range; }; #define largest_acked(acki) (+(acki)->ranges[0].high) #define smallest_acked(acki) (+(acki)->ranges[(acki)->n_ranges - 1].low) /* gaf_: generate ACK frame */ struct lsquic_packno_range; typedef const struct lsquic_packno_range * (*gaf_rechist_first_f) (void *rechist); typedef const struct lsquic_packno_range * (*gaf_rechist_next_f) (void *rechist); typedef lsquic_time_t (*gaf_rechist_largest_recv_f) (void *rechist); /* gsf_: generate stream frame */ typedef size_t (*gsf_read_f) (void *stream, void *buf, size_t len, int *fin); /* This structure contains functions that parse and generate packets and * frames in version-specific manner. To begin with, there is difference * between GQUIC's little-endian (Q038 and lower) and big-endian formats * (Q039 and higher). Q044 uses different format for packet headers. */ struct parse_funcs { /* Return buf length */ int (*pf_gen_reg_pkt_header) (const struct lsquic_conn *, const struct lsquic_packet_out *, unsigned char *, size_t); void (*pf_parse_packet_in_finish) (struct lsquic_packet_in *packet_in, struct packin_parse_state *); enum QUIC_FRAME_TYPE (*pf_parse_frame_type) (unsigned char); /* Return used buffer length or a negative value if there was not enough * room to write the stream frame. In the latter case, the negative of * the negative return value is the number of bytes required. The * exception is -1, which is a generic error code, as we always need * more than 1 byte to write a STREAM frame. */ int (*pf_gen_stream_frame) (unsigned char *buf, size_t bufsz, uint32_t stream_id, uint64_t offset, int fin, size_t size, gsf_read_f, void *stream); int (*pf_parse_stream_frame) (const unsigned char *buf, size_t rem_packet_sz, struct stream_frame *); int (*pf_parse_ack_frame) (const unsigned char *buf, size_t buf_len, ack_info_t *ack_info); int (*pf_gen_ack_frame) (unsigned char *outbuf, size_t outbuf_sz, gaf_rechist_first_f, gaf_rechist_next_f, gaf_rechist_largest_recv_f, void *rechist, lsquic_time_t now, int *has_missing, lsquic_packno_t *largest_received); int (*pf_gen_stop_waiting_frame) (unsigned char *buf, size_t buf_len, lsquic_packno_t cur_packno, enum lsquic_packno_bits, lsquic_packno_t least_unacked_packno); int (*pf_parse_stop_waiting_frame) (const unsigned char *buf, size_t buf_len, lsquic_packno_t cur_packno, enum lsquic_packno_bits, lsquic_packno_t *least_unacked); int (*pf_skip_stop_waiting_frame) (size_t buf_len, enum lsquic_packno_bits); int (*pf_gen_window_update_frame) (unsigned char *buf, int buf_len, uint32_t stream_id, uint64_t offset); int (*pf_parse_window_update_frame) (const unsigned char *buf, size_t buf_len, uint32_t *stream_id, uint64_t *offset); int (*pf_gen_blocked_frame) (unsigned char *buf, size_t buf_len, uint32_t stream_id); int (*pf_parse_blocked_frame) (const unsigned char *buf, size_t buf_len, uint32_t *stream_id); int (*pf_gen_rst_frame) (unsigned char *buf, size_t buf_len, uint32_t stream_id, uint64_t offset, uint32_t error_code); int (*pf_parse_rst_frame) (const unsigned char *buf, size_t buf_len, uint32_t *stream_id, uint64_t *offset, uint32_t *error_code); int (*pf_gen_connect_close_frame) (unsigned char *buf, int buf_len, uint32_t error_code, const char *reason, int reason_len); int (*pf_parse_connect_close_frame) (const unsigned char *buf, size_t buf_len, uint32_t *error_code, uint16_t *reason_length, uint8_t *reason_offset); int (*pf_gen_goaway_frame) (unsigned char *buf, size_t buf_len, uint32_t error_code, uint32_t last_good_stream_id, const char *reason, size_t reason_len); int (*pf_parse_goaway_frame) (const unsigned char *buf, size_t buf_len, uint32_t *error_code, uint32_t *last_good_stream_id, uint16_t *reason_length, const char **reason); int (*pf_gen_ping_frame) (unsigned char *buf, int buf_len); #ifndef NDEBUG /* These float reading and writing functions assume `mem' has at least * 2 bytes. */ void (*pf_write_float_time16) (lsquic_time_t time_us, void *mem); uint64_t (*pf_read_float_time16) (const void *mem); #endif size_t (*pf_calc_stream_frame_header_sz) (uint32_t stream_id, uint64_t offset); void (*pf_turn_on_fin) (unsigned char *); size_t (*pf_packout_size) (const struct lsquic_conn *, const struct lsquic_packet_out *); size_t (*pf_packout_header_size) (const struct lsquic_conn *, enum packet_out_flags); }; extern const struct parse_funcs lsquic_parse_funcs_gquic_le; /* Q039 and later are big-endian: */ extern const struct parse_funcs lsquic_parse_funcs_gquic_Q039; extern const struct parse_funcs lsquic_parse_funcs_gquic_Q044; #define select_pf_by_ver(ver) ( \ ((1 << (ver)) & (1 << LSQVER_035)) \ ? &lsquic_parse_funcs_gquic_le \ : (ver) < LSQVER_044 \ ? &lsquic_parse_funcs_gquic_Q039 \ : &lsquic_parse_funcs_gquic_Q044) int lsquic_gquic_parse_packet_in_begin (struct lsquic_packet_in *, size_t length, int is_server, struct packin_parse_state *); int lsquic_iquic_parse_packet_in_long_begin (struct lsquic_packet_in *, size_t length, int is_server, struct packin_parse_state *state); int lsquic_iquic_parse_packet_in_short_begin (struct lsquic_packet_in *, size_t length, int is_server, struct packin_parse_state *state); enum QUIC_FRAME_TYPE parse_frame_type_gquic_Q035_thru_Q039 (unsigned char first_byte); size_t calc_stream_frame_header_sz_gquic (uint32_t stream_id, uint64_t offset); size_t lsquic_gquic_packout_size (const struct lsquic_conn *, const struct lsquic_packet_out *); size_t lsquic_gquic_packout_header_size (const struct lsquic_conn *conn, enum packet_out_flags flags); size_t lsquic_gquic_po_header_sz (enum packet_out_flags flags); /* This maps two bits as follows: * 00 -> 1 * 01 -> 2 * 10 -> 4 * 11 -> 6 * * Assumes that only two low bits are set. */ #define twobit_to_1246(bits) ((bits) * 2 + !(bits)) /* This maps two bits as follows: * 00 -> 1 * 01 -> 2 * 10 -> 4 * 11 -> 8 * * Assumes that only two low bits are set. */ #define twobit_to_1248(bits) (1 << (bits)) char * acki2str (const struct ack_info *acki, size_t *sz); void lsquic_turn_on_fin_Q035_thru_Q039 (unsigned char *); #endif
c
11
0.587251
81
36.974249
233
starcoderdata
void testCustomizedIterator(size_t skipped) { // iterator that skips on every #skipped# elems using Tag = NthBitChecker<NthBit>; using const_iterator = typename IterableTableTupleChunks<Chunks, Tag>::const_iterator; using iterator = typename IterableTableTupleChunks<Chunks, Tag>::iterator; MaskedStringGen<Tag> gen(skipped); Chunks alloc(TupleSize); array<void*, NumTuples> addresses; size_t i; for(i = 0; i < NumTuples; ++i) { addresses[i] = gen.fill(alloc.allocate()); assert(gen.same(addresses[i], i)); } i = 0; auto const& alloc_cref = alloc; fold<const_iterator>(alloc_cref, [&i, &addresses, skipped](void const* p) { if (i % skipped == 0) { ++i; } if (Chunks::Compact::value) { assert(p == addresses[i]); } ++i; }); assert(i == NumTuples); // Free all tuples via allocator. Note that allocator needs // to be aware the "emptiness" from the iterator POV, not // allocator's POV. // Note: see document on NonCompactingChunks to understand // why we cannot use iterator to free memories. Tag const tag; if (Chunks::Compact::value) { bool freed; TrackedDeleter<Chunks> deleter(alloc, freed); do { freed = false; try { for_each<iterator>(alloc, [&deleter, &tag](void* p) { assert(tag(p)); deleter(p); }); } catch (range_error const&) {} } while(freed); // Check using normal iterator (i.e. non-skipping one) that // the remains are what should be. fold<typename IterableTableTupleChunks<Chunks, truth>::const_iterator>( alloc_cref, [&tag](void const* p) { assert(! tag(p)); }); } else { // to free on compacting chunk safely, collect and free separately forward_list<void const*> crematorium; i = 0; fold<const_iterator>(alloc_cref, [&crematorium, &tag, &i](void const* p) { assert(tag(p)); crematorium.emplace_front(p); ++i; }); for_each(crematorium.begin(), crematorium.end(), [&alloc](void const*p) { alloc.free(const_cast<void*>(p)); }); // We should not check/free() the rest using // iterator, for much the same reason that we don't use // same iterator-delete pattern (i.e. for_each) as // compactible allocators. } }
c++
19
0.549674
98
39.75
64
inline
package com.healthy.gym.equipment.component; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class ImageUrlCreatorImpl implements ImageUrlCreator { private final Environment environment; public ImageUrlCreatorImpl(Environment environment) { this.environment = environment; } @Override public String createImageUrl(String imageId) { String gateway = environment.getRequiredProperty("gateway"); String service = environment.getRequiredProperty("spring.application.name"); String controller = "/image/" + imageId; return gateway + "/" + service + controller; } }
java
10
0.734957
84
29.347826
23
starcoderdata
/* * 作成日: 2003/11/13 * */ package com.nullfish.lib.vfs.manipulation.abst; import java.sql.SQLException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.nullfish.lib.vfs.VFile; import com.nullfish.lib.vfs.exception.VFSException; import com.nullfish.lib.vfs.exception.VFSIOException; import com.nullfish.lib.vfs.manipulation.GetChildrenManipulation; import com.nullfish.lib.vfs.tag_db.TagDataBase; /** * @author shunji * */ public abstract class AbstractGetChildrenManipulation extends AbstractManipulation implements GetChildrenManipulation { VFile[] children; /** * メッセージのパラメータ */ protected Object[] messageParam; /** * 経過フォーマット */ private MessageFormat progressFormat; public AbstractGetChildrenManipulation(VFile file) { super(file); messageParam = new String[1]; messageParam[0] = file.getSecurePath(); } /* (非 Javadoc) * @see com.sexyprogrammer.lib.vfs.manipulation.GetChildrenManipulation#getChildren() */ public VFile[] getChildren() { return children; } /* (非 Javadoc) * @see com.sexyprogrammer.lib.vfs.Manipulation#execute(com.sexyprogrammer.lib.vfs.VFSUser) */ public void doExecute() throws VFSException { children = doGetChildren(file); TagDataBase tagDataBase = file.getFileSystem().getVFS().getTagDataBase(); if(tagDataBase != null) { try { Map fileTagMap = tagDataBase.findTagsInDirectory(file); for(int i=0; i<children.length; i++) { List tags = (List) fileTagMap.get(children[i].getSecurePath()); tags = tags != null ? tags : new ArrayList(); children[i].setTagCache(tags); } } catch (SQLException e) { throw new VFSIOException(e); } } } public abstract VFile[] doGetChildren(VFile file) throws VFSException; /** * 作業経過メッセージを取得する。 * * @return */ public String getProgressMessage() { if(progressFormat == null) { progressFormat = new MessageFormat(progressMessages.getString(GetChildrenManipulation.NAME)); } return progressFormat.format(messageParam); } }
java
18
0.720539
96
22.1
90
starcoderdata
#include<iostream> #include <cmath> #include <algorithm> #include<cstdio> using namespace std; int main(){ int ary[20]={}; int spd[2]={}; while(scanf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",&ary[1],&ary[2],&ary[3],&ary[4],&ary[5],&ary[6],&ary[7],&ary[8],&ary[9],&ary[10],&spd[0],&spd[1])!=EOF){ for(int i=2;i<=10;i++){ ary[i]+=ary[i-1]; } double piy=(double)(ary[10]*spd[0])/(double)(spd[0]+spd[1]); int hog=ceil(piy); int res; for(int i=0;i<=10;i++){ if(hog<=ary[i]){ res=i; break; } } cout<<res<<endl; } return 0; }
c++
13
0.531532
155
19.592593
27
codenet
#include "drawer.h" #include #include #include #include class NewWidget; Drawer::Drawer(QWidget *parent, Qt::WindowFlags f) :QToolBox(parent,f) { setWindowTitle(tr("File Transport")); setWindowIcon(QPixmap(":" "images/FileTrans.png")); toolBtn1 = new QToolButton; toolBtn1->setText(tr("主机1")); toolBtn1->setIcon(QPixmap(":/images/images/user1.png")); toolBtn1->setIconSize(QPixmap(":/images/images/user1.png").size()); toolBtn1->setAutoRaise(true); toolBtn1->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); connect(toolBtn1,SIGNAL(clicked()),this,SLOT(showChatWidget1())); toolBtn2 = new QToolButton; toolBtn2->setText(tr("主机2")); toolBtn2->setIcon(QPixmap(":/images/images/user2.png")); toolBtn2->setIconSize(QPixmap(":/images/images/user2.png").size()); toolBtn2->setAutoRaise(true); toolBtn2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); connect(toolBtn2,SIGNAL(clicked()),this,SLOT(showChatWidget2())); toolBtn3 = new QToolButton; toolBtn3->setText(tr("主机3")); toolBtn3->setIcon(QPixmap(":/images/images/user3.png")); toolBtn3->setIconSize(QPixmap(":/images/images/user3.png").size()); toolBtn3->setAutoRaise(true); toolBtn3->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); connect(toolBtn3,SIGNAL(clicked()),this,SLOT(showChatWidget3())); toolBtn4 = new QToolButton; toolBtn4->setText(tr("主机4")); toolBtn4->setIcon(QPixmap(":/images/images/user4.png")); toolBtn4->setIconSize(QPixmap(":/images/images/user4.png").size()); toolBtn4->setAutoRaise(true); toolBtn4->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); connect(toolBtn4,SIGNAL(clicked()),this,SLOT(showChatWidget4())); QGroupBox *groupBox = new QGroupBox; QVBoxLayout *layout = new QVBoxLayout(groupBox); layout->setMargin(20); layout->setAlignment(Qt::AlignLeft); layout->addWidget(toolBtn1); layout->addWidget(toolBtn2); layout->addWidget(toolBtn3); layout->addWidget(toolBtn4); layout->addStretch(); this->addItem((QWidget*)groupBox,tr("主机列表")); } void Drawer::showChatWidget1(){ chatWidget1 = new Widget(0, toolBtn1->text()); chatWidget1->setWindowTitle(toolBtn1->text()); chatWidget1->setWindowIcon(toolBtn1->icon()); chatWidget1->show(); } void Drawer::showChatWidget2(){ chatWidget2 = new Widget(0, toolBtn2->text()); chatWidget2->setWindowTitle(toolBtn2->text()); chatWidget2->setWindowIcon(toolBtn2->icon()); chatWidget2->show(); } void Drawer::showChatWidget3(){ chatWidget3 = new Widget(0, toolBtn3->text()); chatWidget3->setWindowTitle(toolBtn3->text()); chatWidget3->setWindowIcon(toolBtn3->icon()); chatWidget3->show(); } void Drawer::showChatWidget4(){ chatWidget4 = new Widget(0, toolBtn4->text()); chatWidget4->setWindowTitle(toolBtn4->text()); chatWidget4->setWindowIcon(toolBtn4->icon()); chatWidget4->show(); }
c++
11
0.674271
71
33.077778
90
starcoderdata
#ifndef ODIN_CAMERA_HPP #define ODIN_CAMERA_HPP #include namespace odin { struct Camera { alignas(16) glm::vec3 origin; alignas(16) glm::vec3 lower_left_corner; alignas(16) glm::vec3 horizontal; alignas(16) glm::vec3 vertical; alignas(16) glm::vec3 u; alignas(16) glm::vec3 v; alignas(16) glm::vec3 w; alignas(16) float lens_radius; void init(glm::vec3 lookFrom, glm::vec3 lookAt, glm::vec3 vUp, float vfov, float aspect, float aperture, float focusDist) { lens_radius = aperture / 2.0f; glm::vec3 u, v, w; float theta = vfov * M_PI / 180.0f; float half_height = glm::tan(theta / 2.0f); float half_width = aspect * half_height; origin = lookFrom; w = glm::normalize(lookFrom - lookAt); u = glm::normalize(glm::cross(vUp, w)); v = glm::cross(w, u); lower_left_corner = origin - half_width * focusDist * u - half_height * focusDist * v - focusDist * w; horizontal = 2.0f * half_width * focusDist * u; vertical = 2.0f * half_height * focusDist * v; } }; } // namespace odin #endif // ODIN_CAMERA_HPP
c++
15
0.636364
76
31.111111
36
starcoderdata
package com.cherry.jeeves.utils.rest; import org.apache.http.client.CookieStore; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; //@Configuration public class HttpRestConfig { // @Bean public RestTemplate restTemplate() { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom().setRedirectsEnabled(false).build()); return new StatefullRestTemplate(httpContext); } }
java
10
0.798872
126
41.6
25
starcoderdata
@Override public boolean updateChange(ChangeContext ctx) throws OrmException, IOException { change = ctx.getChange(); // Use defensive copy created by ChangeControl. ReviewDb db = ctx.getDb(); ChangeControl ctl = ctx.getControl(); patchSetInfo = patchSetInfoFactory.get(ctx.getRevWalk(), commit, psId); ctx.getChange().setCurrentPatchSet(patchSetInfo); ChangeUpdate update = ctx.getUpdate(psId); update.setChangeId(change.getKey().get()); update.setSubjectForCommit("Create change"); update.setBranch(change.getDest().get()); update.setTopic(change.getTopic()); boolean draft = status == Change.Status.DRAFT; List<String> newGroups = groups; if (newGroups.isEmpty()) { newGroups = GroupCollector.getDefaultGroups(commit); } patchSet = psUtil.insert(ctx.getDb(), ctx.getRevWalk(), update, psId, commit, draft, newGroups, null); /* TODO: fixStatus is used here because the tests * (byStatusClosed() in AbstractQueryChangesTest) * insert changes that are already merged, * and setStatus may not be used to set the Status to merged * * is it possible to make the tests use the merge code path, * instead of setting the status directly? */ update.fixStatus(change.getStatus()); LabelTypes labelTypes = ctl.getProjectControl().getLabelTypes(); approvalsUtil.addReviewers(db, update, labelTypes, change, patchSet, patchSetInfo, reviewers, Collections.<Account.Id> emptySet()); approvalsUtil.addApprovals(db, update, labelTypes, patchSet, ctx.getControl(), approvals); if (message != null) { changeMessage = new ChangeMessage(new ChangeMessage.Key(change.getId(), ChangeUtil.messageUUID(db)), ctx.getAccountId(), patchSet.getCreatedOn(), patchSet.getId()); changeMessage.setMessage(message); cmUtil.addChangeMessage(db, update, changeMessage); } return true; }
java
13
0.690826
83
41
47
inline
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, // All rights reserved. // MIT License: https://opensource.org/licenses/mit-license.html // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // 3D math functions. // /////////////////////////////////////////////////////////////////////////////// #ifndef _USUL_MATH_3D_FUNCTIONS_H_ #define _USUL_MATH_3D_FUNCTIONS_H_ #include "Usul/Math/Line3.h" #include "Usul/Math/Vector3.h" // For Vector3 #include namespace Usul { namespace Math { /////////////////////////////////////////////////////////////////////////////// // // Unproject the screen point into a 3D point. // https://github.com/toji/gl-matrix // /////////////////////////////////////////////////////////////////////////////// template < class Vec3, class Vec4, class Matrix > inline bool unProject ( const Vec3 &screen, const Matrix &viewMatrix, const Matrix &projMatrix, const Vec4 &viewport, Vec3 &point ) { // Make sure they all have the same value type. typedef typename Matrix::value_type Number; static_assert ( std::is_same < Number, typename Vec3::value_type >::value, "Not the same value type" ); static_assert ( std::is_same < Number, typename Vec4::value_type >::value, "Not the same value type" ); // Make sure we're working with a floating point number type. static_assert ( std::is_floating_point < Number >::value, "Not a floating-point number type" ); // Keep the compiler happy. const Number zero ( static_cast < Number > ( 0 ) ); const Number one ( static_cast < Number > ( 1 ) ); const Number two ( static_cast < Number > ( 2 ) ); // Make the homogeneous, normalized point. // All three, x, y, and z, will be in the range [-1,1]. const Vec4 a ( ( screen[0] - viewport[0] ) * two / viewport[2] - one, ( screen[1] - viewport[1] ) * two / viewport[3] - one, two * screen[2] - one, one ); // Combine the view and projection matrices. const Matrix m = projMatrix * viewMatrix; // Get the inverse and handle when it does not exist. Matrix im; if ( false == Usul::Math::inverse ( m, im ) ) { return false; } // Transform the 4D point. const Vec4 b = Usul::Math::multiply ( im, a ); // Make sure it worked. if ( zero == b[3] ) { return false; } // Shortcut. const Number ib3 = one / b[3]; // Write to the answer. point[0] = b[0] * ib3; point[1] = b[1] * ib3; point[2] = b[2] * ib3; // It worked. return true; } /////////////////////////////////////////////////////////////////////////////// // // Make a 3D line from the 2D screen coordinate. // /////////////////////////////////////////////////////////////////////////////// template < class Number, class Vec4, class Matrix, class Line3 > inline bool makeLine ( const Number &x, const Number &y, const Matrix &viewMatrix, const Matrix &projMatrix, const Vec4 &viewport, Line3 &line ) { // Make sure they all have the same value type. static_assert ( std::is_same < Number, typename Vec4::value_type >::value, "Not the same value type" ); static_assert ( std::is_same < Number, typename Line3::value_type >::value, "Not the same value type" ); static_assert ( std::is_same < Number, typename Matrix::value_type >::value, "Not the same value type" ); // Make sure we're working with a floating point number type. static_assert ( std::is_floating_point < Number >::value, "Not a floating-point number type" ); // Typedefs. typedef Usul::Math::Vector3 < Number > Vec3; // Keep the compiler happy. const Number one ( static_cast < Number > ( 1 ) ); // Get the 3D point on the near plane. Vec3 nearPoint; if ( false == unProject ( Vec3 ( x, viewport[3] - y, -one ), viewMatrix, projMatrix, viewport, nearPoint ) ) { return false; } // Get the 3D point on the far plane. Vec3 farPoint; if ( false == unProject ( Vec3 ( x, viewport[3] - y, one ), viewMatrix, projMatrix, viewport, farPoint ) ) { return false; } // Set the line. line.set ( nearPoint, farPoint ); // It worked. return true; } } // namespace Math } // namespace Usul #endif // _USUL_MATH_3D_FUNCTIONS_H_
c
17
0.547279
110
27.526316
152
starcoderdata
def toxml(self): """Method serializes service operation to XML """ root = Element('operation') SubElement(root, 'service').text = str(self.service) if (self.customer != None): SubElement(root, 'customer').text = str(self.customer) if (self.payer != None): SubElement(root, 'payer').text = str(self.payer) if (self.subscriber != None): SubElement(root, 'subscriber').text = str(self.subscriber) if (self.status != None): SubElement(root, 'status').text = self.status elParams = SubElement(root, 'params') for key, value in self.params.items(): elParam = SubElement(elParams, 'entry') elem = SubElement(elParam, 'key') elem.text = str(key) elem = SubElement(elParam, 'value') elem.text = str(value) return root
python
11
0.552174
70
34.423077
26
inline
package com.deflatedpickle.justweight.common.config; import com.deflatedpickle.justweight.Reference; import com.deflatedpickle.justweight.common.util.ItemUtil; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; import java.util.HashMap; import java.util.Map; import java.util.Objects; @Mod.EventBusSubscriber(modid = Reference.MOD_ID) @Config(modid = Reference.MOD_ID, name = Reference.CONFIG_GENERAL, category = Configuration.CATEGORY_GENERAL) @Config.LangKey("config.justweight.general") public class ConfigHandler { @Config.Name("Item Config") @Config.Comment("Configure the weights of all the items") @Config.LangKey("config.justweight.configItem") public static final HashMap<String, Float> itemMap = new HashMap<>(); static { for (ModContainer mod : Loader.instance().getActiveModList()) { for (Item item : ForgeRegistries.ITEMS) { // itemMap.put(item.getTranslationKey(), ItemUtil.INSTANCE.determineItemWeight(new ItemStack(item))); } } } @SubscribeEvent public static void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.getModID().equals(Reference.MOD_ID)) { ConfigManager.sync(Reference.MOD_ID, Config.Type.INSTANCE); } } }
java
12
0.76024
117
39.688889
45
starcoderdata
package org.echocat.kata.java.part1.http; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class HttpParser { private static final Logger LOGGER = LoggerFactory.getLogger(HttpParser.class); private static final int SP = 0x20; private static final int CR = 0x80; private static final int LF = 0x8A; public void parseHttpRequest(InputStream is) throws IOException, HttpParsingException { InputStreamReader reader = new InputStreamReader(is, StandardCharsets.US_ASCII); HttpRequest httpRequest = new HttpRequest(); parseRequestLine(reader, httpRequest); parseHeaders(reader, httpRequest); parseBody(reader, httpRequest); } private void parseRequestLine(InputStreamReader reader, HttpRequest httpRequest) throws IOException, HttpParsingException { StringBuilder stringBuilder = new StringBuilder(); boolean methodParsed = false; boolean requestTarget = false; int _byte; while((_byte = reader.read())>=0){ if(_byte ==CR){ _byte = reader.read(); if(_byte == LF){ return; } } if(_byte==SP){ if(!methodParsed){ httpRequest.setMethod(stringBuilder.toString()); methodParsed = true; }else if(! requestTarget){ requestTarget= true; }else{ throw new HttpParsingException(HttpStatusCode.CLIENT_ERROR_400_BAD_REQUEST); } stringBuilder.delete(0,stringBuilder.length()); }else{ stringBuilder.append((char)_byte); if(!methodParsed){ if(stringBuilder.length()>HttpMethod.MAX_LENGTH){ throw new HttpParsingException(HttpStatusCode.CLIENT_ERROR_501_NOT_IMPLEMENTED); } } } } } private void parseBody(InputStreamReader reader, HttpRequest httpRequest) { } private void parseHeaders(InputStreamReader reader, HttpRequest httpRequest) { } }
java
17
0.606218
127
32.085714
70
starcoderdata
package de.tbressler.waterrower.subscriptions; import de.tbressler.waterrower.io.ConnectionListener; import de.tbressler.waterrower.io.IConnectionListener; import de.tbressler.waterrower.io.WaterRowerConnector; import de.tbressler.waterrower.io.msg.AbstractMessage; import de.tbressler.waterrower.log.Log; import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import static de.tbressler.waterrower.subscriptions.Priority.*; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * The implementation of the subscription polling service. * * @author * @version 1.0 */ public class SubscriptionPollingService implements ISubscriptionPollingService { /* The maximum size of messages in the queue. */ private static final int MESSAGE_QUEUE_SIZE = 20; /* The interval between two poll messages (in ms). */ private final long interval; /* List of subscriptions. */ private final List subscriptions = new CopyOnWriteArrayList<>(); /* The connector to the WaterRower. */ private final WaterRowerConnector connector; /* The executor service for polling of subscriptions. */ private final ScheduledExecutorService executorService; /* True if subscription polling is active. */ private final AtomicBoolean isActive = new AtomicBoolean(false); /* Counter for the polling cycles. */ private final AtomicLong pollCycle = new AtomicLong(0); /* Message queue for the current polling cycle. */ private final BlockingQueue messageQueue = new ArrayBlockingQueue<>(MESSAGE_QUEUE_SIZE, true); /* Listener for the connection to the WaterRower, which handles the received messages*/ private final IConnectionListener listener = new ConnectionListener() { @Override public void onMessageReceived(AbstractMessage msg) { // If not active skip execution. if (!isActive.get()) return; for(ISubscription subscription : subscriptions) { subscription.handle(msg); } } }; /** * The subscription polling manager. * * @param connector The connector to the WaterRower, must not be null. * @param executorService The executor service for the subscription polling, must not be null. * @param interval The interval between messages, must not be null. * Recommended = 200 ms. */ public SubscriptionPollingService(WaterRowerConnector connector, ScheduledExecutorService executorService, Duration interval) { this.interval = requireNonNull(interval).toMillis(); this.connector = requireNonNull(connector); this.connector.addConnectionListener(listener); this.executorService = requireNonNull(executorService); } /** * Start the subscription polling service. */ @Override public void start() { Log.debug("Start subscription polling service."); isActive.set(true); collectMessagesForNextPollingInterval(); scheduleSendMessageTask(); } /* Collect messages from the current subscriptions for polling. */ private void collectMessagesForNextPollingInterval() { // If not active skip execution. if (!isActive.get()) return; Log.debug("Schedule polling for "+subscriptions.size()+" subscription(s)..."); long cycle = pollCycle.getAndIncrement(); boolean pollMedium = cycle % 2 == 0; boolean pollLow = cycle % 5 == 0; for (ISubscription subscription : subscriptions) { if ((subscription.getPriority() == NO_POLLING) || (subscription.getPriority() == MEDIUM && !pollMedium) || (subscription.getPriority() == LOW && !pollLow)) continue; AbstractMessage msg = subscription.poll(); boolean addedToQueue = messageQueue.offer(msg); // If the message couldn't be added to queue, show a warning. This is the case // when too many subscriptions are subscribed. The size of the queue = MESSAGE_QUEUE_SIZE. if (!addedToQueue) { Log.warn("Can not add more messages, the message queue is full! Skipping remaining messages in current cycle."); return; } } } /* Schedule the send task for execution. */ private void scheduleSendMessageTask() { executorService.schedule(() -> sendNextMessage(), interval, MILLISECONDS); } /* Send the first message from the message queue to the WaterRower. */ private void sendNextMessage() { try { // If not active skip execution. if (!isActive.get()) return; AbstractMessage msg = messageQueue.poll(); if (msg != null) { Log.debug("Send scheduled polling message >" + msg.toString() + "<"); connector.send(msg); } } catch (IOException e) { Log.error("Couldn't send polling message due to an error!", e); } if (messageQueue.isEmpty()) collectMessagesForNextPollingInterval(); scheduleSendMessageTask(); } /** * Stop the subscription polling service. */ @Override public void stop() { Log.debug("Stop subscription polling service."); isActive.set(false); } /** * Subscribe to data/events. This will start the polling for the given data. * * @param subscription The subscription and callback, must not be null. */ @Override public void subscribe(ISubscription subscription) { subscriptions.add(requireNonNull(subscription)); Log.debug("Added subscription: " + subscription); } /** * Unsubscribe from data/events. This will stop the polling for the given data. * * @param subscription The subscription, must not be null. */ @Override public void unsubscribe(ISubscription subscription) { subscriptions.remove(requireNonNull(subscription)); Log.debug("Removed subscription: " + subscription); } }
java
16
0.661335
131
30.710145
207
starcoderdata
/* Copyright 2018 OpenEBS Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package probe import ( "k8s.io/klog" "github.com/openebs/node-disk-manager/cmd/ndm_daemonset/controller" libudevwrapper "github.com/openebs/node-disk-manager/pkg/udev" ) // EventAction action type for disk events like attach or detach events type EventAction string const ( // AttachEA is attach disk event name AttachEA EventAction = libudevwrapper.UDEV_ACTION_ADD // DetachEA is detach disk event name DetachEA EventAction = libudevwrapper.UDEV_ACTION_REMOVE ) // ProbeEvent struct contain a copy of controller it will update disk resources type ProbeEvent struct { Controller *controller.Controller } // addDiskEvent fill disk details from different probes and push it to etcd func (pe *ProbeEvent) addDiskEvent(msg controller.EventMessage) { diskList, err := pe.Controller.ListDiskResource() if err != nil { klog.Error(err) go pe.initOrErrorEvent() return } for _, diskDetails := range msg.Devices { klog.Info("Processing details for ", diskDetails.ProbeIdentifiers.Uuid) pe.Controller.FillDiskDetails(diskDetails) // if ApplyFilter returns true then we process the event further if !pe.Controller.ApplyFilter(diskDetails) { continue } klog.Info("Processed details for ", diskDetails.ProbeIdentifiers.Uuid) oldDr := pe.Controller.GetExistingDiskResource(diskList, diskDetails.ProbeIdentifiers.Uuid) // if old DiskCR doesn't exist and parition is found, it is ignored since we don't need info // of partition if disk as a whole is ignored if oldDr == nil && len(diskDetails.PartitionData) != 0 { klog.Info("Skipping partition of already excluded disk ", diskDetails.ProbeIdentifiers.Uuid) continue } // if diskCR is already present, and udev event is generated for partition, append the partition info // to the diskCR if oldDr != nil && len(diskDetails.PartitionData) != 0 { newDrCopy := oldDr.DeepCopy() klog.Info("Appending partition data to ", diskDetails.ProbeIdentifiers.Uuid) newDrCopy.Spec.PartitionDetails = append(newDrCopy.Spec.PartitionDetails, diskDetails.ToPartition()...) pe.Controller.UpdateDisk(*newDrCopy, oldDr) } else { pe.Controller.PushDiskResource(oldDr, diskDetails) /* * There will be one blockdevice CR for each physical Disk. * For network devices like LUN there will be a blockdevice * CR but no disk CR. 1 to N mapping would be valid case * where disk have more than one partitions. * TODO: Need to check if udev event is for physical disk * and based on that need to create disk CR or blockdevice CR * or both. */ deviceDetails := pe.Controller.NewDeviceInfoFromDiskInfo(diskDetails) if deviceDetails != nil { klog.Infof("DeviceDetails:%#v", deviceDetails) deviceList, err := pe.Controller.ListBlockDeviceResource() if err != nil { klog.Error(err) go pe.initOrErrorEvent() return } oldDvr := pe.Controller.GetExistingBlockDeviceResource(deviceList, deviceDetails.UUID) pe.Controller.PushBlockDeviceResource(oldDvr, deviceDetails) } } /// update the list of DiskCRs diskList, err = pe.Controller.ListDiskResource() if err != nil { klog.Error(err) go pe.initOrErrorEvent() return } } } // deleteEvent deactivate disk/blockdevice resource using uuid from etcd func (pe *ProbeEvent) deleteEvent(msg controller.EventMessage) { diskOk := pe.deleteDisk(msg) blockDeviceOk := pe.deleteBlockDevice(msg) // when one disk is removed from node and entry related to // that disk is not present in etcd, in that case it // again rescan full system and update etcd accordingly. if !diskOk || !blockDeviceOk { go pe.initOrErrorEvent() } } func (pe *ProbeEvent) deleteBlockDevice(msg controller.EventMessage) bool { bdList, err := pe.Controller.ListBlockDeviceResource() if err != nil { klog.Error(err) return false } ok := true for _, diskDetails := range msg.Devices { bdUUID := pe.Controller.DiskToDeviceUUID(diskDetails.ProbeIdentifiers.Uuid) oldBDResource := pe.Controller.GetExistingBlockDeviceResource(bdList, bdUUID) if oldBDResource == nil { ok = false continue } pe.Controller.DeactivateBlockDevice(*oldBDResource) } return ok } func (pe *ProbeEvent) deleteDisk(msg controller.EventMessage) bool { diskList, err := pe.Controller.ListDiskResource() if err != nil { klog.Error(err) return false } ok := true for _, diskDetails := range msg.Devices { oldDiskResource := pe.Controller.GetExistingDiskResource(diskList, diskDetails.ProbeIdentifiers.Uuid) if oldDiskResource == nil { ok = false continue } pe.Controller.DeactivateDisk(*oldDiskResource) } return ok } // initOrErrorEvent rescan system and update disk resource this is // used for initial setup and when any uid mismatch or error occurred. func (pe *ProbeEvent) initOrErrorEvent() { udevProbe := newUdevProbe(pe.Controller) defer udevProbe.free() err := udevProbe.scan() if err != nil { klog.Error(err) } }
go
14
0.743785
106
32.603659
164
starcoderdata
#include #include using namespace std; class multclass { public: int operator()(int x, int y) const { return x * y; } // 重载操作符 operator }; void src1014() { // P361,利用类来定义函数对象 cout << "--->" << "代码10-14(利用类来定义函数对象)" << "<---" << endl; int A[] = { 1, 2, 3, 4, 5 }; const int N = sizeof(A) / sizeof(int); cout << "The result by multipling all elements in A is:" << accumulate(A, A + N, 1, multclass()) // 将普通函数 mult() 传递给通用算法 << endl; }
c++
10
0.618774
72
21.695652
23
starcoderdata
using Common; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using Microsoft.ML; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using LargeDatasets.DataStructures; using static Microsoft.ML.DataOperationsCatalog; namespace LargeDatasets { class Program { private const string datasetFile = "url_svmlight"; private const string datasetZip = datasetFile + ".tar.gz"; private const string datasetUrl = "https://archive.ics.uci.edu/ml/machine-learning-databases/url/url_svmlight.tar.gz"; private static string commonDatasetsRelativePath = @"../../../../../../../../datasets"; private static string commonDatasetsPath = GetAbsolutePath(commonDatasetsRelativePath); static string originalDataDirectoryRelativePath = @"../../../Data/OriginalUrlData"; static string originalDataRelativePath = @"../../../Data/OriginalUrlData/url_svmlight"; static string preparedDataRelativePath = @"../../../Data/PreparedUrlData/url_svmlight"; static string originalDataDirectoryPath = GetAbsolutePath(originalDataDirectoryRelativePath); static string originalDataPath = GetAbsolutePath(originalDataRelativePath); static string preparedDataPath = GetAbsolutePath(preparedDataRelativePath); static void Main(string[] args) { //STEP 1: Download dataset //DownloadDataset(originalDataDirectoryPath); string testFilePath = Path.Combine(originalDataRelativePath, "Day0.svm"); List destFiles = new List { testFilePath }; Web.DownloadBigFile(originalDataDirectoryRelativePath, datasetUrl, datasetZip, commonDatasetsPath, destFiles); //Step 2: Prepare data by adding second column with value total number of features. PrepareDataset(originalDataPath, preparedDataPath); MLContext mlContext = new MLContext(); //STEP 3: Common data loading configuration var fullDataView = mlContext.Data.LoadFromTextFile Path.Combine(preparedDataPath, "*"), hasHeader: false, allowSparse: true); //Step 4: Divide the whole dataset into 80% training and 20% testing data. TrainTestData trainTestData = mlContext.Data.TrainTestSplit(fullDataView, testFraction: 0.2, seed: 1); IDataView trainDataView = trainTestData.TrainSet; IDataView testDataView = trainTestData.TestSet; //Step 5: Map label value from string to bool var UrlLabelMap = new Dictionary<string, bool>(); UrlLabelMap["+1"] = true; //Malicious url UrlLabelMap["-1"] = false; //Benign var dataProcessingPipeLine = mlContext.Transforms.Conversion.MapValue("LabelKey", UrlLabelMap, "LabelColumn"); ConsoleHelper.PeekDataViewInConsole(mlContext, trainDataView, dataProcessingPipeLine, 2); //Step 6: Append trainer to pipeline var trainingPipeLine = dataProcessingPipeLine.Append( mlContext.BinaryClassification.Trainers.FieldAwareFactorizationMachine(labelColumnName: "LabelKey", featureColumnName: "FeatureVector")); //Step 7: Train the model Console.WriteLine("====Training the model====="); var mlModel = trainingPipeLine.Fit(trainDataView); Console.WriteLine("====Completed Training the model====="); Console.WriteLine(""); //Step 8: Evaluate the model Console.WriteLine("====Evaluating the model====="); var predictions = mlModel.Transform(testDataView); var metrics = mlContext.BinaryClassification.Evaluate(data: predictions, labelColumnName: "LabelKey", scoreColumnName: "Score"); ConsoleHelper.PrintBinaryClassificationMetrics(mlModel.ToString(),metrics); // Try a single prediction Console.WriteLine("====Predicting sample data====="); var predEngine = mlContext.Model.CreatePredictionEngine<UrlData, UrlPrediction>(mlModel); // Create sample data to do a single prediction with it var sampleDatas = CreateSingleDataSample(mlContext, trainDataView); foreach (var sampleData in sampleDatas) { UrlPrediction predictionResult = predEngine.Predict(sampleData); Console.WriteLine($"Single Prediction --> Actual value: {sampleData.LabelColumn} | Predicted value: {predictionResult.Prediction}"); } Console.WriteLine("====End of Process..Press any key to exit===="); Console.ReadLine(); } //public static void DownloadDataset(string originalDataDirectoryPath) //{ // if (!Directory.Exists(originalDataDirectoryPath)) // { // Console.WriteLine("====Downloading and extracting data===="); // using (var client = new WebClient()) // { // //The code below will download a dataset from a third-party, UCI (link), and may be governed by separate third-party terms. // //By proceeding, you agree to those separate terms. // client.DownloadFile("https://archive.ics.uci.edu/ml/machine-learning-databases/url/url_svmlight.tar.gz", "url_svmlight.zip"); // } // Stream inputStream = File.OpenRead("url_svmlight.zip"); // Stream gzipStream = new GZipInputStream(inputStream); // TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream); // tarArchive.ExtractContents(originalDataDirectoryPath); // tarArchive.Close(); // gzipStream.Close(); // inputStream.Close(); // Console.WriteLine("====Downloading and extracting is completed===="); // } //} private static void PrepareDataset(string originalDataPath,string preparedDataPath) { //Create folder for prepared Data path if it does not exist. if (!Directory.Exists(preparedDataPath)) { Directory.CreateDirectory(preparedDataPath); } Console.WriteLine("====Preparing Data===="); Console.WriteLine(""); //ML.Net API checks for number of features column before the sparse matrix format //So add total number of features i.e 3231961 as second column by taking all the files from originalDataPath //and save those files in preparedDataPath. if (Directory.GetFiles(preparedDataPath).Length == 0) { var ext = new List { ".svm" }; var filesInDirectory = Directory.GetFiles(originalDataPath, "*.*", SearchOption.AllDirectories) .Where(s => ext.Contains(Path.GetExtension(s))); foreach (var file in filesInDirectory) { AddFeaturesColumn(Path.GetFullPath(file), preparedDataPath); } } Console.WriteLine("====Data Preparation is done===="); Console.WriteLine(""); Console.WriteLine("original data path= {0}", originalDataPath); Console.WriteLine(""); Console.WriteLine("prepared data path= {0}", preparedDataPath); Console.WriteLine(""); } private static void AddFeaturesColumn(string sourceFilePath,string preparedDataPath) { string sourceFileName = Path.GetFileName(sourceFilePath); string preparedFilePath = Path.Combine(preparedDataPath, sourceFileName); //if the file does not exist in preparedFilePath then copy from sourceFilePath and then add new column if (!File.Exists(preparedFilePath)) { File.Copy(sourceFilePath, preparedFilePath, true); } string newColumnData = "3231961"; string[] CSVDump = File.ReadAllLines(preparedFilePath); List CSV = CSVDump.Select(x => x.Split(' ').ToList()).ToList(); for (int i = 0; i < CSV.Count; i++) { CSV[i].Insert(1, newColumnData); } File.WriteAllLines(preparedFilePath, CSV.Select(x => string.Join('\t', x))); } public static string GetAbsolutePath(string relativePath) { FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location); string assemblyFolderPath = _dataRoot.Directory.FullName; string fullPath = Path.Combine(assemblyFolderPath, relativePath); return fullPath; } private static List CreateSingleDataSample(MLContext mlContext, IDataView dataView) { // Here (ModelInput object) you could provide new test data, hardcoded or from the end-user application, instead of the row from the file. List sampleForPredictions = mlContext.Data.CreateEnumerable false).Take(4).ToList(); ; return sampleForPredictions; } } }
c#
23
0.607066
197
51.5
186
starcoderdata
package com.logviewer.data2; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class TestFileGenerator { private static Path root; public static void main(String[] args) throws IOException { if (args.length != 1) throw new IllegalArgumentException(); root = Paths.get(args[0]); create("buffered-file/empty.log", ""); create("buffered-file/n3.log", "\n\n\n"); create("buffered-file/rn3.log", "\r\n\r\n\r\n"); create("buffered-file/single-line.log", "abc"); create("buffered-file/a__bc_edf_.log", "a\r\nbc\nedf\n"); } private static void create(String name, String data) throws IOException { Path file = root.resolve(name); if (!Files.exists(file)) { Files.write(file, data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, StandardOpenOption.CREATE); } } }
java
13
0.658017
122
28.972222
36
starcoderdata