code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
<?php namespace App\Models; use PDO; use App\Core\Model; use \App\Flash; /** * Post Model * * PHP 7.1 */ class Image extends \Core\Model { public function uploadImage($imgname) { $db = static::getDB(); $sql = 'INSERT INTO image_upload (image) VALUES (:image)'; $stmt = $db->prepare($sql); $stmt->bindValue(':image', $imgname, PDO::PARAM_STR); $stmt->execute(); } public function checkImageExists($imgname) { $db = static::getDB(); $sql = 'SELECT image FROM image_upload WHERE image = :image'; $stmt = $db->prepare($sql); $stmt->bindValue(':image', $imgname, PDO::PARAM_STR); $stmt->execute(); if($r = $stmt->fetch()) { return true; } else { return false; } } public function getImages() { $db = static::getDB(); $sql = 'SELECT id, image FROM image_upload ORDER BY id DESC'; $stmt = $db->query($sql); $result = $stmt->fetchAll(PDO::FETCH_OBJ); return $result; } public function getImageId($id) { $db = static::getDB(); $sql = 'SELECT id, image FROM image_upload WHERE id = :id LIMIT 1'; $stmt = $db->prepare($sql); $stmt->bindValue(':id', $id, PDO::PARAM_INT); $stmt->setFetchMode(PDO::FETCH_CLASS, get_called_class()); $stmt->execute(); return $stmt->fetch(); } public function deleteImage($id) { $sql = 'DELETE FROM image_upload WHERE id = :id'; $db = static::getDB(); $stmt = $db->prepare($sql); $stmt->bindValue(':id', $id, PDO::PARAM_INT); return $stmt->execute(); } }
php
11
0.603344
69
16.6
85
starcoderdata
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FunctionAnnotationExamples.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // // -------------------------------------------------------------------------------------------------------------------- namespace ExampleLibrary { using System; using OxyPlot; using OxyPlot.Annotations; using OxyPlot.Axes; [Examples("FunctionAnnotation"), Tags("Annotations")] public static class FunctionAnnotationExamples { [Example("FunctionAnnotation")] public static PlotModel FunctionAnnotation() { var model = new PlotModel { Title = "FunctionAnnotation" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Minimum = -20, Maximum = 80 }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Minimum = -10, Maximum = 10 }); model.Annotations.Add(new FunctionAnnotation { Equation = Math.Sin, StrokeThickness = 2, Color = OxyColor.FromAColor(120, OxyColors.Blue), Text = "f(x)=sin(x)" }); model.Annotations.Add(new FunctionAnnotation { Equation = y => y * y, StrokeThickness = 2, Color = OxyColor.FromAColor(120, OxyColors.Red), Type = FunctionAnnotationType.EquationY, Text = "f(y)=y^2" }); return model; } } }
c#
18
0.550664
214
48.37931
29
starcoderdata
package org.sagebionetworks.bridge.upload; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.testng.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.sagebionetworks.bridge.models.healthdata.HealthDataRecord; import org.sagebionetworks.bridge.models.upload.Upload; public class UploadRawZipHandlerTest { private static final String UPLOAD_FILENAME = "filename"; private static final String UPLOAD_ID = "my-upload"; private static final String EXPECTED_RAW_DATA_ZIP_FILENAME = UPLOAD_ID + UploadRawZipHandler.RAW_ATTACHMENT_SUFFIX; private static final String EXPECTED_NON_ZIPPED_FILENAME = UPLOAD_ID + '-' + UPLOAD_FILENAME; private UploadValidationContext context; private UploadRawZipHandler handler; private File mockDecryptedFile; private UploadFileHelper mockUploadFileHelper; private HealthDataRecord record; private Upload upload; @BeforeMethod public void before() { // Set up mocks and handler. mockUploadFileHelper = mock(UploadFileHelper.class); handler = new UploadRawZipHandler(); handler.setUploadFileHelper(mockUploadFileHelper); // Set up context. We only read the upload ID, decrypted data file (mock), and the record. context = new UploadValidationContext(); upload = Upload.create(); upload.setFilename(UPLOAD_FILENAME); upload.setUploadId(UPLOAD_ID); context.setUpload(upload); mockDecryptedFile = mock(File.class); context.setDecryptedDataFile(mockDecryptedFile); record = HealthDataRecord.create(); context.setHealthDataRecord(record); } @Test public void test() throws Exception { // Execute and validate. handler.handle(context); verify(mockUploadFileHelper).uploadFileAsAttachment(EXPECTED_RAW_DATA_ZIP_FILENAME, mockDecryptedFile); assertEquals(record.getRawDataAttachmentId(), EXPECTED_RAW_DATA_ZIP_FILENAME); } @Test public void notZipped() throws Exception { // This is the same as the zipped case, except the filename is different. upload.setZipped(false); handler.handle(context); verify(mockUploadFileHelper).uploadFileAsAttachment(EXPECTED_NON_ZIPPED_FILENAME, mockDecryptedFile); assertEquals(record.getRawDataAttachmentId(), EXPECTED_NON_ZIPPED_FILENAME); } @Test(expectedExceptions = UploadValidationException.class) public void errorCase() throws Exception { // Mock uploadFileHelper to throw. doThrow(IOException.class).when(mockUploadFileHelper).uploadFileAsAttachment(EXPECTED_RAW_DATA_ZIP_FILENAME, mockDecryptedFile); // Execute (throws exception). handler.handle(context); } }
java
11
0.727949
119
36.935897
78
starcoderdata
using System; using System.Collections.Generic; //using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace CoreAndFood.Data.Models { public class Context: DbContext //unutma { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("server = DESKTOP-81USL0I\\SQLEXPRESS; database = CoreFood; integrated security = true"); // } public DbSet Foods { get; set; } public DbSet Categories { get; set; } } }
c#
12
0.700331
132
29.2
20
starcoderdata
# -*- coding: utf-8 -*- from pathlib import Path from click.testing import CliRunner from umarkdown.cli import main def test_cli_read_from_text_file(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("# Hello World") result = runner.invoke(main, ["hello.md"]) assert result.exit_code == 0 assert " World == result.output def test_cli_write_to_file(runner: CliRunner): with runner.isolated_filesystem(): result = runner.invoke(main, ["-", "hello.html"], input="# Hello World") assert result.exit_code == 0 assert " World == Path("hello.html").read_text() def test_cli_read_from_text_file_and_write_to_file(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("# Hello World") result = runner.invoke(main, ["hello.md", "hello.html"]) assert result.exit_code == 0 assert " World == Path("hello.html").read_text() def test_cli_with_source_pos(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("# Hello World") result = runner.invoke(main, ["hello.md", "--sourcepos"]) assert result.exit_code == 0 assert '<h1 data-sourcepos="1:1-1:13">Hello World == result.output def test_cli_with_hard_breaks(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("Hello,\nWorld!") result = runner.invoke(main, ["hello.md"]) assert result.exit_code == 0 assert " == result.output with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("Hello,\nWorld!") result = runner.invoke(main, ["hello.md", "--hardbreaks"]) assert result.exit_code == 0 assert " />\nWorld! == result.output def test_cli_with_no_breaks(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("Hello,\nWorld!") result = runner.invoke(main, ["hello.md"]) assert result.exit_code == 0 assert " == result.output with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("Hello,\nWorld!") result = runner.invoke(main, ["hello.md", "--nobreaks"]) assert result.exit_code == 0 assert " World! == result.output def test_cli_with_unsafe(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write(" World! result = runner.invoke(main, ["hello.md"]) assert result.exit_code == 0 assert "<!-- raw HTML omitted -->\n" == result.output with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write(" World! result = runner.invoke(main, ["hello.md", "--unsafe"]) assert result.exit_code == 0 assert " World! == result.output def test_cli_with_smart(runner: CliRunner): with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("Hello---") result = runner.invoke(main, ["hello.md"]) assert result.exit_code == 0 assert " == result.output with runner.isolated_filesystem(): with open("hello.md", "w") as f: f.write("Hello---") result = runner.invoke(main, ["hello.md", "--smart"]) assert result.exit_code == 0 assert " == result.output
python
12
0.580058
82
35.104762
105
starcoderdata
from app.api.models import MovieIn, MovieOut, MovieUpdate from app.api.db import movies, database async def add_movie(payload: MovieIn): query = movies.insert().values(**payload.dict()) return await database.execute(query=query) async def get_all_movies(): query = movies.select() return await database.fetch_all(query=query) async def get_movie(id): query = movies.select(movies.c.id==id) return await database.fetch_one(query=query) async def delete_movie(id: int): query = movies.delete().where(movies.c.id==id) return await database.execute(query=query) async def update_movie(id: int, payload: MovieIn): query = ( movies .update() .where(movies.c.id == id) .values(**payload.dict()) ) return await database.execute(query=query)
python
13
0.68059
57
29.148148
27
starcoderdata
private List<List<List<Double>>> getPermutatedCorrelations(Collection<Integer> combinedInd) throws IOException { List<List<Double>> corrRes1 = new ArrayList<>(); List<List<Double>> corrRes2 = new ArrayList<>(); int permutations = MetaOmGraph.getNumPermutations(); final List<Boolean> status = new ArrayList<>(); // status.add(0, true); final BlockingProgressDialog progress = new BlockingProgressDialog(MetaOmGraph.getMainWindow(), "Calculating permutations...", "", 0L, permutations, true); SwingWorker analyzeWorker = new SwingWorker() { public boolean errored = false; @Override public Object construct() { try { for (int i = 0; i < permutations && !progress.isCanceled(); i++) { progress.setProgress(i); List<Collection<Integer>> shuffleResult = randomlySplitIndices(combinedInd, getGrp1Size(), getGrp2Size()); // JOptionPane.showMessageDialog(null, "ind:"+i+" // l1"+shuffleResult.get(0).toString()+" l2"+shuffleResult.get(1).toString()); // get the groupwise correlation for this permutation List<List<Double>> thisResult = computeTwoGroupCorrelations(shuffleResult.get(0), shuffleResult.get(1)); // add the results two two lists corrRes1.add(thisResult.get(0)); corrRes2.add(thisResult.get(1)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public void finished() { if (progress.isCanceled()) { errored = true; progress.dispose(); } if ((!progress.isCanceled()) && (!errored)) { status.add(true); } progress.dispose(); } }; analyzeWorker.start(); progress.setVisible(true); List<List<List<Double>>> result = new ArrayList<>(); result.add(corrRes1); result.add(corrRes2); // JOptionPane.showMessageDialog(null, "returning RES"); return result; }
java
19
0.641566
112
28.212121
66
inline
def yes_no(value): """Convert boolen value to text representation :param value: Truth value to be converted :type value: bool :return: Yes or No text :rtype: str """ return 'Yes' if value else 'No'
python
6
0.637168
50
24.222222
9
inline
<?php return array( /** * The URI of the agegate */ 'agegate_uri' => 'check', /** * The minimum and maximum age to access the site */ 'minimum_age' => 18, 'maximum_age' => 114, /** * The input type to use. Choices are: * "date" for html5 <input type="date" /> * "select" for 3 tags for day, month and year */ 'input_type' => 'date', /** * The name of the cookie to set. Change this to whatever you want */ 'cookie_name' => 'age_ok', /** * The URL to redirect to on failure */ 'redirect_on_error' => true, 'redirect_url' => "http://www.drinkaware.co.uk/why-am-i-here", /** * The value of the cookie to set. Change this to something unique */ 'cookie_val' => 'validated', /** * The age of the cookie to set. Options are 'forever', an integer (minutes) or the default is for the session */ 'cookie_age' => '3600', /** * Determines whether the user can try again or not */ 'can_try_again' => true, /** * The view that should be rendered for the agegate. You can use the bundled view, or specify your own and use * @include('laravel-agegate::agegate') to get the agegate form and validation errors */ 'view' => 'laravel-avp::avp', 'allowed_routes' => array( 'privacy-policy', 'cookies', 'terms' ), /** * */ 'allowed_user_agents' => array( 'ipv4' => array( '192.168.127.12' ), 'strings' => array( 'bot', 'slurp', 'crawl', 'spider', 'yahoo', 'facebookexternalhit', ), ), );
php
9
0.601695
111
18.175
80
starcoderdata
import time from app.sensors import BH1750 from app.sensors import DHT_11 from app.statsdsender import StatsdSender from app.config import Config def main(): _config = Config() _bh1750 = BH1750(bus=_config.get_bus(), device=_config.get_device(), mode=_config.get_mode()) _dht11 = DHT_11(pin=_config.get_pin()) _statsdsender = StatsdSender(host=_config.get_hostname(), port=_config.get_port(), prefix=_config.get_prefix()) print("Sending stats to %s:%s with prefix %s" % (_config.get_hostname(), _config.get_port(), _config.get_prefix())) while True: luminosity = _bh1750.get_luminosity() (humidity, temperature) = _dht11.read_humidity_temperature() _statsdsender.send_luminosity(luminosity) _statsdsender.send_humidity(humidity) _statsdsender.send_temperature(temperature) time.sleep(5) if __name__ == '__main__': main()
python
10
0.672204
119
33.730769
26
starcoderdata
public List<List<Integer>> threeSum2Pointer(int[] nums) { if (nums.length<3) { return new ArrayList<List<Integer>>(); } Arrays.sort(nums); Set<List<Integer>> results = new HashSet<>(); // use a set to avoid duplicates for (int i=0; i< nums.length; i++) { int left = i + 1; int right = nums.length - 1; int total = 0; while (left < right) { total = nums[i] + nums[left] + nums[right]; if (total > 0) { right -= 1; } else if (total < 0) { left += 1; } else { results.add(Arrays.asList(nums[i], nums[left], nums[right])); // moving pointers so we don't repeat them left += 1; right -= 1; } } } return new ArrayList<>(results); }
java
16
0.377715
90
38.259259
27
inline
int __intel_wait_for_register(struct intel_uncore *uncore, i915_reg_t reg, u32 mask, u32 value, unsigned int fast_timeout_us, unsigned int slow_timeout_ms, u32 *out_value) { unsigned fw = intel_uncore_forcewake_for_reg(uncore, reg, FW_REG_READ); u32 reg_value; int ret; might_sleep_if(slow_timeout_ms); spin_lock_irq(&uncore->lock); intel_uncore_forcewake_get__locked(uncore, fw); ret = __intel_wait_for_register_fw(uncore, reg, mask, value, fast_timeout_us, 0, &reg_value); intel_uncore_forcewake_put__locked(uncore, fw); spin_unlock_irq(&uncore->lock); if (ret && slow_timeout_ms) ret = __wait_for(reg_value = intel_uncore_read_notrace(uncore, reg), (reg_value & mask) == value, slow_timeout_ms * 1000, 10, 1000); /* just trace the final value */ trace_i915_reg_rw(false, reg, reg_value, sizeof(reg_value), true); if (out_value) *out_value = reg_value; return ret; }
c
11
0.627649
67
24.435897
39
inline
/* * Author: * File Name: FileDialogService.cs * Project Name: NetworkCryptography * Creation Date: 10/21/2017 * Modified Date: 10/21/2017 * Description: A service class for opening file dialogs. */ using System; using System.Windows; using Microsoft.Win32; namespace NetworkCryptography.Client { /// /// A service class for opening file dialogs. /// public class FileDialogService { /// /// Open a file dialog with a caption and filter. /// /// <param name="caption">The caption of the file dialog. /// <param name="filter">The file filter; file selection will be restricted to these file extensions. /// string containing the path of the selected file. public string OpenDialog(string caption, string filter = "All files (*.*)|*.*") { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), Title = caption, Filter = filter, CheckFileExists = true, CheckPathExists = true, RestoreDirectory = true }; return dialog.ShowDialog() == true ? dialog.FileName : string.Empty; } } }
c#
19
0.607787
117
32.02381
42
starcoderdata
if (Meteor.isServer) { Meteor.methods({ 'removeAll':function(){ return stats.remove({user: Meteor.userId()}); }, 'removeLast':function(){ var removeLast = stats.findOne({user: Meteor.userId()}, {sort:{$natural:-1}}) return stats.remove({_id:removeLast._id}) }, 'addStat':function(stat,user){ stats.insert({stat:stat,user:user}); } }); }
javascript
19
0.596899
81
19.5
18
starcoderdata
from datetime import datetime, timedelta import scrapy from ..items import Covid19NewsCrawlerItem from core.models import CovidNews def to_num(value): if value == 'N/A': value = '0,0' return float(value.replace(',', '')) class Covid19News(scrapy.Spider): name = 'news' start_urls = [ "https://www.who.int/emergencies/diseases/" "novel-coronavirus-2019/media-resources/news" ] custom_settings = { 'ITEM_PIPELINES': { 'covid19crawler.pipelines.Covid19NewsCrawlerPipeline': 400, 'covid19crawler.pipelines.CSVNewsPipeline': 500, } } def parse(self, response): t = response.xpath('//*[@id="PageContent_C003_Col01"]/div/div/a') title = [] href = [] date = [] for data in t.css('.text-underline::text'): title.append(data.get()) for data in t.css('.sub-title::text'): try: date.append(datetime.strptime( "-".join(data.get().replace(',', ' ').split()[:3]), '%d-%B-%Y').date()) except (ValueError, TypeError): date.append(datetime.now().date()) for data in t.xpath('@href'): href.append(data.get()) for i in range(20): items = Covid19NewsCrawlerItem() item, created = CovidNews.objects.get_or_create( title=title[i], date=date[i], defaults={'href': href[i]}) items['title'] = title[i] items['href'] = href[i] items['date'] = date[i] yield items
python
25
0.52456
73
26.949153
59
starcoderdata
import React from 'react'; import Dogstagram from '../components/Dogstagram'; import SEO from '~/components/seo'; import Hero from '~/components/Hero'; import Slider from '~/components/Slider'; import { HomeHeading } from '~/utils/styles'; import styled from 'styled-components'; import ShopProducts from '~/components/ShopProducts'; const MainContent = styled.div` display: flex; flex-direction: column; justify-content: baseline; align-items: center; p { width: 80%; margin: 15px auto; line-height: 1.5em; @media (min-width: 600px) { width: 90%; max-width: 600px; } } `; function IndexPage() { return ( <> <SEO title="Home" keywords={['dog treats', 'peanut butter', 'subscription', 'dogs']} description="Home page of Peanut Butter Dog Treats" /> <Hero /> Butter Dog Treats These goodies are made with all-natural Oats and gluten-free Peanut Butter. No xylitol, no artificial preservatives, no artificial flavoring, doggy taste tested! I take your pet's safety seriously, as I do mine. If you have any concerns about how and where these treats are made, rest assured that I use only non-toxic surface disinfectant and abide by the regulations covered under the Texas Cottage Food Law. For more information, please read more on the blog. <Slider /> <ShopProducts /> <Dogstagram /> ); } export default IndexPage;
javascript
11
0.629697
80
27.947368
57
starcoderdata
package com.hyperaware.android.talk.concurrency; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.hyperaware.android.talk.concurrency.loader.ResultOrException; import com.hyperaware.android.talk.concurrency.loader.StatefulExecutorServiceLoader; import com.hyperaware.android.talk.concurrency.logging.Logging; /** * An example of how to use a Loader to load a string resource into a * TextView, pretending that the operation would block for some time. */ public class ActivityProgressLoader extends FragmentActivity { private static final String LOG_TAG = ActivityProgressLoader.class.getSimpleName(); private static final int LOADER_ID = 1; private View vProgressContainer; private Button buttonLoadNow; private TextView tvProgress; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); initViews(); attachLoader(); } private void initViews() { setContentView(R.layout.activity_progress_loader); buttonLoadNow = (Button) findViewById(R.id.button_load_now); buttonLoadNow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { loadNow(); } }); vProgressContainer = findViewById(R.id.v_progress_container); tvProgress = (TextView) findViewById(R.id.tv_progress); } private void attachLoader() { // Get the currently active loader (returns null if not previously // initialized) final Loader<ResultOrException<Void, Exception>> loader = getSupportLoaderManager().getLoader(LOADER_ID); final ProgressLoader progressLoader = (ProgressLoader) loader; // If the loader is active... if (progressLoader != null) { // Reattach to it so it can continue where it left off initProgressLoader(); updateUiLoading(); // And update the UI to match the state switch (progressLoader.getState()) { case Init: break; case Loading: updateUiStart(); updateUiProgress(progressLoader.getCurrent(), progressLoader.getTotal()); break; case Loaded: updateUiEnd(); break; } } final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); lbm.registerReceiver(startReceiver, new IntentFilter(ProgressLoader.ACTION_START)); lbm.registerReceiver(progressReceiver, new IntentFilter(ProgressLoader.ACTION_PROGRESS)); lbm.registerReceiver(endReceiver, new IntentFilter(ProgressLoader.ACTION_END)); } @Override protected void onDestroy() { super.onDestroy(); // Android won't warn you about LocalBroadcastManager receiver // leaks, so don't forget to couple all registers with an unregister. final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); lbm.unregisterReceiver(startReceiver); lbm.unregisterReceiver(progressReceiver); lbm.unregisterReceiver(endReceiver); } private void initProgressLoader() { getSupportLoaderManager().initLoader(LOADER_ID, null, new ProgressLoaderCallbacks()); } private void loadNow() { // Update UI to indicate a load is in progress updateUiLoading(); // Destroy any existing loader that had been run getSupportLoaderManager().destroyLoader(LOADER_ID); // Init a new loader initProgressLoader(); } private void updateUiLoading() { buttonLoadNow.setEnabled(false); } private void updateUiStart() { vProgressContainer.setVisibility(View.VISIBLE); tvProgress.setText(""); } private void updateUiProgress(final int current, final int total) { tvProgress.setText(current + "/" + total); } private void updateUiEnd() { vProgressContainer.setVisibility(View.GONE); } /** * Handle ProgressLoader.ACTION_START by showing the progress UI. */ private final BroadcastReceiver startReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { updateUiStart(); } }; private final BroadcastReceiver progressReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final int current = intent.getIntExtra(ProgressLoader.EXTRA_CURRENT, 0); final int total = intent.getIntExtra(ProgressLoader.EXTRA_TOTAL, 0); updateUiProgress(current, total); } }; private final BroadcastReceiver endReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { updateUiEnd(); } }; /** * Loader callbacks that define the instance of the loader to use and what * to do when the loader completes. */ private class ProgressLoaderCallbacks implements LoaderCallbacks<ResultOrException<Void, Exception>> { public ProgressLoaderCallbacks() { } @Override public Loader<ResultOrException<Void, Exception>> onCreateLoader(final int id, final Bundle args) { return new ProgressLoader(ActivityProgressLoader.this); } @Override public void onLoadFinished(final Loader<ResultOrException<Void, Exception>> loader, final ResultOrException<Void, Exception> result) { Logging.logDebugThread(LOG_TAG, "Content loaded."); buttonLoadNow.setEnabled(true); getSupportLoaderManager().destroyLoader(LOADER_ID); } @Override public void onLoaderReset(final Loader<ResultOrException<Void, Exception>> loader) { } } private static class ProgressLoader extends StatefulExecutorServiceLoader { public static final String NAMESPACE = ProgressLoader.class.getName() + '.'; public static final String ACTION_START = NAMESPACE + "ACTION_START"; public static final String ACTION_PROGRESS = NAMESPACE + "ACTION_PROGRESS"; public static final String ACTION_END = NAMESPACE + "ACTION_END"; public static final String EXTRA_CURRENT = NAMESPACE + "EXTRA_CURRENT"; public static final String EXTRA_TOTAL = NAMESPACE + "EXTRA_TOTAL"; private static final int ITERATIONS = 10; private volatile int current; private volatile int total; public ProgressLoader(final Context context) { // This context may be an Activity instance, but it will not be stored. super(context); } @Override protected ResultOrException<Void, Exception> onLoadInBackgroundStateful() { current = 0; total = ITERATIONS; // Use LocalBroadcastManager to advertise changes in state and // progress. final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getContext()); lbm.sendBroadcast(new Intent(ACTION_START)); for (int i = 0; i < ITERATIONS; i++) { final int cur = i + 1; current = cur; Logging.logDebugThread(LOG_TAG, "Doing work unit " + cur); final Intent intent = new Intent(ACTION_PROGRESS); intent.putExtra(EXTRA_CURRENT, cur); intent.putExtra(EXTRA_TOTAL, ITERATIONS); lbm.sendBroadcast(intent); // No actual work here, just delay SystemClock.sleep(1000); } lbm.sendBroadcast(new Intent(ACTION_END)); return new ResultOrException<>((Void) null); } public int getCurrent() { return current; } public int getTotal() { return total; } } }
java
15
0.655472
142
34.631799
239
starcoderdata
package org.egov.user.domain.exception; import lombok.Getter; import org.egov.user.domain.model.User; public class InvalidUserUpdateException extends RuntimeException { private static final long serialVersionUID = 580361940613077431L; @Getter private User user; public InvalidUserUpdateException(User user) { this.user = user; } }
java
8
0.795918
66
20.4375
16
starcoderdata
import React from "react"; import PropTypes from "prop-types"; import { IconButton } from "furmly-base-web"; class Panel extends React.Component { state = { isOpen: "show" }; getIcon = () => { if (this.props.right) { return this.state.isOpen == "show" ? "chevron-right" : "chevron-left"; } return this.state.isOpen == "show" ? "chevron-left" : "chevron-right"; }; toggle = () => { this.setState({ isOpen: this.state.isOpen == "show" ? "collapsed" : "show" }); }; render() { return ( <div className={`panel ${this.state.isOpen} ${this.props.type}`}> <IconButton onClick={this.toggle} icon={this.getIcon()} /> <div className={"content"}>{this.props.children} ); } } Panel.propTypes = { children: PropTypes.node, iconSize: PropTypes.number, right: PropTypes.bool, type: PropTypes.oneOf(["large", "huge"]) }; export default Panel;
javascript
19
0.601472
76
24.026316
38
starcoderdata
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.zylib.yfileswrap.gui.zygraph; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.proximity.ZyProximityNode; import y.view.EdgeLabel; import java.awt.event.MouseEvent; public interface IZyGraphListener<NodeType, EdgeType> { void edgeClicked(EdgeType node, MouseEvent event, double x, double y); void edgeLabelEntered(EdgeLabel label, MouseEvent event); void edgeLabelExited(EdgeLabel label); void nodeClicked(NodeType node, MouseEvent event, double x, double y); void nodeEntered(NodeType node, MouseEvent event); void nodeHovered(NodeType node, double x, double y); void nodeLeft(NodeType node); void proximityBrowserNodeClicked(ZyProximityNode proximityNode, MouseEvent event, double x, double y); }
java
11
0.773181
96
33.195122
41
starcoderdata
public void SetMarkers(List<Marker> markerList) { //Check the list if (markerList == null || markerList.Count <= 0) { ShowAlertDialog(GetString(Resource.String.errorTitle), GetString(Resource.String.dbErrorMarkerListEmptyError), GetString(Resource.String.btnClose)); } else { AddMarkerListToMap(markerList); } }
c#
15
0.553047
164
36
12
inline
public AccountModel parseToken(String token) { try { if (StringUtils.isEmpty(token)) { return null; } Claims body = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); Optional<AccountModel> account = accountRepository.findById(Long.parseLong((String) body.get("userId"))); if (account.isPresent()) { String username = body.getSubject(); logger.info("Username of token is " + username + " and username of database is " + account.get().getUsername()); if (!StringUtils.isEmpty(username) && !username.equals(account.get().getUsername())) { return null; } return account.get(); } } catch (JwtException e) { // Simply print the exception and null will be returned for the userDto e.printStackTrace(); } return null; }
java
16
0.482175
102
37.724138
29
inline
"use strict"; var a = '123'; var name = ['23', '34']; nams.forEach(function (item) { return console.log(item); });
javascript
9
0.59322
30
15.857143
7
starcoderdata
package br.dominioL.estruturados.mapa; import br.dominioL.estruturados.elemento.Codificavel; import br.dominioL.estruturados.elemento.Igualavel; public interface Par<C extends Igualavel & Codificavel, V extends Igualavel { public C fornecerChave(); public V fornecerValor(); }
java
4
0.798817
84
25
13
starcoderdata
protected boolean isAnAppInstalled() { boolean appIsInstalled = false; // File baseCacheDirectory = baseCacheDir(); // String [] list = baseCacheDirectory!=null?baseCacheDirectory.list():null; // if( list == null ) return appIsInstalled; // List<String> files = Arrays.asList(list); // if(files.contains(appConfig)) appIsInstalled = true; //check if app info has been initialized boolean appInfoInitialized = (appInfo!=null && appInfo[AppInfo.NAME] != null && appInfo[AppInfo.NAME].length()>0); //if not, try to initialize from sved prefs if(!appInfoInitialized) { appInfo = getStoredAppInfo2(); appInfoInitialized = (appInfo!=null && appInfo[AppInfo.NAME] != null && appInfo[AppInfo.NAME].length()>0); } if(appInfoInitialized) { appIsInstalled = new File(baseDir(), appConfig).exists(); } //Log.d("[appMobi]", "checking if an app is installed, appInfoInitialized:"+appInfoInitialized+(appInfoInitialized?(" ("+appInfo[AppInfo.NAME]+")"):"")+" appIsInstalled:"+appIsInstalled);//TODO - remove after testing return appIsInstalled; }
java
13
0.652137
218
43.076923
26
inline
package org.hy.common; import java.util.EventListener; /** * 线程方式执行相关的动作的事件监听接口 * * @author ZhengWei(HY) * @createDate 2017-01-19 * @version v1.0 */ public interface ExecuteListener extends EventListener { /** * 执行结果 * * @author ZhengWei(HY) * @createDate 2017-01-19 * @version v1.0 * * @param i_Event */ public void result(ExecuteEvent i_Event); }
java
6
0.571429
54
14.166667
30
starcoderdata
#ifndef ANG_SD_MESH_H_ #define ANG_SD_MESH_H_ #include #include "opengl/shader.h" #include "opengl/texture.h" #include "opengl/vertex.h" class PlayerMesh { public: std::vector vertices; std::vector<unsigned int> indices; std::vector textures; PlayerMesh(std::vector vertices, std::vector<unsigned int> indices, std::vector textures); void Draw(Shader shader) const; ~PlayerMesh(); PlayerMesh(PlayerMesh &&); PlayerMesh(const PlayerMesh &) = delete; void updateVertices(std::vector newVertices); private: mutable bool verticesDirty = false; unsigned int VAO, VBO, EBO; void setupMesh(); }; #endif // ANG_SD_MESH_H_
c
9
0.711286
77
21.411765
34
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Roblox.Services.Database; using Roblox.Services.DatabaseCache; using Roblox.Services.Exceptions.Services; using Roblox.Services.Lib.Extensions; namespace Roblox.Services.Services { public class AvatarService : IAvatarService { private IAvatarDatabase db { get; set; } public AvatarService(IAvatarDatabase db) { this.db = db; } public async Task GetUserAvatar(long userId) { var result = await db.GetUserAvatar(userId); if (result == null) throw new RecordNotFoundException(); var assets = await db.GetAvatarAssets(userId); return new() { colors = new() { headColorId = result.headColorId, torsoColorId = result.torsoColorId, leftArmColorId = result.leftArmColorId, rightArmColorId = result.rightArmColorId, leftLegColorId = result.leftLegColorId, rightLegColorId = result.rightLegColorId, }, scales = new() { bodyType = result.bodyType, depth = result.depth, head = result.head, height = result.height, proportion = result.proportion, width = result.width, }, type = result.type, assetIds = assets, }; } public async Task SetUserAvatar(Models.Avatar.SetAvatarRequest request) { var userId = request.userId; var assets = request.assetIds.ToList().Distinct().ToList(); // first, get current avatar, figure out the assetIds dif, then insert/remove the assets var current = (await db.GetAvatarAssets(userId)).ToList(); var toRemove = ListExtensions.GetItemsNotInSecondList( current, assets, (idOne, idTwo) => idOne == idTwo ); var toAdd = ListExtensions.GetItemsNotInSecondList( assets, current, (idOne, idTwo) => idOne == idTwo ); // Submit changes foreach (var item in toRemove) { await db.DeleteAvatarAsset(userId, item); } foreach (var item in toAdd) { await db.InsertAvatarAsset(userId, item); } var hasPreviousAvatar = current.Count > 0 || await db.GetUserAvatar(userId) != null; if (hasPreviousAvatar) { await db.UpdateUserAvatar(request); } else { await db.InsertUserAvatar(request); } } } }
c#
18
0.520972
100
32.388889
90
starcoderdata
using System; using Arcus.BackgroundJobs.Tests.Integration.Fixture; using GuardNet; namespace Arcus.BackgroundJobs.Tests.Integration.AzureActiveDirectory.Fixture { /// /// Represents the configuration model to connect to the test Azure Active Directory used during the integration tests. /// public class AzureActiveDirectoryConfig { /// /// Initializes a new instance of the <see cref="AzureActiveDirectoryConfig" /> class. /// /// <param name="tenantId">The ID of the tenant of the test Azure Active Directory used during the integration tests. /// <param name="clientId">The ID of the service principal to connect to the Azure Active Directory. /// <param name="clientSecret">The secret of the service principal to connect to the Azure Active Directory. /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="tenantId"/>, <paramref name="clientId"/>, or <paramref name="clientSecret"/> is blank. /// public AzureActiveDirectoryConfig( string tenantId, string clientId, string clientSecret) { Guard.NotNullOrWhitespace(tenantId, nameof(tenantId), "Requires a non-blank tenant ID to run Azure Active Directory integration tests"); TenantId = tenantId; ServicePrincipal = new ServicePrincipal(clientId, clientSecret); } /// /// Gets the ID of the tenant of the test Azure Active Directory used during the integration tests. /// public string TenantId { get; } /// /// Gets the service principal credentials to connect to the test Azure Active Directory used during the integration tests. /// public ServicePrincipal ServicePrincipal { get; } } }
c#
14
0.657868
148
45.904762
42
starcoderdata
const Database = require('./config') const initDb = { async init() { const db = await Database() // abre a conexão com o banco // usa funcao assincrona pois o js nao espera a inicialização do banco // inicialização esta em uma variavel pois ela é necessária para invocar o método exec e run // primeiramente deve-se criar as tabelas e isso é feito apenas UMA vez // comando SQL precisam estar dentro da crase `` // criação da tabela profile await db.exec(`CREATE TABLE profile( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, avatar TEXT, monthly_budget INT, days_per_week INT, hours_per_day INT, vacation_per_year INT, value_hour INT )`) // criação da tabela jobs await db.exec(`CREATE TABLE jobs( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, daily_hours INT, total_hours INT, created_at DATETIME )`) // inserindo os meus dados no profile await db.run(`INSERT INTO profile( name, avatar, monthly_budget, days_per_week, hours_per_day, vacation_per_year, value_hour ) VALUES ( "Vinicius", "https://github.com/albertivini.png", 2000, 6, 5, 4, 70 );`) // sera que tem q usar esse ponto e virgula no final msm? // inserindo os dados iniciais no jobs await db.run(`INSERT INTO jobs( name, daily_hours, total_hours, created_at ) VALUES ( " 2, 1, 1622294361746 );`) await db.run(`INSERT INTO jobs( name, daily_hours, total_hours, created_at ) VALUES ( "OneTwo Project", 3, 47, 1622294361746 );`) await db.close() // fecha a conexão com o banco } } initDb.init() // executando a função
javascript
19
0.493794
100
25.244186
86
starcoderdata
import os import pprint from contextlib import suppress from sh import git as _git, ErrorReturnCode # pylint: disable=no-name-in-module import requests from flask import current_app, request import log from .. import URL ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) DATA = os.path.join(ROOT, "data") GITHUB_BASE = "https://raw.githubusercontent.com/jacebrowning/coverage-space/main/" CONTRIBUTING_URL = GITHUB_BASE + "CONTRIBUTING.md" CHANGELOG_URL = GITHUB_BASE + "CHANGELOG.md" git = _git.bake(git_dir=os.path.join(DATA, ".git"), work_tree=DATA) def sync(model, *, changes=True): """Store all changes in version control.""" if changes: log.info("Saving changes...") git.checkout('master') git.add(all=True) try: git.diff(cached=True, exit_code=True) except ErrorReturnCode: git.commit(message=str(model)) else: log.info("No changes to save") log.info("Pulling changes...") try: git.pull(rebase=True) except ErrorReturnCode: log.error("Merge conflicts detected, attempting reset...") git.fetch() with suppress(ErrorReturnCode): git.rebase(abort=True) git.reset('origin/master', hard=True) if changes: log.info("Pushing changes...") git.push(force=True) def track(obj): """Log the requested content, server-side.""" data = dict( v=1, tid=_get_tid(), cid=request.remote_addr, t='pageview', dh=URL, dp=request.path, dt=request.method + ' ' + request.url_rule.endpoint, uip=request.remote_addr, ua=request.user_agent.string, dr=request.referrer, ) if _get_tid(default=None): requests.post("http://www.google-analytics.com/collect", data=data) log.debug("Analytics data:\n%s", pprint.pformat(data)) return obj def _get_tid(*, default='local'): """Get the analtyics tracking identifier.""" return current_app.config['GOOGLE_ANALYTICS_TID'] or default
python
14
0.624645
83
26.402597
77
starcoderdata
private static void fillRightAboveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { while (node.next.point.getX() < edge.getP().getX()) { if (tcx.isDebugEnabled()) { tcx.getDebugContext().setActiveNode(node); } // Check if next node is below the edge Orientation o1 = orient2d(edge.getQ(), node.next.point, edge.getP()); if (o1 == Orientation.CCW) { fillRightBelowEdgeEvent(tcx, edge, node); } else { node = node.next; } } }
c#
15
0.450875
112
36.2
20
inline
public void StoreItemToPlayerPrefs() { //removes the old item if (itemTypes[itemIndex] != "TempPotion" && itemTypes[itemIndex] != "PermPotion") { for (int i = 0; i < stats.Length; i++) { PlayerPrefs.SetInt(stats[i], PlayerPrefs.GetInt(stats[i]) - PlayerPrefs.GetInt(stats[i] + itemTypes[itemIndex] + "Buff")); //subtract the buff from the stat PlayerPrefs.SetInt(stats[i] + itemTypes[itemIndex] + "Buff", 0); //set the buff to 0 } } //Adds the new item PlayerPrefs.SetString(itemTypes[itemIndex], itemName); //give the new name to the weapon PlayerPrefs.SetInt(mainBuffName + itemTypes[itemIndex] + "Buff", mainBuffPoints); //store the points of the mainbuff in ((MainStat)Buff) PlayerPrefs.SetInt(rareBuffName + itemTypes[itemIndex] + "Buff",rareBuffPoints); //store the points of the rarebuff in ((picked rare stat)Buff) PlayerPrefs.SetInt(legendaryBuffName + itemTypes[itemIndex] + "Buff",rareBuffPoints); //store the points of the legendarybuff in ((picked legendary stat)Buff) PlayerPrefs.SetInt(mainBuffName, PlayerPrefs.GetInt(mainBuffName) + mainBuffPoints); //Set the mainstat of the player to the mainbuffed amount PlayerPrefs.SetInt(rareBuffName, PlayerPrefs.GetInt(rareBuffName) + rareBuffPoints); //Set the rare stat of the player to the rare buffed amount PlayerPrefs.SetInt(legendaryBuffName, PlayerPrefs.GetInt(legendaryBuffName) + rareBuffPoints); //Set the legendary buff of the player to the legendary amount }
c#
21
0.747119
160
63.173913
23
inline
using Gsemac.Drawing.Extensions; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; // This implementation is based off of the implementation provided here: // https://social.msdn.microsoft.com/Forums/windows/en-US/769ca9d6-1e9d-4d76-8c23-db535b2f19c2/sample-code-datagridview-progress-bar-column?forum=winformsdatacontrols namespace Gsemac.Forms { public class DataGridViewProgressBarCell : DataGridViewImageCell { // Public members public bool ShowProgressPercentage { get; set; } = true; public Color BackgroundColor { get; set; } = Color.FromArgb(230, 230, 230); public Color ProgressColor { get; set; } = Color.FromArgb(6, 176, 37); public Color TextColor { get; set; } public DataGridViewProgressBarCell() { ValueType = typeof(double); } public override object Clone() { DataGridViewProgressBarCell clone = (DataGridViewProgressBarCell)base.Clone(); clone.ShowProgressPercentage = ShowProgressPercentage; clone.BackgroundColor = BackgroundColor; clone.ProgressColor = ProgressColor; clone.TextColor = TextColor; return clone; } // Protected members protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { return emptyImage; } protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { // Paint the default cell appearance. DataGridViewCellStyle style = cellStyle; base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, style, advancedBorderStyle, paintParts); // Paint the progress bar. double progressValue = Convert.ToDouble(value); double progressPercentage = progressValue / 100.0; string progressStr = $"{progressValue:0.#}%"; Color outlineColor = BackgroundColor.AddShade(0.15f); Color progressOutlineColor = ProgressColor.AddShade(0.15f); // Paint the progress bar background. Rectangle drawRect = new Rectangle(cellBounds.X + 2, cellBounds.Y + 2, cellBounds.Width - 4, cellBounds.Height - 4); using (Brush brush = new SolidBrush(BackgroundColor)) graphics.FillRectangle(brush, drawRect); using (Pen pen = new Pen(outlineColor)) graphics.DrawRectangle(pen, drawRect); // Paint the progress bar foreground. if (progressValue > 0) { Rectangle progressRect = new Rectangle(drawRect.X, drawRect.Y, Convert.ToInt32(progressPercentage * drawRect.Width), drawRect.Height); using (Brush brush = new SolidBrush(ProgressColor)) graphics.FillRectangle(brush, progressRect); using (Pen pen = new Pen(progressOutlineColor)) graphics.DrawRectangle(pen, progressRect); } // Paint the progress bar text. if (ShowProgressPercentage) { bool isSelected = DataGridView.CurrentCell?.RowIndex == rowIndex; Color textColor = TextColor == default ? (isSelected ? style.SelectionForeColor : style.ForeColor) : TextColor; Font textFont = style.Font; TextRenderer.DrawText(graphics, progressStr, textFont, drawRect, textColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); } } // Private members private static readonly Bitmap emptyImage = new Bitmap(1, 1, PixelFormat.Format32bppArgb); } }
c#
21
0.672605
332
35.769912
113
starcoderdata
/* * 1008.cpp * * Created on: 2017年5月2日 * Author: Administrator */ // #include // #include #include // using namespace std; void inversion(int* n,int end,int begin); /** * 解决思路: * 数组分成AB前后两部分 * 全部倒置成B^-1A^-1 * 然后在前面倒置,后面倒置BA */ int main(){ int size,distance; //数组大小,位移量 int* n = NULL; // cin >> size; // cin >> distance; scanf("%d %d", &size, &distance); distance = distance%size; // n = new int[size]; n = (int*)malloc(size * sizeof(int)); for(int i=0;i<size;i++){ // cin >> n[i]; scanf("%d ",&n[i]); } inversion(n,size,0); //整体倒置 inversion(n,distance,0); //前面的B^-1倒置 inversion(n,size,distance); //后面A^-1倒置 for(int i=0;i<size-1;i++){ // cout << n[i]<<" "; printf("%d ",n[i]); } // cout << n[size-1]<<endl; printf("%d", n[size-1]); } //数组倒置函数 //num要从begin位子操作的数量 void inversion(int* n,int end,int begin){ for(int i=begin;i<(end+begin)/2;i++){ int temp = n[i]; n[i] = n[begin+end-i-1]; n[begin+end-i-1] = temp; } }
c
11
0.568862
41
17.555556
54
starcoderdata
"use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; Object.defineProperty(exports, "__esModule", { value: true }); var globalStubs = {}; global.$_stubs_$ = {}; function setGlobalStubs(stubs) { globalStubs = __assign({}, globalStubs, stubs); global.$_stubs_$ = globalStubs; } exports.setGlobalStubs = setGlobalStubs; var nodeRegistered = false; var firstRequire = null; function setFirstRequire(name) { if (firstRequire == null) { firstRequire = name; } } function cleanup() { var matcher = new RegExp(firstRequire); if (global.FuseBox) { global.FuseBox.flush(function (file) { return file.match(matcher); }); } if (require && require.cache) { for (var _i = 0, _a = Object.getOwnPropertyNames(require.cache); _i < _a.length; _i++) { var item = _a[_i]; if (item.match(matcher)) { delete require.cache[item]; } } } } function proxy(requireFunc, stubs) { firstRequire = null; if (require && !nodeRegistered) { registerNode(); } global.$_stubs_$ = Object.assign({}, globalStubs, stubs); var req = requireFunc(); cleanup(); req = requireFunc(); global.$_stubs_$ = globalStubs; cleanup(); return req; } exports.proxy = proxy; function mock(path, impl) { if (require && !nodeRegistered) { registerNode(); } var parts = path.split('/'); global.$_stubs_$[parts[parts.length - 1]] = impl(); global.$_stubs_$[path] = impl(); } exports.mock = mock; function unmockAll() { global.$_stubs_$ = {}; } exports.unmockAll = unmockAll; function unmock(path) { var parts = path.split('/'); global.$_stubs_$[parts[parts.length - 1]] = null; global.$_stubs_$[path] = null; } exports.unmock = unmock; function proxyRequire(require, path) { var parts = path.split('/'); var module_name = parts[parts.length - 1]; setFirstRequire(module_name); return global.$_stubs_$[path] || global.$_stubs_$[module_name] || require(path); } exports.proxyRequire = proxyRequire; function FuseBoxStubPlugin(test) { return { test: test || /\.js/, transform: function (file) { file.contents = file.contents.replace(/require\s*\((['"]\s*[\w-_\.\/\\]*\s*['"])\)/g, 'proxyRequire(function() { return require($1); }, $1)'); if (file.contents.indexOf('jest.mock') >= 0) { file.contents = file.contents.replace(/jest\.mock\s*\(/g, 'require("proxyrequire").mock('); file.contents = file.contents + '\nrequire("proxyrequire").unmockAll()'; } } }; } exports.FuseBoxStubPlugin = FuseBoxStubPlugin; function registerGlobals() { global.proxyRequire = proxyRequire; } exports.registerGlobals = registerGlobals; function registerNode() { global.$_stubs_$ = {}; var Module = require('module'); if (Module && Module.prototype && Module.prototype.require) { var originalRequire = Module.prototype.require; Module.prototype.require = function (path) { var parts = path.split('/'); var module_name = parts[parts.length - 1]; setFirstRequire(module_name); return (global.$_stubs_$[path] || global.$_stubs_$[module_name] || originalRequire.apply(this, arguments)); }; } nodeRegistered = true; } exports.registerNode = registerNode; function transform(content) { return content.replace(/require\s*\((['"]\s*[\w-_\.\/\\]*\s*['"])\)/g, 'proxyRequire(function() { return require($1); }, $1)'); } exports.transform = transform; function webpackStubLoader(content) { return transform(content); } exports.webpackStubLoader = webpackStubLoader;
javascript
15
0.596579
154
32.133333
120
starcoderdata
static final void randBytes ( Random r, byte[] buffer ) { // regular nextBytes is not reproducible if the reads are not aligned for ( int i = 0; i < buffer.length; i++ ) { buffer[ i ] = (byte) r.nextInt(256); } }
java
10
0.557312
77
35.285714
7
inline
from abc import ABC, abstractmethod class OCR(ABC): """OCR class that performs OCR on a given image.""" @abstractmethod def perform_ocr(self, image: object) -> dict: """Perform OCR on a given image. :param image: PIL Image/numpy array or file path(str) to be processed :return: results dictionary containing bboxes and text for each detected word """ pass @staticmethod def get_text_from_ocr_dict(ocr_result: dict, separator: str = " ") -> str: """Combine the text from the OCR dict to full text. :param ocr_result: dictionary containing the ocr results per word :param separator: separator to use when joining the words return: str containing the full extracted text as string """ if not ocr_result: return "" else: return separator.join(ocr_result["text"])
python
14
0.637804
85
30.566667
30
starcoderdata
<?php namespace CodelyTv\Mooc\Courses\Application\Create; use CodelyTv\Mooc\Courses\Domain\Course; use CodelyTv\Mooc\Courses\Domain\CourseDuration; use CodelyTv\Mooc\Courses\Domain\CourseName; use CodelyTv\Mooc\Courses\Domain\CourseRepository; use CodelyTv\Mooc\Shared\Domain\Course\CourseId; use CodelyTv\Shared\Domain\Bus\Event\EventBus; use CodelyTv\Shared\Domain\Logger; use CodelyTv\Shared\Infrastructure\Logger\MonologLogger; class CourseCreator { /** @var CourseRepository */ private $repository; /** @var EventBus */ private $bus; private $logger; /** * CourseCreator constructor. * @param CourseRepository $repository * @param EventBus $bus */ public function __construct(CourseRepository $repository, EventBus $bus) { $this->repository = $repository; $this->bus = $bus; } public function __invoke(CourseId $id, CourseName $name, CourseDuration $duration) { $course = Course::create($id, $name, $duration); $this->repository->save($course); $this->bus->publish(...$course->pullDomainEvents()); } }
php
12
0.689165
86
23.478261
46
starcoderdata
import * as THREE from 'three' function coreFunc() { let cubeContainer = document.querySelector('#cube-scene') var clock = new THREE.Clock() const cubeCore = [] //SCENE const scene = new THREE.Scene() // /* CAMERA ha 4 parametri: • Field of View (FOV): valore in gradi, rappresenta l'estensione della scena visualizzata • Aspect Ratio: width del contenitore / height del contenitore • Near (clipping plane) & Far (clipping plane): questi ultimi due parametri rappresentano il range in cui gli oggetti devono essere renderizzati. Per migliorare perfomance, diminuire range. ∆ per ora utilizzo una camera PerspectiveCamera, però ce ne sono altre. */ const camera = new THREE.PerspectiveCamera( 75, cubeContainer.clientWidth / cubeContainer.clientHeight, 0.1, 1000 ) camera.position.set(0,0,10) camera.lookAt( 0, 0, 0 ) // /* RENDER: ci sono diversi render in ThreeJS, per ora uso il render di WebGL. Imposto la grandezza del renderer, e lo aggiungo al documento HTML. */ const renderer = new THREE.WebGLRenderer() renderer.setSize( cubeContainer.clientWidth, cubeContainer.clientHeight ) cubeContainer.appendChild( renderer.domElement ) // //cube const geometry = new THREE.BoxGeometry() const material = new THREE.MeshBasicMaterial( { color: 0x39CFB4 } ) const cube = new THREE.Mesh( geometry, material ) cube.scale.x = 4 cube.scale.y = 4 cube.scale.z = 4 scene.add( cube ) // //line const lineMat = new THREE.LineBasicMaterial( { color: 0xF75940 } ) const linePoints = [] linePoints.push(new THREE.Vector3(-6,0,0)) linePoints.push(new THREE.Vector3(0,6,0)) linePoints.push(new THREE.Vector3(6,0,0)) linePoints.push(new THREE.Vector3(0,-6,0)) linePoints.push(new THREE.Vector3(-6,0,0)) const lineGeometry = new THREE.BufferGeometry().setFromPoints( linePoints ) const line = new THREE.Line(lineGeometry, lineMat) scene.add(line) // //lots of cubes function cubeGenerator(num) { for(let i = 0; i < num; i++) { let cubeGeometry = new THREE.BoxGeometry() let cubeColor = "rgb("+(i+6)*4+",1"+(Math.floor(Math.random() * 9)+10*3)+","+(i*16)+")" console.log(cubeColor) let cubeMat = new THREE.MeshBasicMaterial( { color: cubeColor} ) cubeCore[i] = new THREE.Mesh( cubeGeometry, cubeMat ) scene.add(cubeCore[i]) cubeCore[i].position.x = Math.floor(Math.random() * 10) cubeCore[i].position.y = i } } cubeGenerator(7) //behaviours function cubeBehaviour() { cube.rotation.x += 0.01 cube.rotation.y += 0.02 } function lineBehaviour() { line.rotation.x -= 0.01 line.rotation.y += 0.01 } // function clickTitle() { document.querySelector('#scene-title').addEventListener('click', () => { console.log('Clicked!') cube.scale.x = Math.floor(Math.random() * 7) cube.scale.y = Math.floor(Math.random() * 7) cube.scale.z = Math.floor(Math.random() * 7) }) } clickTitle() function createCube() { document.querySelector('#create-cube').addEventListener('click', () => { console.log('Adding cube') let auxGeometry = new THREE.BoxGeometry() let auxMaterial = new THREE.MeshBasicMaterial( { color: 0x96C0CE } ) let auxCube = new THREE.Mesh( auxGeometry, auxMaterial ) auxCube.scale.x = 2 auxCube.scale.y = 2 auxCube.scale.z = 2 auxCube.position.x = 1 auxCube.position.y = 3 auxCube.name = ' scene.add( auxCube ) console.log(scene.children) scene.children.splice(2,1) }) } createCube() function deleteCube() { document.querySelector('#delete-cube').addEventListener('click', () => { console.log('Deleting cube') for( var i = 0; i < scene.children.length; i++) { if ( scene.children[i].name === 'Nuovo cubo') { scene.children.splice(i, 1); //ma non viene eliminato dalla memoria, perchè serve il dispose() ma la doc fa schifo } } }) } deleteCube() //animate loop function animate() { cubeBehaviour() lineBehaviour() let t = clock.getElapsedTime() for(let d = 0; d < cubeCore.length; d++) { let auxSize = (Math.abs(Math.cos(t)))/1.05; cubeCore[d].scale.x = auxSize cubeCore[d].scale.y = auxSize cubeCore[d].scale.z = auxSize cubeCore[d].rotation.x += 0.01 cubeCore[d].rotation.y += 0.02 } requestAnimationFrame( animate ) renderer.render( scene, camera ) } animate() } export default coreFunc;
javascript
20
0.647974
117
29.644295
149
starcoderdata
from selenium.webdriver.common.by import By from ..abstract import PageElement from .base import TaskPage class Task304Page(TaskPage): result = PageElement(By.ID, "id_result") sentence = PageElement(By.ID, "id_sentence") submit = PageElement(By.ID, "id_submit")
python
8
0.749235
49
28.727273
11
starcoderdata
package com.yassirh.digitalocean.data; public class SizeTable extends TableHelper { public static final String SIZE_SLUG = "size_slug"; public static final String MEMORY = "memory"; public static final String CPU = "cpu"; public static final String DISK = "disk"; public static final String TRANSFER = "transfer"; public static final String COST_PER_HOUR = "cost_per_hour"; public static final String COST_PER_MONTH = "cost_per_month"; public SizeTable(){ columns.put(SIZE_SLUG, "string primary key"); columns.put(MEMORY, "integer"); columns.put(CPU, "integer"); columns.put(DISK, "integer"); columns.put(TRANSFER, "integer"); columns.put(COST_PER_HOUR, "REAL"); columns.put(COST_PER_MONTH, "REAL"); TABLE_NAME = "sizes"; } }
java
9
0.708279
62
30.708333
24
starcoderdata
import { G as getValue, a7 as defLastLadderReset, g as getElementsByTagName, p as pCC, d as defTable, b9 as containsText, B as getText, V as setValue } from './calfSystem-d357ca6f.js'; import './isChecked-6167b36b.js'; import { s as simpleCheckbox } from './simpleCheckbox-9f95c1f3.js'; import './hideElement-f7381055.js'; import { i as insertHtmlAfterEnd } from './insertHtmlAfterEnd-8735ac4b.js'; import { p as parseDateAsTimestamp } from './parseDateAsTimestamp-491fa6b5.js'; import './toggleForce-c034bc71.js'; import { c as collapse } from './collapse-cd6af20d.js'; let lastLadderReset; let trackLadderReset; function checkForPvPLadder(row) { if (trackLadderReset && containsText('PvP Ladder', row.children[1].children[0])) { const logTime = parseDateAsTimestamp( getText(row.children[1].children[2]).replace('Posted: ', ''), ); if (logTime > lastLadderReset) { setValue(defLastLadderReset, logTime); lastLadderReset = logTime; } } } function testArticle(rowType) { return rowType > 1; } function setupPref(prefName, rowInjector) { insertHtmlAfterEnd(rowInjector, simpleCheckbox(prefName)); } function viewArchive() { lastLadderReset = getValue(defLastLadderReset); trackLadderReset = getValue('trackLadderReset'); const prefName = 'collapseNewsArchive'; const theTables = getElementsByTagName(defTable, pCC); if (theTables.length > 2) { setupPref(prefName, theTables[0].rows[2]); collapse({ prefName, theTable: theTables[2], headInd: 7, articleTest: testArticle, extraFn: checkForPvPLadder, }); } } export default viewArchive; //# sourceMappingURL=viewArchive-22c7d811.js.map
javascript
17
0.72176
184
33.326531
49
starcoderdata
import React from "react" import { FaLinkedinIn, FaGithub, FaEnvelope } from "react-icons/fa" import Layout from "../components/layout" import Image from "../components/image" import IconButton from "../components/iconbutton" import SEO from "../components/seo" const IndexPage = () => ( <SEO title="Home" keywords={[ `gatsby`, `portfolio`, `react`, `front end development`, `RPA`, `javascript`, ]} /> <div className="intro-wrapper"> <div className="headshot"> <Image /> <h2 className="intro-heading">Hello there. My name is <h4 className="intro-subheading"> Web Developer. Business Process Automator. Gym Rat. <div className="button-container"> <IconButton text="Connect" href="https://www.linkedin.com/in/benjamin-j-myers/"> <FaLinkedinIn /> <IconButton text="Mail" href="mailto: <FaEnvelope /> <IconButton text="Projects" href="https://github.com/benjammin502"> <FaGithub /> ) export default IndexPage
javascript
8
0.597729
86
25.804348
46
starcoderdata
import re from textwrap import dedent from bs4 import BeautifulSoup import bs4 from csvw.dsv import UnicodeWriter from clldutils.misc import slug from pylexibank.dataset import Dataset from pylexibank.forms import FormSpec from pylexibank.util import pb class TOB(Dataset): name = None dset = None pages = 1 lexemes = {} form_spec = FormSpec( brackets={"(": ")"}, separators=";/,~", missing_data=('?', '-', ''), strip_inside_brackets=True ) tob_sources = { "Starostin2011": dedent(""" @misc{Starostin2011, Year = {2011}, Editor = { and Title = {The Global Lexicostatistical Database} }""") } def _url(self, page): return 'http://starling.rinet.ru/cgi-bin/response.cgi?' + \ 'root=new100&morpho=0&basename=new100' + \ r'\{0}\{1}&first={2}'.format(self.dset, self.name, page) def cmd_download(self, args): self.raw_dir.write('sources.bib', "\n".join(self.tob_sources.values())) # download data all_records = [] for i in pb(list(range(1, 20 * self.pages + 1, 20))): with self.raw_dir.temp_download( self._url(i), 'file-{0}'.format(i), log=args.log) as fname: soup = BeautifulSoup(fname.open(encoding='utf8').read(), 'html.parser') for record in soup.findAll(name='div', attrs={"class": "results_record"}): if isinstance(record, bs4.element.Tag): children = list(record.children) number = children[0].findAll('span')[1].text.strip() concept = children[1].findAll('span')[1].text for child in children[2:]: if isinstance(child, bs4.element.Tag): dpoints = child.findAll('span') if len(dpoints) >= 3: lname = dpoints[1].text glottolog = re.findall( 'Glottolog: (........)', str(dpoints[1]))[0] entry = dpoints[2].text cogid = list(child.children)[4].text.strip() all_records.append( (number, concept, lname, glottolog, entry, cogid)) with UnicodeWriter(self.raw_dir / 'output.csv') as f: f.writerows(all_records) def cmd_makecldf(self, args): args.writer.add_sources() concepts = args.writer.add_concepts( id_factory=lambda c: c.id.split('-')[-1] + '_' + slug(c.english), lookup_factory=lambda c: c.id.split('-')[-1] ) for cid, concept, lang, gc, form, cogid in self.raw_dir.read_csv('output.csv'): lid = lang.replace(' ', '_') args.writer.add_language(ID=lid, Name=lang, Glottocode=gc) global_cog_id = "%s-%s" % (cid, cogid) for row in args.writer.add_forms_from_value( Language_ID=lid, Parameter_ID=concepts[cid], Value=form, Source=list(self.tob_sources), Cognacy=global_cog_id ): args.writer.add_cognate( lexeme=row, Cognateset_ID=global_cog_id, Source=list(self.tob_sources))
python
28
0.497021
90
38.606742
89
starcoderdata
[MethodImpl(MethodImplOptions.NoInlining)] static byte TestCoveredIndex3(Span<byte> data, int start, int end) { byte x = 0; byte y = 0; byte z = 0; for (var idx = start; idx < end; idx++) { x ^= data[idx]; if (idx != 100) { y ^= data[50]; // Should be able to eliminate this bounds check z ^= data[25]; } } byte r = (byte)(z ^ y ^ x ^ y ^ z); return r; }
c#
14
0.365449
74
25.217391
23
inline
using System; using RimWorld; using UnityEngine; using Verse; namespace rjw { public abstract class Designator_Toggle : Command { public Designator_Toggle() { this.activateSound = SoundDefOf.SelectDesignator; } public Func isActive; public Action toggleAction; public SoundDef turnOnSound = SoundDefOf.CheckboxTurnedOn; public SoundDef turnOffSound = SoundDefOf.CheckboxTurnedOff; public override SoundDef CurActivateSound { get { if (this.isActive()) { return this.turnOffSound; } return this.turnOnSound; } } public override void ProcessInput(Event ev) { base.ProcessInput(ev); this.toggleAction(); } public override GizmoResult GizmoOnGUI(Vector2 loc) { GizmoResult result = base.GizmoOnGUI(loc); Rect rect = new Rect(loc.x, loc.y, this.Width, 75f); Rect position = new Rect(rect.x + rect.width - 24f, rect.y, 24f, 24f); Texture2D image = (!this.isActive()) ? Widgets.CheckboxOffTex : Widgets.CheckboxOnTex; GUI.DrawTexture(position, image); return result; } public override bool InheritInteractionsFrom(Gizmo other) { Command_Toggle command_Toggle = other as Command_Toggle; return command_Toggle != null && command_Toggle.isActive() == this.isActive(); } } public class Designator_ComfortPrisoner : Designator { private static readonly MiscTranslationDef MTdef = DefDatabase public Designator_ComfortPrisoner() { defaultLabel = MTdef.label; defaultDesc = MTdef.description; icon = ContentFinder // TODO: Can this be null? hotKey = KeyBindingDefOf.Misc12; // These don't matter but set them just in case // soundDragSustain = SoundDefOf.DesignateDragStandard; // soundDragChanged = SoundDefOf.DesignateDragStandardChanged; // useMouseIcon = false; // soundSucceeded = SoundDefOf.DesignateClaim; } public Func isActive; public override GizmoResult GizmoOnGUI(Vector2 loc) { GizmoResult result = base.GizmoOnGUI(loc); Rect rect = new Rect(loc.x, loc.y, this.Width, 75f); Rect position = new Rect(rect.x + rect.width - 24f, rect.y, 24f, 24f); Texture2D image = (!this.isActive()) ? Widgets.CheckboxOffTex : Widgets.CheckboxOnTex; GUI.DrawTexture(position, image); return result; } public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } public override void DesignateSingleCell(IntVec3 c) { } public override AcceptanceReport CanDesignateThing(Thing t) { var p = t as Pawn; //return (p != null) && (p.IsPrisonerOfColony || p.IsColonist || p.Faction == Faction.OfPlayer) && xxx.can_get_raped(p) && (!comfort_prisoners.is_designated(p)); if (p != null) { if (p.IsPrisonerOfColony) { defaultLabel = "comfort prisoner"; //TODO: adds translationdef. } else if (xxx.is_animal(p)) { defaultLabel = "comfort animal"; } else { defaultLabel = "comfort colonist"; } } return ((p != null) && (!comfort_prisoners.is_designated(p)) && ((p.IsColonist || p.Faction == Faction.OfPlayer) || (xxx.is_animal(p)) || (p.IsPrisonerOfColony))); //TODO: Rape target button? } public override void DesignateThing(Thing t) { DesignationDef designation_def = comfort_prisoners.designation_def_no_sticky; if (xxx.config.rape_me_sticky_enabled) { designation_def = comfort_prisoners.designation_def; //comfort_prisoners.designation_def = comfort_prisoners.designation_def_no_sticky; } base.Map.designationManager.AddDesignation(new Designation(t, designation_def)); } } }
c#
17
0.701698
194
26.701493
134
starcoderdata
import asyncio from vk import VK from vk.utils.requests_pool import VKRequestsPool from jconfig import Config SECTION_NAME = 'vk' CONFIG_FILENAME = "config.json" async def enter_captcha(url: str, sid: str) -> str: print(url) key = input("Введите капчу: ") return key async def main(): cfg = Config(SECTION_NAME, CONFIG_FILENAME) vk = VK(cfg['token']) vk.error_dispatcher.register_captcha_handler(enter_captcha) # For example "how clean blacklist faster way" # getting count users in blacklist req = await vk.api_request("account.getBanned", dict(count=0)) # prepare temporary variables for making queries of the "execute" format banned_pool = [] # variable to combine results banned = [] # Create a request pool instance async with VKRequestsPool(vk) as pool: # Add to this instance as many requests as we need for i in range(0, req["count"], 200): banned_pool.append( pool.method( "account.getBanned", dict(count=200, offset=i) ) ) # Clear pool in memory del pool # Getting results from pool for banned_p in banned_pool: if banned_p.ok: banned.extend(banned_p.result['items']) else: print(banned_p.error) # clear tmp variables in memory del banned_p, banned_pool # Again creating for "unban" method unbanned_pool = [] async with VKRequestsPool(vk) as pool: for user_id in banned: unbanned_pool.append( pool.method( "account.unban", dict(owner_id=user_id) ) ) del pool for k, unbanned_p in enumerate(unbanned_pool): if unbanned_p.ok: print(f"https://vk.com/id{banned_p[k]}") else: print(f"error https://vk.com/id{banned_p[k]}") print(unbanned_p.error) del k, unbanned_p, unbanned_pool, banned # Success!!! Blacklist is clean if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main())
python
15
0.597831
76
28.472222
72
starcoderdata
<?php namespace Dez\Form; use Dez\Form\Decorator\DefaultForm; use Dez\Form\Element\InputEmail; use Dez\Form\Element\InputPassword; use Dez\Form\Element\InputText; use Dez\Form\Element\Select; use Dez\Form\Element\Submit; /** * Class Form * @package Dez\Form */ class Form { /** * @var Decorator */ protected $decorator; /** * @var string */ protected $action; /** * @var string */ protected $method = 'get'; /** * @var bool */ protected $multipartData = false; /** * @var Element[] */ protected $elements = []; /** * Form constructor. * @param $action * @param string $method * @param bool|false $multipart */ public function __construct($action = null, $method = 'get', $multipart = false) { $this->setAction($action)->setMethod($method)->setMultipartData($multipart)->setDecorator(new DefaultForm($this)); } /** * Cloning */ public function __clone() { $this->setDecorator(clone $this->getDecorator()); $this->getDecorator()->setForm($this); } /** * @return Decorator */ public function getDecorator() { return $this->decorator; } /** * @param Decorator $decorator * @return static */ public function setDecorator(Decorator $decorator) { if (!$decorator->hasForm()) { $decorator->setForm($this); } $this->decorator = $decorator; return $this; } /** * @return string */ public function __toString() { return $this->render(); } /** * @return string */ public function render() { return $this->getDecorator()->render(); } /** * @param $name * @param $label * @return Form */ public function addPassword($name, $label) { return $this->add(new InputPassword($name, null, $label)); } /** * @param Element $element * @return $this */ public function add(Element $element) { $this->elements[$element->getName()] = $this->getDecorator()->element($element); return $this; } /** * @param $name * @param $label * @return Form */ public function addText($name, $label) { return $this->add(new InputText($name, null, $label)); } /** * @param $name * @param $label * @return Form */ public function addEmail($name, $label) { return $this->add(new InputEmail($name, null, $label)); } /** * @param $value * @return Form */ public function addSubmit($value) { return $this->add(new Submit(null, $value)); } /** * @param $name * @param array $data * @param $label * @return Form */ public function addSelect($name, array $data = [], $label) { return $this->add(new Select($name, $data, $label)); } /** * @param array $defaultValues * @return $this */ public function setDefaultArray(array $defaultValues = []) { foreach ($defaultValues as $name => $value) { $this->setDefault($name, $value); } return $this; } /** * @param $name * @param null $defaultValue * @return $this */ public function setDefault($name, $defaultValue = null) { if ($this->hasElement($name)) { $this->getElement($name)->setDefault($defaultValue); } return $this; } /** * @param $name * @return bool */ public function hasElement($name) { return isset($this->elements[$name]); } /** * @param $name * @return Element */ public function getElement($name) { return $this->hasElement($name) ? $this->elements[$name] : null; } /** * @return mixed */ public function getAction() { return $this->action; } /** * @param mixed $action * @return $this */ public function setAction($action) { $this->action = $action; return $this; } /** * @return string */ public function getMethod() { return $this->method; } /** * @param string $method * @return $this */ public function setMethod($method) { $this->method = $method; return $this; } /** * @return boolean */ public function isMultipartData() { return $this->multipartData; } /** * @param boolean $multipartData * @return $this */ public function setMultipartData($multipartData) { $this->multipartData = $multipartData; return $this; } /** * @return Element[] */ public function getElements() { return $this->elements; } /** * @param Element[] $elements * @return $this */ public function setElements($elements) { $this->elements = $elements; return $this; } }
php
13
0.57579
118
15.67509
277
starcoderdata
def __init__(self, toml_file, num_sample_chunk=1e6): """Load xmission parameters and run basic setup""" self.cf = Config() experiment = Broadcast(toml_file) self.num_sample_chunk = num_sample_chunk self.x_a = experiment.surface.x_a self.y_a = experiment.surface.y_a self.t_a = experiment.t_a self.f_a = experiment.f_a self.experiment = experiment # make a rough estimate of number of processing chunks needed self.realization = None
python
7
0.62069
69
36.357143
14
inline
const options = { tizenPath: "tizen/", outPath: "./build/", }; const convertSvg = require("./grunt/svg2png"); module.exports = grunt => { const prod = grunt.option("prod"); const logLevel = grunt.option("logLevel"); const fileLogger = grunt.option("fileLogger"); const certificate = grunt.option("cert") || (prod ? "Samsung" : "Tizen"); if (grunt.option("time")) { require("time-grunt")(grunt); } grunt.loadNpmTasks("grunt-shell"); grunt.loadNpmTasks("grunt-env"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.config.init({ env: require("./grunt/options/env"), tizen: require("./package").tizen, shell: require("./grunt/options/shell")(grunt, options), clean: { build: [options.outPath] }, }); const bundleParams = [ prod ? "prod" : "", typeof(logLevel) === "string" ? "LOG_LEVEL=" + logLevel : "", fileLogger ? "FILE_LOGGER" : "" ].join(":"); grunt.registerTask("convert-icon", function() { const done = this.async(); convertSvg("./src/style/app-icon.svg", options.outPath + "app-icon.png").then(done); }); grunt.registerTask("default", "watch"); grunt.registerTask("build", `Build deployment package. Available params:\n` + `--prod - Optimizes the build\n` + `--cert=[name] - Sign with a different security profile (default: "Samsung")`, ["clean", "bundle", "package"]); grunt.registerTask("test", ["shell:test"]); grunt.registerTask("install", "Install package on connected target device", [`shell:install`]); grunt.registerTask("uninstall", "Uninstall package from connected target device", [`shell:uninstall`]); grunt.registerTask("start", "Start application on connected device", ["shell:kill", "shell:start"]); grunt.registerTask("stop", "Stop application on connected target device", ["shell:kill"]); grunt.registerTask("debug", "Start application in debug mode on target device. Open debugger on http://localhost:4711", ["start", "shell:portForward:4711"]); grunt.registerTask("bundle", "Build application bundle. Add --prod flag for optimized bundling.", ["env:prod", `shell:bundle:${bundleParams}`]); grunt.registerTask("package", "Assemble Tizen package from build output. Add --cert=[name] to sign with a different certificate.", ["convert-icon", "shell:tizen-build", `shell:tizen-package:${certificate}`]); grunt.registerTask("watch", "Start dev server on port 80 and watch for file changes", [`shell:watch:${bundleParams}`]); };
javascript
15
0.631302
134
41.190476
63
starcoderdata
#define _min(a, b) ((a) < (b) ? (a) : (b)) #define _max(a, b) ((a) < (b) ? (b) : (a)) int sum(int count, ...) { va_list ap; int sum; va_start (ap, count); /* Initialize the argument list. */ sum = 0; for (int i = 0; i < count; i++) sum += va_arg (ap, int); /* Get the next argument value. */ va_end (ap); /* Clean up. */ return sum; } int min(int count, ...) { va_list ap; int minimum = MAX_ELEMENT; va_start (ap, count); /* Initialize the argument list. */ for (int i = 0; i < count; i++) { int next_el; next_el = va_arg (ap, int); minimum = _min(minimum, next_el); } va_end (ap); /* Clean up. */ return minimum; } int max(int count, ...) { va_list ap; int maximum = MIN_ELEMENT; va_start (ap, count); /* Initialize the argument list. */ for (int i = 0; i < count; i++) { int next_el; next_el = va_arg (ap, int); maximum = _max(maximum, next_el); } va_end (ap); /* Clean up. */ return maximum; }
c
9
0.438119
71
22.326923
52
starcoderdata
Euler/euler008.py from functools import reduce def mul(a, b): return a * b for _ in range(int(input())): n, k = map(int, input().split()) num = input() maxi = 0 for i in range(n-k+1): m = reduce(mul, map(int, list(num[i : i+k]))) if maxi < m: maxi = m print(maxi)
python
16
0.591837
92
25.2
15
starcoderdata
def SenseMovement(self, frame): if type(self._prev_frame) == type(None): self._prev_frame = frame # Remove the old movement if self._movement_list[self._iterator]: self.counter -= 1 self._movement_list[self._iterator] = False diff_frame = np.abs(self._prev_frame - frame) self._prev_frame = frame ret, thresh = cv2.threshold(diff_frame, 20, 255, cv2.THRESH_BINARY) if np.count_nonzero(thresh) > 100: self.counter += 1 self._movement_list[self._iterator] = True #print(np.count_nonzero(thresh)) # Increment the iterator an keep it in range self._iterator += 1 if self._iterator >= 36000: self._iterator = 0 # Disable this if you don't want to show thresh with counter cv2.putText(thresh, str(self.counter), (2,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, 255, 2, cv2.LINE_AA) return thresh
python
9
0.568
107
39.04
25
inline
protected virtual bool Visit(ModelMetadata metadata, string key, object model) { RuntimeHelpers.EnsureSufficientExecutionStack(); if (model != null && !_currentPath.Push(model)) { // This is a cycle, bail. return true; } bool result; try { // Throws InvalidOperationException if the object graph is too deep result = VisitImplementation(ref metadata, ref key, model); } finally { _currentPath.Pop(model); } return result; }
c#
11
0.482707
83
29.272727
22
inline
<?php class Setting_model extends CI_Model { public function __construct() { parent::__construct(); $this->db = $this->load->database('default', TRUE); } function getAdmin() { $sql = 'SELECT * FROM admin ORDER BY id ASC'; $q = $this->db->query($sql); return $q->result(); } function getBagian() { $sql = 'SELECT * FROM dt_uid_bagian ORDER BY URUT ASC'; $q = $this->db->query($sql); return $q->result(); } function addBagian($urut,$name) { $sql_get = 'SELECT * FROM dt_uid_bagian WHERE URUT = ? '; $q = $this->db->query($sql_get,array($urut)); $dt = $q->result(); if(!empty($dt)){ return array(false,'Nomor urut tidak boleh sama '); } $sql = "INSERT INTO dt_uid_bagian (URUT,BAGIAN) VALUES (?,?)"; $status = $this->db->query($sql, array($urut,$name)); if($status){ return array($status,'Data telah ditambahkan'); } else { return array($status, $this->db->error()); } } function editBagian($urut,$bagian,$urut_old,$bagian_old) { $sql_del = "DELETE FROM dt_uid_bagian WHERE URUT = ? AND BAGIAN = ?"; $status_del = $this->db->query($sql_del,array($urut_old,$bagian_old)); if(!$status_del){ return array(false,'Data tidak ditemukan'); } $sql = "INSERT INTO dt_uid_bagian (URUT,BAGIAN) VALUES (?,?)"; $status = $this->db->query($sql, array($urut,$bagian)); if($status){ return array($status,'Data telah diedit'); } else { return array($status, $this->db->error()); } } function deleteBagian($urut,$name) { $sql = "DELETE FROM dt_uid_bagian WHERE URUT = ? AND BAGIAN = ?"; return $this->db->query($sql,array($urut,$name)); } function getJabatan($bagian = '') { $sql = 'SELECT * FROM dt_uid_jabatan '; if($bagian != ''){ $sql .= 'WHERE BAGIAN = ? '; } $sql .= 'ORDER BY URUT ASC'; $q = $this->db->query($sql,array($bagian)); return $q->result(); } function addJabatan($bagian,$urut,$jabatan) { $sql_get = 'SELECT * FROM dt_uid_jabatan WHERE BAGIAN = ? AND URUT = ? '; $q = $this->db->query($sql_get,array($bagian,$urut)); $dt = $q->result(); if(!empty($dt)){ return array(false,'Nomor urut sudah terpakai '); } $sql = "INSERT INTO dt_uid_jabatan (URUT,JABATAN,BAGIAN) VALUES (?,?,?)"; $status = $this->db->query($sql, array($urut,$jabatan,$bagian)); if($status){ return array($status,'Data telah ditambahkan'); } else { return array($status, $this->db->error()); } } function editJabatan($bagian,$urut,$jabatan,$urut_old,$jabatan_old) { $sql_sel = "SELECT * FROM dt_uid_jabatan WHERE URUT = ? AND BAGIAN = ? AND JABATAN = ?"; $status_sel = $this->db->query($sql_sel,array($urut_old,$bagian,$jabatan_old)); $dt = $status_sel->result(); if(empty($dt)){ return array(false,'Data tidak ditemukan'); } $sql = "UPDATE dt_uid_jabatan SET URUT = ?, JABATAN = ? WHERE URUT = ? AND BAGIAN = ? AND JABATAN = ?"; $status = $this->db->query($sql, array($urut,$jabatan,$urut_old,$bagian,$jabatan_old)); if($status){ return array($status,'Data telah diedit'); } else { return array($status, $this->db->error()); } } function deleteJabatan($urut,$bagian,$jabatan) { $sql = "DELETE FROM dt_uid_jabatan WHERE URUT = ? AND BAGIAN = ? AND JABATAN = ?"; return $this->db->query($sql,array($urut,$bagian,$jabatan)); } function getUsers() { $sql = 'SELECT * FROM uid '; $sql .= 'ORDER BY NAMA ASC'; $q = $this->db->query($sql); return $q->result(); } function getMaster($type) { switch($type){ case 'bagian': $sql = 'SELECT * FROM dt_uid_bagian '; $sql .= 'ORDER BY BAGIAN ASC'; $q = $this->db->query($sql); return $q->result(); break; case 'jabatan': $sql = 'SELECT * FROM dt_uid_jabatan '; $sql .= 'ORDER BY JABATAN ASC'; $q = $this->db->query($sql); return $q->result(); break; case 'level': return json_decode(json_encode(array( array('ID'=>1,'LEVEL'=> 'OPERATOR'), array('ID'=>2,'LEVEL'=> 'SUPERVISI'), array('ID'=>3,'LEVEL'=> 'MANAGER'), array('ID'=>9,'LEVEL'=> 'ADMINISTRATOR') ))); break; case 'regional': $sql = 'SELECT * FROM dt_regional '; $sql .= 'ORDER BY NAMA_REGIONAL ASC'; $q = $this->db->query($sql); return $q->result(); break; case 'cabang': $sql = 'SELECT * FROM dt_cabang '; $sql .= 'ORDER BY NAMA_CABANG ASC'; $q = $this->db->query($sql); return $q->result(); } } function addUser($post) { $sql = "INSERT INTO admin (username,password,fullname) VALUES (?,?,?)"; $status = $this->db->query($sql,$post); if($status){ return array($status,'Data telah ditambahkan'); } else { return array($status, $this->db->error()); } } function deleteUser($uid) { $sql = "DELETE FROM admin WHERE id = ?"; return $this->db->query($sql,array($uid)); } function getUserById($uid){ $sql = 'SELECT * FROM uid WHERE UID = ? ORDER BY NAMA ASC LIMIT 0,1'; $q = $this->db->query($sql,[$uid]); return $q->result(); } function editUser($post){ if(isset($post['id_admin']) && $post['id_admin'] > 0){ $sql = "UPDATE admin SET username = ?, fullname = ? WHERE id = ?"; $status = $this->db->query($sql,array($post['username'],$post['fullname'],$post['id_admin'])); if($status){ return array($status,'Data telah diupdate'); } else { return array($status, $this->db->error()); } } else { return array(false, 'Data invalid'); } } function getLogs() { $sql = 'SELECT TGL,UID,AKSI,APP_FORM,RESUME,IP_ADDRESS,COMP_NAME,TIME_STAMP FROM log '; $sql .= 'ORDER BY TIME_STAMP DESC'; $q = $this->db->query($sql); return $q->result(); } function getUsersForDdl() { $sql = 'SELECT UID,NAMA FROM uid '; $sql .= 'ORDER BY NAMA ASC'; $q = $this->db->query($sql); return $q->result(); } } ?>
php
20
0.479833
111
30.678414
227
starcoderdata
<div class="content-wrapper"> <section class="content-header"> <i class="glyphicon glyphicon-list-alt"> Struktur Organisasi Edit, Delete <section class="content"> <div class="row"> <div style="padding-left: 8%; " class="col-md-11"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> <!-- /.box-header --> <!-- form start --> <form role="form" > <?php foreach ($list as $so){ ?> <img style=" width: 600px;" src="<?php echo base_url('assets/images/so/'.$so->gambar) ?>" alt="Gambar tidak tampil"> <?php } ?> <!-- /.box --> <div class=" col-xs-12 text-right"> <a class="btn btn-info" href="<?php echo base_url(); ?>strukturorganisasi/edit/<?php echo $so->id_so ?>">Ubah
php
10
0.428033
164
31.390244
41
starcoderdata
#include #include #include #include void * f(void * x) { long i = (long)x; return (void *)(i * i); } myth_thread_t parent_th; myth_thread_t th[1000]; void * ret[1000]; //#define nthreads 100 int main(int argc, char ** argv) { int nthreads = (argc > 1 ? atoi(argv[1]) : 100); long i; parent_th = myth_self(); for (i = 0; i < nthreads; i++) { th[i] = myth_create(f, (void *)i); myth_join(th[i], &ret[i]); if (ret[i] != (void *)(i * i)) { printf("NG\n"); return 1; } } #if 0 for (i = 0; i < nthreads; i++) { void * ret[1]; myth_join(th[i], ret); if (ret[0] != (void *)(i * i)) { printf("NG\n"); return 1; } } #endif printf("OK\n"); return 0; }
c
12
0.506494
50
17.333333
42
starcoderdata
def discover_address(configfile): import appuifw CONFIG_FILE=os.path.join(CONFIG_DIR,configfile) try: f=open(CONFIG_FILE,'r') config=eval(f.read()) f.close() except: config={} address=config.get('target','') if address: choice=appuifw.popup_menu([u'Default host', u'Other...'],u'Connect to:') if choice==1: address=None if choice==None: return None # popup menu was cancelled. if not address: print "Discovering..." addr,services=socket.bt_discover() print "Discovered: %s, %s"%(addr,services) if len(services)>1: choices=services.keys() choices.sort() choice=appuifw.popup_menu([unicode(services[x])+": "+x for x in choices],u'Choose port:') port=services[choices[choice]] else: port=services[services.keys()[0]] address=(addr,port) config['target']=address # make sure the configuration file exists. if not os.path.isdir(CONFIG_DIR): os.makedirs(CONFIG_DIR) f=open(CONFIG_FILE,'wt') f.write(repr(config)) f.close() return address
python
17
0.528099
73
31.5
40
inline
static int SYMBOL(regexec_br)(struct rx *rx) { DPRINTF("i_regexp: entering branch, pc = %p, spos = \"%s\"", rx->piece, rx->spos); while (rx->piece->type != PT_GUARD) { if (rx->piece->type == PT_BRANCH) break; DPRINTF("i_regexec_br: pc = %p, spos = \"%s\"", rx->piece, rx->spos); if (!SYMBOL(regexec_p)(rx)) { DPRINTF("i_regexec_br: branch failed"); return 0; } // rx->piece = rx->piece->next; } DPRINTF("i_regexec_br: branch succeeded, spos = \"%s\"", rx->spos); return 1; }
c
11
0.572549
83
23.333333
21
inline
// // SBKUnitConvertHelper.h // Sensoro Beacon Kit // // Created by on 14/12/26. // Copyright (c) 2014年 Sensoro Inc. All rights reserved. // #import #import "SBKConstants.h" @class SBKBeacon; /** * The SBKUnitConvertHelper class is a utitlity tool class to help developer to convert enum to a readable text * or value. * */ @interface SBKUnitConvertHelper : NSObject /** * Get the radius of beacon's region, unit is meter. * * @param beacon which beacon. * * @return the radius of region, unit is meter. */ + (float) rangeRadiusOfBeacon: (SBKBeacon *) beacon; /** * Get transmit power of beacon, unit is dBm. * * @param beacon which beacon. * * @return transmit power of beacon. */ + (short) transmitPowerToRawValue: (SBKBeacon *) beacon; /** * Get broadcast interval of beacon, unit is ms. * * @param beacon which beacon. * * @return broadcast interval of beacon. */ + (float) frequencyToRawValue: (SBKBeacon *) beacon; /** * Get descripton of transmit power of beacon. * * @param beacon which beacon. * * @return descripton of transmit power of beacon. */ + (NSString*) transmitPowerToString: (SBKBeacon *) beacon; /** * Get description of broadcast interval of beacon. * * @param beacon which beacon. * * @return description of broadcast interval of beacon. */ + (NSString*) frequencyToString: (SBKBeacon *) beacon; /** * Flag to indicator whether the beacon use micro antenna. * * @param beacon which beacon. * * @return YES : use micro antenna, NO : use normal antenna. */ + (BOOL)isMicroTX:(SBKBeacon *) beacon; @end
c
7
0.689229
112
21.064935
77
starcoderdata
import argparse import os import tarfile import warnings import numpy as np import pandas as pd from sklearn.compose import make_column_transformer from sklearn.exceptions import DataConversionWarning from sklearn.model_selection import train_test_split from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder, StandardScaler warnings.filterwarnings(action="ignore", category=DataConversionWarning) try: from sklearn.externals import joblib except: import joblib columns = [ "age", "education", "major industry code", "class of worker", "num persons worked for employer", "capital gains", "capital losses", "dividends from stocks", "income", ] target_col = "income" class_labels = [" - 50000.", " 50000+."] def read_data(input_data_path): print(f"Reading input data from {input_data_path}") df = pd.read_csv(input_data_path) df = pd.DataFrame(data=df, columns=columns) df.dropna(inplace=True) df.drop_duplicates(inplace=True) df.replace(class_labels, list(range(len(class_labels))), inplace=True) negative_examples, positive_examples = np.bincount(df[target_col]) print( f"Data after cleaning: {df.shape}, {positive_examples} positive examples, " f"{negative_examples} negative examples" ) return df def transform(df, args, preprocess=None): if preprocess is None: model_directory = os.path.join(args.data_dir, "model") print(f"Reading model from {model_directory}") with tarfile.open( os.path.join(model_directory, "proc_model.tar.gz"), mode="r:gz" ) as archive: print(f"Exctracting tarfile to {model_directory}") archive.extractall(path=model_directory) preprocess = joblib.load(os.path.join(model_directory, "model.joblib")) features = preprocess.transform(df) print(f"Data shape after preprocessing: {features.shape}") return features def write_data(data, args, file_prefix): output_path = os.path.join(args.data_dir, file_prefix) print(f"Saving data to {output_path}") pd.DataFrame(data).to_csv(output_path, header=False, index=False) def split_data(df, args): split_ratio = args.train_test_split_ratio print(f"Splitting data into train and test sets with ratio {split_ratio}") return train_test_split( df.drop(target_col, axis=1), df[target_col], test_size=split_ratio, random_state=0, ) def fit(df, args): preprocess = make_column_transformer( ( ["age", "num persons worked for employer"], KBinsDiscretizer(encode="onehot-dense", n_bins=10), ), ( ["capital gains", "capital losses", "dividends from stocks"], StandardScaler(), ), ( ["education", "major industry code", "class of worker"], OneHotEncoder(sparse=False), ), ) print("Creating preprocessing and feature engineering transformations") preprocess.fit(df) joblib.dump(preprocess, "./model.joblib") model_output_directory = os.path.join(args.data_dir, "model/proc_model.tar.gz") print(f"Saving model to {model_output_directory}") with tarfile.open(model_output_directory, mode="w:gz") as archive: archive.add("./model.joblib", recursive=True) return preprocess def parse_arg(): parser = argparse.ArgumentParser() parser.add_argument("--mode", type=str, default="infer") parser.add_argument("--train-test-split-ratio", type=float, default=0.3) parser.add_argument("--data-dir", type=str, default="opt/ml/processing") parser.add_argument("--data-input", type=str, default="input/census-income.csv") args, _ = parser.parse_known_args() print(f"Received arguments {args}") return args def main(args): """ To run locally: DATA=s3://sagemaker-sample-data-us-east-1/processing/census/census-income.csv aws s3 cp $DATA /tmp/input/ mkdir /tmp/{train,test,model} python preprocessing.py --mode "train" --data-dir /tmp """ input_data_path = os.path.join(args.data_dir, args.data_input) df = read_data(input_data_path) if args.mode == "infer": test_features = transform(df, args) write_data(test_features, args, "test/test_features.csv") if target_col in df.columns: write_data(df[target_col], args, "test/test_labels.csv") return test_features elif args.mode == "train": X_train, X_test, y_train, y_test = split_data(df, args) preprocess = fit(X_train, args) train_features = transform(X_train, args, preprocess) test_features = transform(X_test, args, preprocess) write_data(train_features, args, "train/train_features.csv") write_data(y_train, args, "train/train_labels.csv") write_data(test_features, args, "test/test_features.csv") write_data(y_test, args, "test/test_labels.csv") return train_features, test_features if __name__ == "__main__": args = parse_arg() main(args)
python
14
0.658003
84
32.887417
151
starcoderdata
protected void populateEmptyMandatoryFieldMap(Object fieldGroups, ExpeditedAdverseEventInputCommand command){ Map<String, InputFieldGroup> groupMap = (Map<String, InputFieldGroup>) fieldGroups; if (groupMap == null) return; emptyFieldNameMap = new HashMap<String, Boolean>(); for (InputFieldGroup group : groupMap.values()) { for (InputField field : group.getFields()) { //for every required or mandatory field, check if value is provided. if(field.isRequired() || field.getAttributes().get(MANDATORY_FIELD_ATTR) != null){ List<UnsatisfiedProperty> unsatisfiedProps = expeditedReportTree.verifyPropertiesPresent(field.getPropertyName().substring(9), command.getAeReport()); for(UnsatisfiedProperty unsatisfiedProperty : unsatisfiedProps){ String unsatisfiedPropertyName = unsatisfiedProperty.getBeanPropertyName(); emptyFieldNameMap.put("aeReport." + unsatisfiedPropertyName.substring(0, unsatisfiedPropertyName.indexOf("].") + 1), Boolean.TRUE); } } } } }
java
21
0.653026
165
54.904762
21
inline
private void init(Context context) { dialogWidth = context.getResources().getDimensionPixelSize(R.dimen.sd_dialog_width); float dimAmount = AttrResources.getAttrFloat(context, android.R.attr.backgroundDimAmount); // Ensure backgroundDimAmount is in range dimAmount = clamp(dimAmount, 0.0f, 1.0f); final int alpha = (int) (255 * dimAmount); backgroundDimColor = Color.argb(alpha, 0, 0, 0); }
java
10
0.724221
94
45.444444
9
inline
func (f *Files) fileLoop( iFile int, hx, hv [][3]float64, hr []float64, work HaloWork, subsample ...int, ) { if hv == nil { hv = make([][3]float64, len(hx)) } xp, vp, mp, idp := f.Read(iFile, subsample...) // Make finder; need the simulation width hd := &sio.Header{} finders := make([]*box.Finder, runtime.NumCPU()) for i := range finders { f.buf.ReadHeader(f.Names[iFile], hd) finders[i] = box.NewFinder(hd.TotalWidth, xp) } loopWork := func (worker, istart, iend, istep int) { xbuf, vbuf := [][3]float64{}, [][3]float64{} mbuf, idbuf := []float64{}, []int{} for ih := istart; ih < iend; ih += istep { // halo index // Indices of particles in halo idx := finders[worker].Find(hx[ih], hr[ih]) // resize buffers xbuf, vbuf = expandVec(xbuf, len(idx)), expandVec(vbuf, len(idx)) mbuf = expandFloat(mbuf, len(idx)) idbuf = expandInt(idbuf, len(idx)) for j := range idx { ip := idx[j] // particle index for k := 0; k < 3; k ++ { xbuf[j][k] = box.SymBound( xp[ip][k] - hx[ih][k], hd.TotalWidth, ) vbuf[j][k] = vp[ip][k] - hv[ih][k] } mbuf[j] = mp[ip] idbuf[j] = idp[ip] } // Finally, do the work: work(ih, xbuf, vbuf, mbuf, idbuf) } } thread.SplitArray(len(hx), runtime.NumCPU(), loopWork, thread.Jump()) //thread.SplitArray(len(hx), 2, loopWork, thread.Jump()) }
go
20
0.578488
70
26
51
inline
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.target; import com.intellij.execution.target.value.TargetValue; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * A request for target environment. * * Can be filled with the requirements for target environment like files to upload, * ports to bind and locations to imported from another environents. * * Implementations must cancel promises of all created TargetValues */ @ApiStatus.Experimental public interface TargetEnvironmentRequest { /** * @return a platform of the environment to be prepared. * The result heavily depends on the {@link TargetEnvironmentFactory#getTargetPlatform()} */ @NotNull TargetPlatform getTargetPlatform(); /** * Creates the requirement to upload the local path up to the target environment. * * Returned value may be used in {@link TargetedCommandLineBuilder} * where it will be replaced to the corresponding path at the target machine. */ @NotNull TargetValue createUpload(@NotNull String localPath); /** * Creates the requirement to open a port on the target environment. * * Returned value may be used in {@link TargetedCommandLineBuilder} * where it will be replaced to the passed port. * * As soon as target will be prepared, the value will also contain the port on local machine * that corresponds to the targetPort on target machine. */ @NotNull TargetValue bindTargetPort(int targetPort); }
java
6
0.75074
140
35.717391
46
starcoderdata
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.management; import com.opengamma.engine.view.ViewProcessState; import com.opengamma.id.UniqueId; /** * A management bean for a View * @deprecated use ViewProcessMXBean */ @Deprecated public interface ViewProcessMBean { /** * Gets the unique identifier of the view process. * * @return the identifier, not null */ UniqueId getUniqueId(); /** * Gets the portfolio Identifier * * @return the portfolio identifier */ String getPortfolioId(); /** * Gets the name of the underlying view definition * * @return the name of the underlying view definition */ UniqueId getDefinitionId(); /** * Gets the state of the view process. * * @return the computation state of the view process, not null */ ViewProcessState getState(); /** * Gets whether the view process is persistent. * * @return true if the view process is persistent, false otherwise */ boolean isPersistent(); /** * Terminates this view process, detaching any clients from it. */ void shutdown(); /** * Suspends all operations on the view, blocking until everything is in a suspendable state. While suspended, * any operations which would alter the state of the view will block until {@link #resume} is called. */ void suspend(); /** * Resumes operations on the view suspended by {@link #suspend}. */ void resume(); }
java
4
0.677141
111
22.185714
70
starcoderdata
namespace QianCash.Core; public class AccountBalance { public string AccountId { get; set; } = string.Empty; public List Balances { get; set; } = new List public DateTimeOffset LastSync { get; set; } public string GetBalance() => "hahaha"; }
c#
7
0.68693
66
24.384615
13
starcoderdata
import axios from 'utils/axios.js' // 课程导航 export function getLessonNav () { return axios.get('/api/label/list') } // 课程列表 export function getLessonList (params) { return axios.get('/api/lesson/list', { params }) } // 课程详情 export function getLessonDetail (params) { return axios.get('/api/lesson/info', { params }) } // 课程目录 export function getLessonComment (params) { return axios.get('/api/lesson/comment', { params }) } // 课程问答 export function getLessonQa (params) { return axios.get('/api/lesson/qa', { params }) }
javascript
6
0.66723
43
15.914286
35
starcoderdata
#ifndef MD_AUDIO_CONSTANTS_HPP #define MD_AUDIO_CONSTANTS_HPP namespace md_audio { constexpr auto sample_rate = static_cast constexpr auto sample_duration = 1. / sample_rate; constexpr auto half_sample_rate = sample_rate * .5; constexpr auto two_pi = 6.2831853071795862; constexpr auto pi = 3.1415926535897931; constexpr auto three_quarter_pi = 2.3561944901923448; constexpr auto half_pi = 1.5707963267948966; constexpr auto quarter_pi = .7853981633974483; constexpr auto pi_over_sample_rate = pi * sample_duration; } #endif /* MD_AUDIO_CONSTANTS_HPP */
c++
10
0.717949
62
28.714286
21
starcoderdata
void InitializeSandbox() { // create some history objects CreateHistory(&previous_history_hash); CreateHistory(&history_hash, previous_history_hash); // create a catalog CreateCatalog(&root_hash, ""); if (NeedsFilesystemSandbox()) { WriteKeychain(); WriteManifest(); WriteWhitelist(); InitializeExternalManagers(); } }
c++
8
0.65508
56
24
15
inline
'use strict'; /** * install * * install command * */ const ora = require('ora'); const log = require('../log'); const { baseDir, pkgFile, getCfg, getPkgJsonFromRegistry, getPluginName, execNpmCommand, getLocalPluginVersion, } = require('../utils'); const { NOTFOUNDVERSION } = require('../config'); const NOTNEEDUPDATE = -1; function checkPlugins(plugins) { if (!plugins.length) { return Promise.resolve([]); } const config = getCfg(); const registry = config && config.registry; return Promise.all( plugins.map(p => { const localVersion = getLocalPluginVersion(p); if (localVersion === NOTFOUNDVERSION) { return Promise.resolve(p); } else { return getPkgJsonFromRegistry(p, 'latest', registry).then( json => { const latestVersion = json.version; if (latestVersion !== localVersion) { return p; } else { return NOTNEEDUPDATE; } }, err => { log.error(`获取 ${p} 最新版本失败: ${JSON.stringify(err)}`); return p; } ); } }) ).then( list => { return list.filter(p => { return p !== NOTNEEDUPDATE; }); }, err => { log.error(`获取需要更新的插件列表失败: ${JSON.stringify(err)}`); return []; } ); } function install(plugins) { if (!plugins || !plugins.length) { return Promise.resolve([]); } const { dependencies = {} } = require(pkgFile); const notInstalled = []; const hasInstalled = []; plugins.forEach(p => { const name = getPluginName(p); if (dependencies[name]) { hasInstalled.push(name); } else { notInstalled.push(name); } }); return checkPlugins(hasInstalled) .then(list => { const needUpdateList = list.concat(notInstalled); if (!needUpdateList.length) { log.info('检测到您本地安装的已经是最新的插件,无需重复安装'); return needUpdateList; } const pluginListString = needUpdateList.join(' '); const loading = ora(`Install ${pluginListString}`).start(); return execNpmCommand('install', needUpdateList, false, baseDir).then( () => { loading.succeed(); log.info(`成功安装插件: ${pluginListString}`); return needUpdateList; }, result => { const errMsg = `安装插件失败,插件列表: ${pluginListString},错误码: ${result.code}, 错误日志: ${result.data}`; loading.fail(errMsg); log.error(errMsg); return []; // 安装失败,返回空列表 } ); }) .catch(err => { log.error(`安装插件遇到未知错误: ${JSON.stringify(err)}`); return []; }); } module.exports = install;
javascript
27
0.553538
102
20.943089
123
starcoderdata
package patterns; class pattern8 { void main() { int sum=0; for(int i=0;i<=10;i++) { int power = (int)Math.pow(2, i); sum=sum+power; } System.out.print(sum); } }
java
12
0.453744
44
16.538462
13
starcoderdata
# Copyright 2019 Google LLC # # 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. """Tests for google3.wireless.android.test_tools.tradefed_cluster.metric.""" import datetime import unittest import mock import pytz from tradefed_cluster import metric TIMESTAMP_NAIVE = datetime.datetime(2017, 10, 11) TIMESTAMP_AWARE = pytz.utc.localize(datetime.datetime(2017, 10, 10, 21)) UTC_NOW = datetime.datetime(2017, 10, 11, 1) class MetricTest(unittest.TestCase): @mock.patch('__main__.metric.datetime') @mock.patch.object(metric.command_timing, 'Record', autospec=True) def testRecordCommandTimingMetric_naiveDatetime(self, record, mock_datetime): mock_datetime.datetime.utcnow.return_value = UTC_NOW metric.RecordCommandTimingMetric( cluster_id='cluster', run_target='target', create_timestamp=TIMESTAMP_NAIVE, command_action=metric.CommandAction.LEASE) expected_latency = 60 * 60 # 1 hour in seconds expected_metric_fields = { metric.METRIC_FIELD_CLUSTER: 'cluster', metric.METRIC_FIELD_RUN_TARGET: 'target', metric.METRIC_FIELD_ACTION: 'LEASE', metric.METRIC_FIELD_HOSTNAME: None } record.assert_called_once_with(expected_latency, expected_metric_fields) @mock.patch('__main__.metric.datetime') @mock.patch.object(metric.command_timing, 'Record', autospec=True) def testRecordCommandTimingMetric_awareDatetime(self, record, mock_datetime): mock_datetime.datetime.utcnow.return_value = UTC_NOW metric.RecordCommandTimingMetric( cluster_id='cluster', run_target='target', create_timestamp=TIMESTAMP_AWARE, command_action=metric.CommandAction.RESCHEDULE) expected_latency = 4 * 60 * 60 # 4 hours in seconds expected_metric_fields = { metric.METRIC_FIELD_CLUSTER: 'cluster', metric.METRIC_FIELD_RUN_TARGET: 'target', metric.METRIC_FIELD_ACTION: 'RESCHEDULE', metric.METRIC_FIELD_HOSTNAME: None } record.assert_called_once_with(expected_latency, expected_metric_fields) @mock.patch.object(metric.command_action_count, 'Increment', autospec=True) @mock.patch.object(metric.command_timing, 'Record', autospec=True) def testRecordCommandTimingMetric_givenLatency(self, record, increment): metric.RecordCommandTimingMetric( cluster_id='cluster', run_target='target', command_action=metric.CommandAction.INVOCATION_FETCH_BUILD, latency_secs=100) expected_metric_fields = { metric.METRIC_FIELD_CLUSTER: 'cluster', metric.METRIC_FIELD_RUN_TARGET: 'target', metric.METRIC_FIELD_ACTION: 'INVOCATION_FETCH_BUILD', metric.METRIC_FIELD_HOSTNAME: None } record.assert_called_once_with(100, expected_metric_fields) increment.assert_not_called() @mock.patch.object(metric.command_action_count, 'Increment', autospec=True) @mock.patch.object(metric.command_timing, 'Record', autospec=True) def testRecordCommandTimingMetric_withCount(self, record, increment): metric.RecordCommandTimingMetric( cluster_id='cluster', run_target='target', command_action=metric.CommandAction.INVOCATION_FETCH_BUILD, latency_secs=100, hostname='example.mtv', count=True) expected_metric_fields = { metric.METRIC_FIELD_CLUSTER: 'cluster', metric.METRIC_FIELD_RUN_TARGET: 'target', metric.METRIC_FIELD_ACTION: 'INVOCATION_FETCH_BUILD', metric.METRIC_FIELD_HOSTNAME: 'example.mtv' } record.assert_called_once_with(100, expected_metric_fields) increment.assert_called_once_with(expected_metric_fields) if __name__ == '__main__': unittest.main()
python
12
0.712411
79
38.528302
106
starcoderdata
import React from "react"; const Form = ({ handleSubmit }) => { return ( <form onSubmit={handleSubmit} id="form"> 5 Dai/Transaction Address:{" "} <input type="text" id="address" required="required" placeholder="Enter receiving address" /> <br /> Amount:{" "} <input type="text" id="amount" required="required" placeholder="Enter amount to transfer" /> <br /> ); }; export default Form;
javascript
13
0.4426
50
20.909091
33
starcoderdata
package internal import ( "github.com/go-gl/gl/v4.1-core/gl" "github.com/go-gl/glfw/v3.3/glfw" "github.com/go-gl/mathgl/mgl32" log "github.com/sirupsen/logrus" mygl "terrain/internal/gl" ) type Window struct { GLWindow *mygl.Window Near, Far float32 camera *Camera projection mgl32.Mat4 timer *Timer current, delta float64 } func NewWindow(width, height int) (window *Window, terminate func()) { terminate = GLFWMustInit() var err error window = new(Window) window.GLWindow, err = mygl.CreateWindow(width, height) if err != nil { log.WithError(err).Panic("failed to create window") } window.GLWindow.MakeContextCurrent() window.GLWindow.SetKeyCallback(keyCallback()) window.GLWindow.SetCursorPosCallback(cursorCallback) if err := gl.Init(); err != nil { log.WithError(err).Panic("failed to init GL") panic(err) } gl.Viewport(0, 0, int32(width), int32(height)) gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) //gl.ClearColor(1.0, 0.9, 0.8, 0.7) window.camera = new(Camera) window.camera.Position = mgl32.Vec3{10, 10, 10} window.camera.WorldUp = mgl32.Vec3{0, 1, 0} window.camera.Yaw, window.camera.Pitch, window.camera.Zoom = 0, 0, 0 window.camera.MovementSpeed, window.camera.RotationSpeed = 30, 100 window.Near, window.Far = 0.1, 100 window.projection = projectionMatrix(width, height, window.Near, window.Far) window.timer = NewTimer() return } func (window *Window) IsOpen() bool { return !window.GLWindow.ShouldClose() } func (window *Window) GetSize() (int, int) { return window.GLWindow.GetSize() } func (window *Window) Camera() *Camera { return window.camera } func projectionMatrix(windowWidth, windowHeight int, near, far float32) mgl32.Mat4 { return mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/float32(windowHeight), near, far, ) } func (window *Window) Projection() mgl32.Mat4 { return window.projection } func (window *Window) CurrentTime() float64 { return window.current } func (window *Window) DeltaTime() float64 { return window.delta } func (window *Window) Render(drawer func()) { for !window.GLWindow.ShouldClose() { window.GLWindow.SwapBuffers() glfw.PollEvents() gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) width, height := window.GetSize() gl.Viewport(0, 0, int32(width), int32(height)) window.current, window.delta = window.timer.Update() window.moveCamera(window.delta) window.projection = projectionMatrix(width, height, window.Near, window.Far) drawer() } } var movementMap = map[glfw.Key]Direction{ glfw.KeyW: ForwardDirection, glfw.KeyS: BackwardDirection, glfw.KeyA: LeftDirection, glfw.KeyD: RightDirection, glfw.KeyR: UpRotation, glfw.KeyF: DownRotation, glfw.KeyQ: LeftRotation, glfw.KeyE: RightRotation, } func (window *Window) moveCamera(delta float64) { for key, direction := range movementMap { if _, ok := PressedKeys[key]; ok { window.camera.Move(delta, direction) } } } var PressedKeys = map[glfw.Key]struct{}{} func keyCallback() mygl.KeyCallback { var ( fullScreen bool prevXPos, prevYPos, prevHeight, prevWidth int ) return func(window *mygl.Window, key glfw.Key, action glfw.Action) { if key == glfw.KeyEscape && action == glfw.Press { window.SetShouldClose(true) return } if key == glfw.KeyF11 && action == glfw.Press { if fullScreen { window.UnFullScreen(prevXPos, prevYPos, prevWidth, prevHeight) } else { prevXPos, prevYPos = window.GetPos() prevWidth, prevHeight = window.GetSize() window.FullScreen(mygl.GetPrimaryMonitor()) } fullScreen = !fullScreen } switch action { case glfw.Press: PressedKeys[key] = struct{}{} case glfw.Release: delete(PressedKeys, key) } } } var CursorX, CursorY float64 func cursorCallback(_ *glfw.Window, xPos float64, yPos float64) { CursorX, CursorY = xPos, yPos }
go
16
0.706954
84
23.35625
160
starcoderdata
// // Created by xshx on 2021/9/29. // #include "uart5.h" #include "middle/commen_middle.h" #include "middle/uart5_middle.h" //extern xQueueHandle Uart8FromUart5MsgQueue; static const char *logtag ="[UART5]-"; unsigned char Init_Request[128]="230105302E302E32DDEC"; int uart5_status; int ProcMessageByHead(unsigned char nHead,unsigned char nCommand,unsigned char nMessageLen,unsigned char *pszMessage) { printf("%s ======Head[0x%x],Command[0x%x], nMessageLen Message logtag, nHead,nCommand, nMessageLen, pszMessage); switch (nCommand) { case CMD_INITOK_SYNC: { printf("%s 初始化完成\n", logtag); cmdSysInitOKSyncRsp(nMessageLen, pszMessage); break; } case CMD_OPEN_DOOR: { cmdOpenDoorRsp(nMessageLen, pszMessage); break; } case CMD_TEMPER_DATA:{//测温请求回复 cmdTemperRsp( nMessageLen, pszMessage ); break; } case CMD_CLOSE_FACEBOARD: { cmdPowerDownRsp(nMessageLen, pszMessage); break; } case CMD_FACE_REG: { cmdUserRegReqProc(nMessageLen, pszMessage); break; } case CMD_FACE_REG_RLT: { break; } case CMD_NTP_SYS_TIME: { cmdSetSysTimeSynProc(nMessageLen, pszMessage); break; } case CMD_FACE_DELETE_USER: { cmdDeleteUserReqProcByHead(/*HEAD_MARK*/nHead, nMessageLen, pszMessage); break; } case CMD_REQ_RESUME_FACTORY: { cmdReqResumeFactoryProc(nMessageLen, pszMessage); break; } case CMD_REG_ACTIVE_BY_PHONE: { cmdReqActiveByPhoneProc(nMessageLen, pszMessage); break; } case CMD_WIFI_SSID: { cmdWifiSSIDProc(nMessageLen, pszMessage); break; } case CMD_WIFI_PWD: { cmdWifiPwdProc(nMessageLen, pszMessage); break; } case CMD_WIFI_MQTT: { cmdMqttParamSetProc(nMessageLen, pszMessage); break; } case CMD_WIFI_TIME_SYNC: { cmdWifiTimeSyncRsp(nMessageLen, pszMessage); break; } case CMD_ORDER_TIME_SYNC: { cmdWifiOrderTimeSyncRsp(nMessageLen, pszMessage); break; } case CMD_WIFI_OPEN_DOOR: { cmdWifiOpenDoorRsp(nMessageLen, pszMessage); break; } case CMD_BT_INFO: { printf("%s 收到蓝牙消息\n",logtag); cmdBTInfoRptProc(nMessageLen, pszMessage); break; } case CMD_WIFI_MQTTSER_URL: { cmdMqttSvrURLProc(nMessageLen, pszMessage); break; } case CMD_MECHANICAL_LOCK: { // cmdMechicalLockRsp(nMessageLen, pszMessage); break; } default: printf("%s 收到其他消息\n",logtag); break; } return 0; } static int ProcessMessage(unsigned char nCommand,unsigned char nMessageLen, unsigned char *pszMessage) { ProcMessageByHead(HEAD_MARK, nCommand, nMessageLen, pszMessage); return 0; } static void Uart5InitTask( void *pvParameters){ printf("%s 初始化 \n", logtag); SendMessageToMCUFromUart5( Init_Request); vTaskDelete(NULL); } static void Uart5MainTask( void *pvParameters){ printf("%s 创建 Main Task \n", logtag); // while (1 ){ // if( UART5_FREE == uart5_status && ) // // } vTaskDelete(NULL); } static void Uart5ReceiveMcuTask( void *pvParameters){ uint8_t recv_buffer[128] = {0}; printf("%s 创建 recive mcu Task \n", logtag); LPUART_RTOS_Init(); for (;;) { //查询消息 while (uxQueueMessagesWaiting(Uart5FromMcuMsgQueue)) { printf("%s 接收串口消息\n", logtag); int msglen = 0; unsigned char HeadMark; unsigned char CmdId = 0; unsigned char datalen = 0; uint8_t recv_buffer[64] = {0}; uint8_t buffer[128] = {0}; const unsigned char *pszMsgInfo = NULL; if (LPUART_RTOS_Receive(buffer, sizeof(buffer)) == pdPASS) { //处理消息 printf("%s 处理串口消息\n", logtag); StrToHex(recv_buffer, buffer, sizeof(recv_buffer)); pszMsgInfo = MsgHead_Unpacket(recv_buffer, msglen, &HeadMark, &CmdId, &datalen); printf("%s %s \n", logtag, pszMsgInfo); ProcessMessage(CmdId, datalen, pszMsgInfo); } // vTaskDelay(pdMS_TO_TICKS(1000)); } } } static void Uart5ReceiveUart8Task(void *pvParamters) { printf("%s 创建接收Uart8 消息TASK \n", logtag); Message message; portBASE_TYPE xStatus; const portTickType xTicksToWait = 100 / portTICK_RATE_MS; for (;;) { while (uxQueueMessagesWaiting(Uart5FromUart8MsgQueue)) { if (xQueueReceive(Uart5FromUart8MsgQueue, &message, xTicksToWait) == pdPASS) { printf("%s receive[SenderID %d ID = %d DATA = %s]\n", logtag, message.SenderID, message.MessageID, message.Data); } else { printf("%s receive error %d \n", logtag, xStatus); } // vTaskDelay(pdMS_TO_TICKS(1000)); } } } int uart5_task_start(void ){ Uart5FromUart8MsgQueue = xQueueCreate(5, sizeof(Message)); Uart5FromMcuMsgQueue = xQueueCreate(5, sizeof(Message)); if (xTaskCreate(Uart5InitTask, "uart5 init", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS) { printf("创建uart5 init task \n"); } if (xTaskCreate(Uart5MainTask, "uart5 main", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS) { printf("创建uart5 main task \n"); } if (xTaskCreate(Uart5ReceiveMcuTask, "uart5 receive mcu", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS) { printf("创建uart5 receive mcu task \n"); } if (xTaskCreate(Uart5ReceiveUart8Task, "uart5 receive uart8", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS) { printf("创建uart5 receive uart8 task \n"); } return 0; }
c
14
0.569821
138
29.483092
207
starcoderdata
import decimal """ SI unit prefix names, from yocto to yotta. """ PREFIX = u'yzafpn\u03BCm kMGTPEZY' """ Power 10 exponential corresponding to the min/max in *PREFIX*. """ SHIFT = decimal.Decimal('1E24') def sistr(x, baseunit=''): """ Return the string representation of *x* using the SI convention, appending *baseunit* if it is provided. Source: https://stackoverflow.com/questions/29627796/pretty-printing-physical-quantities-with-automatic-scaling-of-si-prefixes """ if x == 0: return '0 ' + baseunit d = (decimal.Decimal(str(x)) * SHIFT).normalize() m, e = d.to_eng_string().split('E') return (m + ' ' + PREFIX[int(e) // 3] + baseunit).encode('utf-8') if __name__ == '__main__': print(sistr(10100, 'g')) print(sistr(10100e-12, 'g')) print(sistr(12)) print(sistr(1200)) print(sistr(0)) print(sistr(1e-6))
python
13
0.630804
130
25.757576
33
starcoderdata
public void autoBLDFoundation() { RobotLog.ii("CAL", "Enter - JARVISAutoBLD1Red"); //initialized the motor encoders robot.initMotorEncoders(); // Ensure that the op mode is still active if (opModeIsActive() && !isStopRequested() ) { //move forward to stop dragging along the wall myEncoderDrive(Direction.BACKWARD, 0.1, 2, 5, SensorsToUse.NONE); //Strafe left to be in a better position to move the foundation myEncoderDrive(Direction.STRAFE_LEFT, 0.1, 8, 5, SensorsToUse.NONE); //move to the foundation myEncoderDrive(Direction.BACKWARD, 0.3, 18, 5, SensorsToUse.NONE); //go at a slower speed to make sure we hook on properly myEncoderDrive(Direction.BACKWARD, 0.07, 8, 5, SensorsToUse.NONE); //leave time for the foundation servos to move sleep(500); //move the foundation attachment down moveFoundationServoDown(); //leave time for the foundation servos to move sleep(500); //move backwards with the foundation and bring it close to the wall myEncoderDrive(Direction.FORWARD, 0.2, 31, 5, SensorsToUse.NONE); //leave time for the robot to finish turning sleep(500); //move the foundation attachment up to release the foundation moveFoundationServoUp(); //stop for 10 seconds so the robot is out of the way of the other robots while the //autonomous mode is still going on sleep(8000); //move left to be right next to the foundation myEncoderDrive(Direction.STRAFE_RIGHT, 0.3, 50, 5, SensorsToUse.NONE); } RobotLog.ii("CAL", "Exit - JARVISAutoBLD1Red"); }
java
9
0.610808
94
44.825
40
inline
package com.pancm.others; import com.geccocrawler.gecco.annotation.PipelineName; import com.geccocrawler.gecco.pipeline.Pipeline; import com.pancm.others.GeccoTest; /** * @Description: 运行完GeccoTest.java 根据@PipelineName 来这里 * @Author: ArvinWoo * @Date: 2020/11/26 14:27 * @ClassName: BlogPipelines **/ @PipelineName(value="blogPipelines") public class BlogPipelines implements Pipeline { /** * 将抓取到的内容进行处理 这里是打印在控制台 */ @Override public void process(GeccoTest blog) { System.out.println(blog.getContent()); } }
java
8
0.730337
59
23.96
25
starcoderdata
#include #include #include #include #include #include using namespace std; #define pow2(i) (1<<i) #define bit(i) (1<<i) #define isOdd(i) (i&1) #define isEven(i) (!(i&1)) #define sz(i) i.size() #define REP(i, b, n) for (int i = b; i < n; i++) #define REPI(i, b, n) for (int i = b; i <= n; i++) #define rep(i, n) REP(i, 0, n) #define repi(i, n) REPI(i, 0, n) string notes[12][2] = {{"C","B#"},{"C#","Db"},{"D",""},{"D#","Eb"},{"E","Fb"},{"F","E#"},{"F#","Gb"},{"G",""},{"G#","Ab"},{"A",""},{"A#","Bb"},{"B","Cb"}}; string majorScale[12][2][7]; void split_commands(const string& commandLine, vector &commands) { stringstream iss(commandLine); string command; while (getline(iss, command, ';')) { commands.push_back(command); } } void composeMajorScale() { int diff[] = {2,2,1,2,2,2,1}; rep(i, 12) { rep(j, 2) { if (notes[i][j] == "" || notes[i][j][1] == '#') continue; int pos = i; rep(k, 7) { majorScale[i][j][k] = notes[pos][j]; if (k) { if (majorScale[i][j][k-1][0] == 'G' && notes[pos][j][0] != 'A') majorScale[i][j][k] = notes[pos][!j]; if (majorScale[i][j][k-1][0] != 'G' && notes[pos][j][0] != majorScale[i][j][k-1][0]+1) majorScale[i][j][k] = notes[pos][!j]; } pos += diff[k]; pos %= 12; } } } } int translate(const string& gap) { int result = 0; if (gap == "SECOND") result = 2; if (gap == "THIRD") result = 3; if (gap == "FOURTH") result = 4; if (gap == "FIFTH") result = 5; if (gap == "SIXTH") result = 6; if (gap == "SEVENTH") result = 7; if (gap == "OCTAVE") result = 8; return result; } int main(void) { string scale, commandLine; composeMajorScale(); while (getline(cin, scale)) { getline(cin, commandLine); vector commands; split_commands(commandLine, commands); cout << "Key of " << scale << endl; int x, y; rep (i, 12) { rep (j, 2) { if (notes[i][j] == scale) x = i, y = j; } } rep (c, commands.size()) { stringstream iss(commands[c]); string note, direction, gap; while (iss >> note >> direction >> gap) { cout << note << ": "; int g = translate(gap) - 1; int pos = -1; if (direction == "DOWN") g = -g; rep (i, 7) { if (majorScale[x][y][i] == note) pos = i; } if (pos == -1) { cout << "invalid note for this key" << endl; } else { cout << direction << " " << gap << " > "; pos = (pos + g + 7) % 7; cout << majorScale[x][y][pos] << endl; } } } cout << endl; } return 0; }
c++
18
0.418238
155
25.958333
120
starcoderdata
N=int(input()) a=list(map(int,input().split())) a.sort() if a[-1]==0: f=True elif N%3!=0: f=False elif a[0]==a[N//3-1] and a[N//3]==a[2*N//3-1] and a[2*N//3]==a[-1] and a[0]^a[N//3]==a[-1]: f=True else: f=False print('Yes' if f else 'No')
python
11
0.505837
91
16.2
15
codenet
package Generics; public class TestRunner{ public static void main(String[] args) { TestRunner.initialize(); } public static void initialize() { Team footballTeam1=new Team<>("The FB team",new FootballPlayer[]{new FootballPlayer("zozo",1),new FootballPlayer("zozo",2),new FootballPlayer("zizoi",3)}); Team footballTeam2=new Team<>("The FB Team 2",new FootballPlayer[]{new FootballPlayer("zozo",1),new FootballPlayer("zozo",2),new FootballPlayer("zizoi",3)}); Team baseballTeam1=new Team<>("The BB Team",new BaseballPlayer[]{new BaseballPlayer("zozo",1),new BaseballPlayer("zozo",2),new BaseballPlayer("zizoi",3)}); Team baseballTeam2=new Team<>("The BB Team 2",new BaseballPlayer[]{new BaseballPlayer("zozo",1),new BaseballPlayer("zozo",2),new BaseballPlayer("zizoi",3)}); Team handballTeam1=new Team<>("The HB Team",new HandballPlayer[]{new HandballPlayer("zozo",1),new HandballPlayer("zozo",2),new HandballPlayer("zizoi",3)}); Team handballTeam2=new Team<>("The HB Team 2",new HandballPlayer[]{new HandballPlayer("zozo",1),new HandballPlayer("zozo",2),new HandballPlayer("zizoi",3)}); League league1=new League<>("The knuckles FB"); League league2=new League<>("The knuckles BB"); League league3=new League<>("The knuckles HB"); league1.addTeam(footballTeam1); league1.addTeam(footballTeam2); league2.addTeam(baseballTeam1); league2.addTeam(baseballTeam2); league3.addTeam(handballTeam1); league3.addTeam(handballTeam2); for(int i=0;i<100;i++) { footballTeam1.compete(footballTeam2); baseballTeam1.compete(baseballTeam2); handballTeam1.compete(handballTeam2); } league1.printTeams(); league2.printTeams(); league3.printTeams(); } }
java
14
0.671352
181
48.142857
42
starcoderdata
def main(): """ Main, used to call test cases for this use case""" from redisu.utils.clean import clean_keys global redis redis = Redis(host=os.environ.get("REDIS_HOST", "localhost"), port=os.environ.get("REDIS_PORT", 6379), password=os.environ.get("REDIS_PASSWORD", None), db=0) clean_keys(redis) # Perform the tests test_object_inspection() test_faceted_search() test_hashed_faceting()
python
11
0.630769
64
29.4
15
inline
@Override public BLEDevice device(final ScanResult scanResult) { // Get device by target identifier final BluetoothDevice bluetoothDevice = scanResult.getDevice(); final TargetIdentifier targetIdentifier = new TargetIdentifier(bluetoothDevice); final BLEDevice existingDevice = database.get(targetIdentifier); if (null != existingDevice) { return existingDevice; } // Get device by pseudo device address final PseudoDeviceAddress pseudoDeviceAddress = pseudoDeviceAddress(scanResult); if (null != pseudoDeviceAddress) { // Reuse existing Android device BLEDevice deviceWithSamePseudoDeviceAddress = null; for (final BLEDevice device : database.values()) { if (null != device.pseudoDeviceAddress() && device.pseudoDeviceAddress().equals(pseudoDeviceAddress)) { deviceWithSamePseudoDeviceAddress = device; break; } } if (null != deviceWithSamePseudoDeviceAddress) { database.put(targetIdentifier, deviceWithSamePseudoDeviceAddress); if (deviceWithSamePseudoDeviceAddress.peripheral() != bluetoothDevice) { deviceWithSamePseudoDeviceAddress.peripheral(bluetoothDevice); } if (deviceWithSamePseudoDeviceAddress.operatingSystem() != BLEDeviceOperatingSystem.android) { deviceWithSamePseudoDeviceAddress.operatingSystem(BLEDeviceOperatingSystem.android); } logger.debug("updateAddress (device={})", deviceWithSamePseudoDeviceAddress); return deviceWithSamePseudoDeviceAddress; } // Create new Android device else { final BLEDevice newDevice = device(bluetoothDevice); newDevice.pseudoDeviceAddress(pseudoDeviceAddress); newDevice.operatingSystem(BLEDeviceOperatingSystem.android); return newDevice; } } // Create new device return device(bluetoothDevice); }
java
13
0.63338
119
50.52381
42
inline
class ToolsDialogController { constructor() { this.name = 'toolsDialog'; } } ToolsDialogController.$inject = []; export default ToolsDialogController;
javascript
8
0.73125
37
19
8
starcoderdata
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : Manages layer and heightfield data. #ifndef CRYINCLUDE_EDITOR_TERRAIN_TERRAINMANAGER_H #define CRYINCLUDE_EDITOR_TERRAIN_TERRAINMANAGER_H #pragma once ////////////////////////////////////////////////////////////////////////// // Dependencies #include "Terrain/Heightmap.h" #include "DocMultiArchive.h" ////////////////////////////////////////////////////////////////////////// // Forward declarations class CLayer; class CSurfaceType; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Class class CTerrainManager { public: CTerrainManager(); virtual ~CTerrainManager(); ////////////////////////////////////////////////////////////////////////// // Surface Types. ////////////////////////////////////////////////////////////////////////// // Returns: // can be 0 if the id does not exit CSurfaceType* GetSurfaceTypePtr(int i) const { if (i >= 0 && i < m_surfaceTypes.size()) { return m_surfaceTypes[i]; } return 0; } int GetSurfaceTypeCount() const { return m_surfaceTypes.size(); } //! Find surface type by name, return -1 if name not found. int FindSurfaceType(const QString& name); void RemoveSurfaceType(CSurfaceType* pSrfType); int AddSurfaceType(CSurfaceType* srf); void RemoveAllSurfaceTypes(); void SerializeSurfaceTypes(CXmlArchive& xmlAr, bool bUpdateEngineTerrain = true); void ConsolidateSurfaceTypes(); /** Put surface types from Editor to game. */ void ReloadSurfaceTypes(bool bUpdateEngineTerrain = true, bool bUpdateHeightmap = true); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Layers int GetLayerCount() const { return m_layers.size(); }; CLayer* GetLayer(int layer) const { return layer < GetLayerCount() ? m_layers[layer] : nullptr; }; //! Find layer by name. CLayer* FindLayer(const char* sLayerName) const; CLayer* FindLayerByLayerId(const uint32 dwLayerId) const; void SwapLayers(int layer1, int layer2); void AddLayer(CLayer* layer) { m_layers.push_back(layer); }; void RemoveLayer(CLayer* layer); void ClearLayers(); void SerializeLayerSettings(CXmlArchive& xmlAr); void MarkUsedLayerIds(bool bFree[CLayer::e_undefined]) const; void CreateDefaultLayer(); // slow // Returns: // 0xffffffff if the method failed (internal error) uint32 GetDetailIdLayerFromLayerId(const uint32 dwLayerId); // needed to convert from old layer structure to the new one bool ConvertLayersToRGBLayer(); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Heightmap CHeightmap* GetHeightmap() { return &m_heightmap; }; CRGBLayer* GetRGBLayer(); void SetTerrainSize(int resolution, int unitSize); void ResetHeightMap(); void SetUseTerrain(bool useTerrain); bool GetUseTerrain(); void Save(); bool Load(); void SaveTexture(); bool LoadTexture(); void SerializeTerrain(TDocMultiArchive& arrXmlAr); void SerializeTerrain(CXmlArchive& xmlAr); void SerializeTexture(CXmlArchive& xmlAr); void SetModified(int x1 = 0, int y1 = 0, int x2 = 0, int y2 = 0); void GetTerrainMemoryUsage(ICrySizer* pSizer); ////////////////////////////////////////////////////////////////////////// protected: std::vector > m_surfaceTypes; std::vector m_layers; CHeightmap m_heightmap; }; #endif // CRYINCLUDE_EDITOR_TERRAIN_TERRAINMANAGER_H
c
12
0.568233
102
34.126984
126
starcoderdata
from pathlib import Path from typing import List, Union import time import pandas as pd def print_markdown(markdown): from IPython.display import Markdown, display display(Markdown(markdown)) def print_bullets(lines: List[str]) -> None: """ Display a list of text as bullet points. Args: lines: List of texts Returns: None """ bullet_points = "\n".join(f"- `{line}`" for line in sorted(lines)) print_markdown(bullet_points) def print_header(text: str, level: int = 2) -> None: """ Display a text as markdown header. Args: text: Text level: 2 for H2, 3 for H3 upto 6. Returns: None """ print_markdown(f'{"#" * level} {text}') def highlight_phrases( original_text: str, phrases: Union[List[str], str], color_palette: str = "Greens", weight: float = 0.2, ) -> None: """ Highlight a list of phrases in a text. Args: original_text: Sentence phrases: A single phrase or a list of phrases color_palette: Any valid matplotlib color palette name weight: Darkness of the color Returns: None """ import matplotlib.cm from IPython.display import HTML, display html = original_text cmap = matplotlib.cm.get_cmap(color_palette) color = f"rgba{cmap(weight, bytes=True)}" if type(phrases) is str: phrases = [phrases] for phrase in phrases: highlighted_phrase = ( f'<span style="background-color: {color}; font-weight: {weight * 800};">' f"{phrase}" f" ) html = html.replace(phrase, highlighted_phrase) display(HTML(f'<p style="color: #444; font-size:1.5em;">{html} def filter_column(df: pd.DataFrame, column_name: str) -> None: """ Show an interactive widget to filter a column in dataframe. Args: df: Pandas DataFrame column_name: Column Name of the DataFrame Returns: Interactive widget for filtering. """ from ipywidgets import interact options = sorted(df[column_name].unique()) interact(lambda value: df[df[column_name] == value], value=options) def download(file_path) -> None: """ Download a file at given path. Args: file_path: File path Returns: None """ from IPython.display import Javascript script = f""" var host = window.location.host; var downloadLink = window.location.protocol + "//" + host + "/files/{file_path}" window.open(downloadLink) """ return Javascript(script) def download_df(df: pd.DataFrame, csv_path=None) -> None: """ Download a dataframe as a CSV with a random filename. The filename is set to a random UUID. Args: df: Pandas DataFrame csv_path: CSV filename. Returns: None """ from IPython.display import display if not csv_path: from uuid import uuid4 csv_path = f"{uuid4()}.csv" df.to_csv(csv_path, index=False) display(download(file_path=csv_path)) time.sleep(1) Path(csv_path).unlink() def search_dataframe(df: pd.DataFrame) -> None: """ Show an interactive widget to search text fields of a dataframe. Args: df: Pandas DataFrame Returns: Interactive widget for searching. """ from ipywidgets import interact from IPython.display import display def _search(query: str, column: str): if query: with pd.option_context( "display.max_rows", None, "display.max_columns", None ): filtered_df = df[ df[column].str.contains(query, case=False, regex=False) ] display(filtered_df) string_columns = df.select_dtypes("object").columns.tolist() interact(_search, query="", column=string_columns) def show_examples(df: pd.DataFrame, group_column: str, data_column: str, n: int = 5): """ Show random examples for each sub-group in a dataframe. Args: df: Dataframe group_column: Column name for performing group by data_column: Column to show examples for n: Number of examples Returns: Markdown """ from IPython.display import Markdown generated_text = "" for group_name, subset in df.explode(group_column).groupby(group_column): examples = subset[data_column].sample(n) generated_text += f"## {group_name}\n\n" generated_text += "\n".join([f"- {example}" for example in examples]) generated_text += "\n\n" return Markdown(generated_text)
python
16
0.603942
92
23.836842
190
starcoderdata
from graphene_django import DjangoObjectType from promun.province import models class ProvinceType(DjangoObjectType): class Meta: model = models.Province only_fields = ( 'id', 'name', 'slug', 'towns' ) class TownType(DjangoObjectType): class Meta: model = models.Town only_fields = ( 'id', 'name', 'slug', ) province_types = [ ProvinceType, TownType ]
python
9
0.520875
44
16.344828
29
starcoderdata
package ast; import libs.HtmlOutputter; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; public class GROUPDEC extends STATEMENT { String name; @Override public void parse() { tokenizer.getAndCheckNext("Name"); tokenizer.getAndCheckNext(":"); name = tokenizer.getNext(); name += tokenizer.getNext(); tokenizer.getAndCheckNext(";"); } @Override public String evaluate() throws FileNotFoundException, UnsupportedEncodingException { buildScript(); return null; } private void buildScript() { StringBuilder sb = new StringBuilder(); sb.append("var tr = document.createElement(\"tr\");\n"); sb.append("tr.setAttribute(\"class\", \"row100 body\");\n"); sb.append("var parentDiv = document.getElementById(\"" + getScope() + "\");\n"); sb.append("parentDiv.appendChild(tr);\n"); sb.append("var component = document.createElement(\"td\");\n"); sb.append("component.setAttribute(\"class\", \"cell100 column1\");\n"); sb.append("tr.appendChild(component);\n"); sb.append("var nameNode = document.createTextNode(\"" + name + "\");\n"); sb.append("component.appendChild(nameNode);\n"); HtmlOutputter.writeToFile("scripts.js", sb.toString(), true); } }
java
10
0.635593
89
31.181818
44
starcoderdata
/* * POPAPP Copyright © 2011 All rights reserved. * * This program comes WITHOUT ANY WARRANTY; It is free software, you can redistribute it and/or * modify it under the terms of the GNU General Public License, Version 3.0. * You may obtain a copy of the License at: http://www.gnu.org/licenses/gpl.html */ // P A C K A G E /////////////////////////////////////////////////////////////////////////////////// package co.popapp.model; // I M P O R T ///////////////////////////////////////////////////////////////////////////////////// import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.HashMap; import java.util.Map; // C L A S S /////////////////////////////////////////////////////////////////////////////////////// /** * TODO . * Groups a set of modules (which groups a set of entities). Provides access to metadata. * @author jamming */ public abstract class Model { /** * TODO . * Marker class to define a class which only holds entities. The reason why this class is * not an interface is because I don't want the modules to inherit from other classes, and * because an entity holder 'is a' module. Will be reviewed in the future. * @author jamming */ public static abstract class Module { /* Marker class */ } /** * TODO . * @author jamming */ @Target (ElementType.FIELD) @Retention (RetentionPolicy.RUNTIME) public @interface NotNull { /* Marker annotation */ } /** TODO This will hold ALL the metadata (no matter what Model it belongs). */ private static final Map<Class<? extends Entity>, EntityStructure> STRUCTURE = new HashMap<Class<? extends Entity>, EntityStructure> (); /** * TODO . * TODO Order fields!!! */ public static EntityStructure load (Class<? extends Entity> entityClass) { EntityStructure entityFields = STRUCTURE.get (entityClass); if (entityFields == null) { entityFields = new EntityStructure (entityClass); Class sc = entityClass.getSuperclass (); if (sc != null && Entity.class.isAssignableFrom (sc)) { @SuppressWarnings ("unchecked") Class superclass = (Class entityFields.fields.addAll (load (superclass).fields); } for (java.lang.reflect.Field f : entityClass.getDeclaredFields ()) if (ReadField.class.isAssignableFrom (f.getType ())) entityFields.fields.add (new FieldStructure (f, null)); STRUCTURE.put (entityClass, entityFields); } return entityFields; } /** * TODO . */ @SuppressWarnings ("unchecked") public static void load (Class<? extends Module>... aModules) { for (Class<? extends Module> m : aModules) for (Class e : m.getDeclaredClasses ()) if (Entity.class.isAssignableFrom (e)) load ((Class<? extends Entity>)e); } /** * TODO . * TODO Order fields!!! */ @SafeVarargs public static void loadAll (Class<? extends Entity>... entityClasses) { for (Class<? extends Entity> entityClass : entityClasses) load (entityClass); } /** * TODO . * @return . */ public static EntityStructure structure (Entity aEntity) { return STRUCTURE.get (aEntity.getClass()); } /** * TODO . * @return . */ public static FieldStructure structure (ReadField aField) { return structure (aField.mEntity).fields.get (aField.mIndex); } /** * TODO . */ private Model () { throw new IllegalStateException (); } } // E O F ///////////////////////////////////////////////////////////////////////////////////////////
java
15
0.558386
100
32.041667
120
starcoderdata
using System.Linq; using System.Net; using System.Web.Mvc; using AutoMapper.QueryableExtensions; using RecruitmentManagementSystem.App.Infrastructure.ActionResults; using RecruitmentManagementSystem.Core.Interfaces; using RecruitmentManagementSystem.Core.Models.Quiz; using RecruitmentManagementSystem.Data.Interfaces; using RecruitmentManagementSystem.Model; namespace RecruitmentManagementSystem.App.Controllers { [Authorize] public class QuizController : BaseController { private readonly IQuizService _quizService; private readonly IQuizRepository _quizRepository; public QuizController(IQuizRepository quizRepository, IQuizService quizService) { _quizService = quizService; _quizRepository = quizRepository; } [HttpGet] public ActionResult Create() { return View(); } [HttpPost] //[ValidateAntiForgeryToken] public ActionResult Create(QuizModel model) { if (!ModelState.IsValid) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors)); } var quizId = _quizService.CreateQuiz(model); return new EnhancedJsonResult(quizId); } [HttpGet] public ActionResult Edit(int id) { var viewModel = _quizRepository.FindAll().ProjectTo => x.Id == id); if (Request.IsAjaxRequest()) { return new EnhancedJsonResult(viewModel, JsonRequestBehavior.AllowGet); } return View(viewModel); } [HttpPost] public ActionResult Edit(QuizModel model) { var entity = _quizRepository.Find(model.Id); if (entity == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; ModelState.AddModelError("", "Question not found."); return new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors)); } if (!ModelState.IsValid) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors)); } _quizService.Update(model); return Json(null); } } }
c#
19
0.612761
110
30.1625
80
starcoderdata
using Customizer.Utility; namespace Customizer.Modeling { /// /// Stores animation data /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = " [CzCustomSerializeMembers] public class LiveAnim { /// /// The unique name of the mesh originally authored against /// [CzSerialize(0)] public string SourceUniqueName; /// /// The bones modified in this animation /// [CzSerialize(1)] public Bone[] Bones; /// /// Animations per bone /// [CzSerialize(2)] public LiveSubAnim[] BoneSubAnims; } }
c#
10
0.618247
111
29.888889
27
starcoderdata
package com.belonk.lifecycle.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * Created by sun on 2020/3/19. * * @author * @version 1.0 * @since 1.0 */ public class LifeCycleBean3 { /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Static fields/constants/initializer * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Instance fields * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Constructors * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ public LifeCycleBean3() { System.out.println("invoke LifeCycleBean3 constructor ... "); } /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Methods * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * JSR 250规范: * PostConstruct注解用在方法上,依赖注入完成(属性设置值)后、且Bean加入到容器前调用。 */ @PostConstruct public void init() { System.out.println("invoke LifeCycleBean3 init method ..."); } @PreDestroy public void destroy() { System.out.println("invoke LifeCycleBean3 destory method ..."); } }
java
9
0.271231
120
26.720588
68
starcoderdata
package com.example.common.account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by bequs-xhjlee on 2016-09-21. */ @Service public class AccountService { @Autowired private AccountRepository accountRepository; public Account findOne(String id) { return accountRepository.findOne(id); } public List findAll() { return accountRepository.findAll(); } public Account save(Account account) { return accountRepository.save(account); } }
java
8
0.711948
62
20.068966
29
starcoderdata
using Repsaj.Submerged.GatewayApp.Universal.Helpers; using Repsaj.Submerged.GatewayApp.Universal.Models; using Repsaj.Submerged.GatewayApp.Universal.Extensions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Repsaj.Submerged.GatewayApp.Universal.Models { public class MainDisplayModel : NotificationBase { TrulyObservableCollection _modules = new TrulyObservableCollection public TrulyObservableCollection Modules { get { return _modules; } set { SetProperty(ref _modules, value); } } TrulyObservableCollection _sensors = new TrulyObservableCollection public TrulyObservableCollection Sensors { get { return _sensors; } set { SetProperty(ref _sensors, value); } } TrulyObservableCollection _relays = new TrulyObservableCollection public TrulyObservableCollection Relays { get { return _relays; } set { SetProperty(ref _relays, value); } } public void ProcessSensorData(IEnumerable sensorData) { List sensorList = sensorData.ToList(); // process all moisture sensors and remove the entries var moistureSensors = sensorList.Where(s => s.SensorType == SensorTypes.MOISTURE); ProcessLeakage(moistureSensors); sensorList.RemoveAll(s => s.SensorType == SensorTypes.MOISTURE); // process all other types of sensors foreach (var sensor in sensorList) { ProcessSensor(sensor); } RaisePropertyChanged(nameof(Sensors)); } private void ProcessLeakage(IEnumerable sensor) { // all moisture sensors are grouped into one value that aggregates all of the values bool value = sensor.Any(s => (bool?)s.Reading == true); var sensorModel = this.Sensors.SingleOrDefault(s => s.Name == "Leakage"); if (sensorModel == null) { SensorDisplayModel newSensor = new SensorDisplayModel() { Name = "Leakage", DisplayName = "Leak detection", Reading = value, SensorType = SensorTypes.MOISTURE, OrderNumber = Int16.MaxValue }; this.Sensors.Add(newSensor); } else { sensorModel.Reading = value; } } private void ProcessSensor(Sensor sensor) { var displayModel = this.Sensors.SingleOrDefault(s => s.Name == sensor.Name); if (displayModel == null && sensor.Reading != null) { displayModel = new SensorDisplayModel(sensor); this.Sensors.Add(displayModel); } else if (displayModel != null && sensor.Reading == null) { this.Sensors.Remove(displayModel); } else if (displayModel != null && sensor.Reading != null) { displayModel.Reading = sensor.Reading; displayModel.Trend = sensor.Trend; displayModel.OrderNumber = sensor.OrderNumber; } this.Sensors.Sort(x => x.OrderNumber); } public void ProcessRelayData(IEnumerable relayData) { foreach (var relay in relayData) { ProcessRelay(relay); } RaisePropertyChanged(nameof(Relays)); } private void ProcessRelay(Relay relay) { var displayModel = this.Relays.SingleOrDefault(s => s.Name == relay.Name); if (displayModel == null) { displayModel = new RelayDisplayModel(relay); this.Relays.Add(displayModel); } else { displayModel.State = relay.State; } } public void ProcessModuleData(IEnumerable moduleData) { foreach (var module in moduleData) { ProcessModule(module); } RaisePropertyChanged(nameof(Modules)); } private void ProcessModule(Module module) { var model = this.Modules.SingleOrDefault(s => s.Name == module.Name); if (model == null) { ModuleDisplayModel newModule = new ModuleDisplayModel(module); this.Modules.Add(newModule); } else { Debug.WriteLine($"Updated module {module.Name} to status {module.Status}"); model.Status = module.Status; } } } }
c#
18
0.564358
117
32.632258
155
starcoderdata
import React from 'react' import { Provider } from 'react-redux' import { store } from './store' import Proofread from './Proofread' import { LOCALSTORAGE_API_ROOT_KEY, LOCALSTORAGE_API_KEY_KEY } from './Proofread/constants'; import { NotificationContainer } from 'react-notifications'; class App extends React.Component { componentWillMount = () => { // Set the API KEY to the local storage window.localStorage.setItem(LOCALSTORAGE_API_KEY_KEY, this.props.apiKey) window.localStorage.setItem(LOCALSTORAGE_API_ROOT_KEY, this.props.apiRoot) } componentWillReceiveProps = (nextProps) => { if (nextProps.apiKey !== this.props.apiKey) { window.localStorage.setItem(LOCALSTORAGE_API_KEY_KEY, this.props.apiKey) } if (nextProps.apiRoot !== this.props.apiRoot) { window.localStorage.setItem(LOCALSTORAGE_API_ROOT_KEY, this.props.apiRoot) } } render() { if (!this.props.apiKey || !this.props.apiRoot) return null; return ( <Provider store={store} > <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css" /> <Proofread {...this.props} /> <NotificationContainer /> ) } } export default (App);
javascript
17
0.675305
103
28.155556
45
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\View; class BaseController extends Controller { protected $user; public function __construct(){ $this->middleware(function($request,$next){ $this->user = Auth::user(); return $next($request); }); } public function getRole(){ return $this->user->userRole->name; } }
php
16
0.676404
47
16.8
25
starcoderdata
@Test public void shouldEmitSessionIdChangeSpan() { underTest.onChange("123", "456"); List<SpanData> spans = otelTesting.getSpans(); assertEquals(1, spans.size()); SpanData span = spans.get(0); assertEquals("sessionId.change", span.getName()); Attributes attributes = span.getAttributes(); assertEquals(1, attributes.size()); assertEquals("123", attributes.get(SessionIdChangeTracer.PREVIOUS_SESSION_ID_KEY)); // splunk.rumSessionId attribute is set in the RumAttributeAppender class }
java
9
0.667845
91
42.615385
13
inline
using HelpMyStreet.Contracts.AddressService.Request; using HelpMyStreet.Contracts.AddressService.Response; using System.Threading; using System.Threading.Tasks; namespace UserService.Core.Interfaces.Services { public interface IAddressService { Task GetPostcodeCoordinatesAsync(GetPostcodeCoordinatesRequest getPostcodeCoordinatesRequest, CancellationToken cancellationToken); Task IsValidPostcode(string postcode, CancellationToken cancellationToken); } }
c#
8
0.830476
171
36.571429
14
starcoderdata