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
import coord_math import random def directed_sqr(x): return x * abs(x) class AgentDecisionMaker: def __init__(self,env_data): #self.map = dict() self.x=0 self.y=0 def on_sight(self,pointcloud): xweight = random.random()*2-1 yweight = random.random()*2-1 for obj_type,point_offset in pointcloud: xoff = point_offset[0] #- self.x yoff = point_offset[1] #- self.y sqrdist = (xoff*xoff + yoff*yoff) weight = 100.0/(0.0001+sqrdist) #print(point_offset) if obj_type == "OBSTICAL": xweight -= weight*xoff yweight -= weight*yoff if obj_type == "GUARD": xweight -= 1000*weight*xoff yweight -= 1000*weight*yoff #print("hithere") if obj_type == "REWARD": xweight += 10*xoff*weight yweight += 10*yoff*weight return xweight,yweight def on_move(self,delta_pos,delta_reward): self.x += delta_pos[0] self.y += delta_pos[1]
python
13
0.514414
48
27.461538
39
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExpressWalker.Core.Visitors { public interface IDictionaryVisitor : IElementVisitor { ExpressAccessor KeyValueAccessor { get; } } }
c#
8
0.753571
57
20.538462
13
starcoderdata
import { Promise } from 'bluebird'; import { last } from 'ramda'; import { logger } from '../config/conf'; import { findAll } from '../domain/stixObservableRelation'; import { executeWrite, updateAttribute } from '../database/grakn'; const updateRelation = async (stixObservableRelation) => { if (stixObservableRelation.entity_type === 'stix_relation') { return executeWrite((wTx) => { return updateAttribute( stixObservableRelation.id, 'stix_relation', { key: 'entity_type', value: ['stix_observable_relation'], }, wTx ); }); } return Promise.resolve(true); }; export const up = async (next) => { try { logger.info(`[MIGRATION] change_bad_entity_type > Starting changing...`); logger.info(`[MIGRATION] change_bad_entity_type > Changing stix relations in batchs of 200`); let hasMore = true; let currentCursor = null; while (hasMore) { logger.info(`[MIGRATION] change_bad_entity_type > Changing stix relations at cursor ${currentCursor}`); const stixObservableRelations = await findAll({ first: 200, after: currentCursor, orderAsc: true, orderBy: 'created_at', }); await Promise.all( stixObservableRelations.edges.map((stixObservableRelationEdge) => { const stixObservableRelation = stixObservableRelationEdge.node; return updateRelation(stixObservableRelation); }) ); if (last(stixObservableRelations.edges)) { currentCursor = last(stixObservableRelations.edges).cursor; hasMore = stixObservableRelations.pageInfo.hasNextPage; } else { hasMore = false; } } logger.info(`[MIGRATION] change_bad_entity_type > Migration complete`); } catch (err) { logger.info(`[MIGRATION] change_bad_entity_type > Error ${err}`); } next(); }; export const down = async (next) => { next(); };
javascript
17
0.635156
109
31.081967
61
starcoderdata
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'next/link'; import styled from 'styled-components'; import is from 'styled-is'; const Trx = styled.a` display: flex; padding: 4px 2px; line-height: 6px; border-radius: 4px; font-size: 9px; border: 1px solid #959595; color: #959595; align-items: center; justify-content: center; ${is('href')` transition: border-color 0.3s ease 0s, color 0.3s ease 0s; &:hover, &:focus { border-color: #2f2f2f; color: #2f2f2f; } `}; `; export default function TrxLink({ trxId }) { if (!trxId) { return <Trx as="div">GENESIS } return ( <Link href={`${process.env.EXPLORER_URL}/trx/${trxId}`} passHref> <Trx target="_blank" rel="noopener nofollow"> TRX ); } TrxLink.propTypes = { trxId: PropTypes.string.isRequired, };
javascript
10
0.638144
69
20.086957
46
starcoderdata
package plandy.javatradeclient.controller; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.chart.LineChart; import javafx.scene.chart.XYChart; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import plandy.javatradeclient.*; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.time.Instant; import java.util.*; public class MainWindowController implements Initializable{ private MarketDataService marketDataService; @FXML private ListView tickerListview; @FXML private PriceChart priceChart; @Override public void initialize(URL location, ResourceBundle resources) { marketDataService = new MarketDataService(); marketDataService.start(); //dataService.requestData( new PriceHistoryDataRequest("aaaa"), new PriceHistoryResultCallback(this) ); marketDataService.requestData( new ListTickersDataRequest(), new ListTickersResultCallback(this) ); tickerListview.setCellFactory( listcell -> new ListCell { @Override protected void updateItem(Stock p_item, boolean p_isEmpty ) { super.updateItem( p_item, p_isEmpty ); if (p_isEmpty || p_item == null || p_item.getTicker() == null) { setText(null); } else { setText( p_item.getTicker() ); } } } ); tickerListview.getSelectionModel().selectedItemProperty().addListener( new StockSelectionListener() ); } private class StockSelectionListener implements ChangeListener { @Override public void changed(ObservableValue<? extends Stock> observable, Stock oldValue, Stock newValue) { if ( newValue != null ) { selectStock( newValue.getTicker() ); } } } private void selectStock( String p_ticker ) { PriceHistoryDataRequest priceHistoryDataRequest = new PriceHistoryDataRequest( p_ticker ); marketDataService.requestData( priceHistoryDataRequest, new PriceHistoryResultCallback(this) ); } public void populateListTickers( ObservableList p_istStocks) { tickerListview.getItems().addAll(p_istStocks); } public void populatePriceHistoryChart( XYChart.Series<Date, Number> p_priceSeries ) { priceChart.getData().clear(); priceChart.getData().add( p_priceSeries ); } private static class ListTickersResultCallback implements IResultCallback { private final MainWindowController controller; public ListTickersResultCallback( MainWindowController p_controller ) { controller = p_controller; } @Override public void executeCallback( String p_listStocks ) { ObservableList priceHistory = FXCollections.observableArrayList(); StringReader stringReader = new StringReader(p_listStocks); BufferedReader buff = new BufferedReader( stringReader ); String line; try { line = buff.readLine(); String[] columnPositions = line.split(","); int tickerIndex = -1; int fullnameIndex = -1; for ( int i = 0; i < columnPositions.length; i++ ) { switch( columnPositions[i] ) { case "ticker": tickerIndex = i; case "fullname": fullnameIndex = i; } } while ( (line = buff.readLine()) != null ) { System.out.println(line); String[] values = line.split(","); Stock dataObject = new Stock( values[tickerIndex], values[fullnameIndex] ); priceHistory.add( dataObject ); } } catch (IOException e) { e.printStackTrace(); } Platform.runLater( () -> { controller.populateListTickers( priceHistory ); }); } } private static class PriceHistoryResultCallback implements IResultCallback { private final MainWindowController controller; public PriceHistoryResultCallback( MainWindowController p_controller ) { controller = p_controller; } @Override public void executeCallback( String p_priceHistory ) { XYChart.Series<Date, Number> priceSeries = new XYChart.Series<>(); List< HashMap<String, Object>> priceHistory = new ArrayList<HashMap<String, Object>>(); StringReader stringReader = new StringReader(p_priceHistory); BufferedReader buff = new BufferedReader( stringReader ); String line; try { line = buff.readLine(); String[] columnPositions = line.split(","); int dateIndex = -1; int openIndex = -1; int highIndex = -1; int lowIndex = -1; int closeIndex = -1; int volumeIndex = -1; for ( int i = 0; i < columnPositions.length; i++ ) { switch( columnPositions[i] ) { case "timestamp": dateIndex = i; case "open": openIndex = i; case "high": highIndex = i; case "low": lowIndex = i; case "close": closeIndex = i; case "volume": volumeIndex = i; } } Instant startInstant = Calendar.getInstance().toInstant(); while ( (line = buff.readLine()) != null ) { System.out.println(line); String[] values = line.split(","); HashMap<String, Object> dataObject = new HashMap<String, Object>(); dataObject.put( "timestamp", values[dateIndex] ); dataObject.put( "open", new Double(values[openIndex]) ); dataObject.put( "high", new Double(values[highIndex]) ); dataObject.put( "low", new Double(values[lowIndex]) ); dataObject.put( "close", new Double(values[closeIndex]) ); dataObject.put( "volume", Long.parseLong(values[volumeIndex]) ); priceHistory.add( dataObject ); XYChart.Data<Date, Number> priceData = new XYChart.Data<Date, Number>( DateUtility.parseStringToDate(values[dateIndex]), new Double(values[closeIndex]) ); priceSeries.getData().add(0, priceData ); } System.out.println( "Starting parse: " + startInstant.toString() ); System.out.println( "Finish parse: " + Calendar.getInstance().toInstant().toString() ); } catch (IOException e) { throw new RuntimeException( e ); } Platform.runLater( () -> { controller.populatePriceHistoryChart( priceSeries ); }); } } // public void injectMarketDataService( MarketDataService p_marketDataService ) { // marketDataService = p_marketDataService; // marketDataService.requestData( new ListTickersDataRequest(), new ListTickersResultCallback(this) ); // } }
java
20
0.58549
174
34.442396
217
starcoderdata
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sertifikat extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->model("Main_model"); } public function no($id){ $peserta = $this->Main_model->get_one("peserta_toefl", ["md5(id)" => $id]); $peserta['link'] = $this->Main_model->get_one("config", ['field' => "web admin"]); if($peserta){ $tes = $this->Main_model->get_one("tes", ["id_tes" => $peserta['id_tes']]); $peserta['nama'] = $peserta['nama']; $peserta['title'] = "Sertifikat ".$peserta['nama']; $peserta['t4_lahir'] = ucwords(strtolower($peserta['t4_lahir'])); $peserta['tahun'] = date('Y', strtotime($tes['tgl_tes'])); $peserta['bulan'] = date('m', strtotime($tes['tgl_tes'])); $peserta['istima'] = poin("Listening", $peserta['nilai_listening']); $peserta['tarakib'] = poin("Structure", $peserta['nilai_structure']); $peserta['qiroah'] = poin("Reading", $peserta['nilai_reading']); $peserta['tgl_tes'] = $tes['tgl_tes']; $peserta['tgl_berakhir'] = date('Y-m-d', strtotime('+1 year', strtotime($tes['tgl_tes']))); $peserta['link_foto'] = config(); $skor = ((poin("Listening", $peserta['nilai_listening']) + poin("Structure", $peserta['nilai_structure']) + poin("Reading", $peserta['nilai_reading'])) * 10) / 3; $peserta['skor'] = $skor; $peserta['no_doc'] = "PT-TW/{$peserta['bulan']}/{$peserta['tahun']}/{$peserta['no_doc']}"; } // $this->load->view("pages/layout/header-sertifikat", $peserta); // $this->load->view("pages/soal/".$page, $data); $peserta['background'] = $this->Main_model->get_one("config", ["field" => 'background']); $this->load->view("pages/sertifikat", $peserta); // $this->load->view("pages/layout/footer"); } public function download($id){ $peserta = $this->Main_model->get_one("peserta_toefl", ["md5(id)" => $id]); $tes = $this->Main_model->get_one("tes", ["id_tes" => $peserta['id_tes']]); $peserta['nama'] = $peserta['nama']; $peserta['t4_lahir'] = ucwords(strtolower($peserta['t4_lahir'])); $peserta['tahun'] = date('Y', strtotime($tes['tgl_tes'])); $peserta['bulan'] = date('m', strtotime($tes['tgl_tes'])); $peserta['listening'] = poin("Listening", $peserta['nilai_listening']); $peserta['structure'] = poin("Structure", $peserta['nilai_structure']); $peserta['reading'] = poin("Reading", $peserta['nilai_reading']); $peserta['tgl_tes'] = $tes['tgl_tes']; $skor = ((poin("Listening", $peserta['nilai_listening']) + poin("Structure", $peserta['nilai_structure']) + poin("Reading", $peserta['nilai_reading'])) * 10) / 3; $peserta['skor'] = $skor; $skor = round($skor); $peserta['no_doc'] = "PT-TW/{$peserta['bulan']}/{$peserta['tahun']}/{$peserta['no_doc']}"; $peserta['config'] = $this->Main_model->config(); $peserta['id_tes'] = $peserta['id_tes']; $defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults(); $fontData = $defaultFontConfig['fontdata']; $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [210, 297], 'orientation' => 'L', // , 'margin_top' => '43', 'margin_left' => '25', 'margin_right' => '25', 'margin_bottom' => '35', 'fontdata' => $fontData + [ 'rockb' => [ 'R' => 'ROCKB.TTF', ],'rock' => [ 'R' => 'ROCK.TTF', ], 'arial' => [ 'R' => 'arial.ttf', 'useOTL' => 0xFF, 'useKashida' => 75, ], 'bodoni' => [ 'R' => 'BOD_R.TTF', ], 'calibri' => [ 'R' => 'CALIBRI.TTF', ], 'cambria' => [ 'R' => 'CAMBRIAB.TTF', ], 'montserrat' => [ 'R' => 'Montserrat-Regular.ttf', ] ], ]); $mpdf->SetTitle("{$peserta['nama']}"); $mpdf->WriteHTML($this->load->view('pages/sertifikat-download', $peserta, TRUE)); $mpdf->Output("{$peserta['nama']}.pdf", "D"); } } /* End of file Sertifikat.php */
php
20
0.486196
174
42.056604
106
starcoderdata
// Copyright 2019 go-fuzz project authors. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. // +build gofuzz package gofuzzdep import ( . "github.com/dvyukov/go-fuzz/go-fuzz-defs" ) // Bool is just a bool. // It is used by code autogenerated by go-fuzz-build // to avoid compilation errors when a user's code shadows the built-in bool. type Bool = bool // CoverTab holds code coverage. // It is initialized to a new array so that instrumentation // executed during process initialization has somewhere to write to. // It is replaced by a newly initialized array when it is // time for actual instrumentation to commence. var CoverTab = new([CoverSize]byte)
go
10
0.758145
97
33.695652
23
starcoderdata
def cnn(self, x=None): ''' :param x: shape is [batch size, input length, site num, features] :return: shape is [batch size, site num, hidden size] ''' x = tf.transpose(x, perm=[0, 2, 1, 3]) # [batch size, site num, input length, features] filter1 = tf.get_variable("filter1", [self.h, self.w, 1, 64], initializer=tf.truncated_normal_initializer(stddev=0.1)) bias1 = tf.get_variable("bias1", [64], initializer=tf.truncated_normal_initializer(stddev=0.1)) layer1 = tf.nn.conv2d(input=x, filter=filter1, strides=[1, 1, 1, 1], padding='SAME') # layer1=tf.layers.conv2d(inputs=x,filters=64,kernel_size=[3,3],padding='same',kernel_initializer=tf.truncated_normal_initializer()) # bn1=tf.layers.batch_normalization(layer1,training=self.placeholders['is_training']) x = tf.add(layer1, bias1) relu1 = tf.nn.relu(layer1) filter2 = tf.get_variable("filter2", [self.h, self.w, 64, 64], initializer=tf.truncated_normal_initializer(stddev=0.1)) bias2 = tf.get_variable("bias2", [64], initializer=tf.truncated_normal_initializer(stddev=0.1)) layer2 = tf.nn.conv2d(input=relu1, filter=filter2, strides=[1, 1, 1, 1], padding='SAME') # bn2=tf.layers.batch_normalization(layer2,training=self.placeholders['is_training']) x = tf.add(layer2, bias2) relu2 = tf.nn.relu(x) filter3 = tf.get_variable("filter3", [self.h, self.w, 64, 64], initializer=tf.truncated_normal_initializer(stddev=0.1)) bias3 = tf.get_variable("bias3", [64], initializer=tf.truncated_normal_initializer(stddev=0.1)) layer3 = tf.nn.conv2d(input=relu2, filter=filter3, strides=[1, 1, 1, 1], padding='SAME') # bn3=tf.layers.batch_normalization(layer3,training=self.placeholders['is_training']) x = tf.add(layer3, bias3) relu3 = tf.nn.relu(x) cnn_x = tf.reduce_max(relu3, axis=2) return cnn_x
python
11
0.61284
140
57.771429
35
inline
package net.alaarc.ast.nodes.stmts; import net.alaarc.ast.IAstNodeVisitor; import net.alaarc.ast.nodes.AstStmt; import java.io.PrintWriter; /** * @author dnpetrov */ public class AstSleepRandStmt extends AstStmt { public AstSleepRandStmt(String sourceFileName, int lineNumber) { super(sourceFileName, lineNumber); } @Override public void accept(IAstNodeVisitor visitor) { visitor.visitSleepRandStmt(this); } }
java
8
0.726269
68
20.571429
21
starcoderdata
package mediaobject import "github.com/dpb587/go-schemaorg" var ( // Date when this media object was uploaded to this site. UploadDate = schemaorg.NewProperty("uploadDate") // Player type required&#x2014;for example, Flash or Silverlight. PlayerType = schemaorg.NewProperty("playerType") // The height of the item. Height = schemaorg.NewProperty("height") // The bitrate of the media object. Bitrate = schemaorg.NewProperty("bitrate") // Indicates if use of the media require a subscription (either paid or free). // Allowed values are or (note that an // earlier version had 'yes', 'no'). RequiresSubscription = schemaorg.NewProperty("requiresSubscription") // The regions where the media is allowed. If not specified, then it's assumed // to be allowed everywhere. Specify the countries in <a // href="http://en.wikipedia.org/wiki/ISO_3166">ISO 3166 format RegionsAllowed = schemaorg.NewProperty("regionsAllowed") // File size in (mega/kilo) bytes. ContentSize = schemaorg.NewProperty("contentSize") // A URL pointing to a player for a specific video. In general, this is the // information in the element of an tag and // should not be the same as the content of the tag. EmbedUrl = schemaorg.NewProperty("embedUrl") // The width of the item. Width = schemaorg.NewProperty("width") // Actual bytes of the media object, for example the image file or video file. ContentUrl = schemaorg.NewProperty("contentUrl") // A NewsArticle associated with the Media Object. AssociatedArticle = schemaorg.NewProperty("associatedArticle") // The production company or studio responsible for the item e.g. series, video // game, episode etc. ProductionCompany = schemaorg.NewProperty("productionCompany") // The duration of the item (movie, audio recording, event, etc.) in <a // href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601 date format Duration = schemaorg.NewProperty("duration") // The CreativeWork encoded by this media object. EncodesCreativeWork = schemaorg.NewProperty("encodesCreativeWork") // mp3, mpeg4, etc. EncodingFormat = schemaorg.NewProperty("encodingFormat") )
go
7
0.746039
80
37.508475
59
starcoderdata
static ov::PartialShape resolve_shape(const ov::PartialShape& then_pshape, const ov::PartialShape& else_pshape) { // then_pshape - shape of output from then_body // else_pshape - shape of output from else_body auto then_rank = then_pshape.rank(); auto else_rank = else_pshape.rank(); // if rangs of shapes are not equal or rang of one of them is dynamic function // return shape with dynamic rank if (then_rank.is_dynamic() || else_rank.is_dynamic()) { return ov::PartialShape::dynamic(); } if (then_rank.get_length() != else_rank.get_length()) { // Union of scalar and 1D case if (then_rank.get_length() <= 1 && else_rank.get_length() <= 1) { return ov::PartialShape::dynamic(1); } else { return ov::PartialShape::dynamic(); } } std::vector<ov::Dimension> new_dims; // If rangs are equal each dimesion of then_body output is union with each dimension of // else_body for (auto then_it = then_pshape.cbegin(), else_it = else_pshape.cbegin(); then_it != then_pshape.cend(); then_it++, else_it++) { if ((*then_it).is_dynamic() || (*else_it).is_dynamic()) { new_dims.push_back(ov::Dimension::dynamic()); } else if (*then_it == *else_it) { new_dims.emplace_back(*then_it); } else { auto dim_min = std::min((*then_it).get_min_length(), (*else_it).get_min_length()); auto dim_max = std::max((*then_it).get_min_length(), (*else_it).get_min_length()); new_dims.emplace_back(dim_min, dim_max); } } return ov::PartialShape(new_dims); }
c++
18
0.588413
113
42.631579
38
inline
using System; using System.Net; namespace Dfe.Spi.GraphQlApi.Infrastructure.TranslatorApi { public class TranslatorApiException : Exception { public TranslatorApiException(string resource, HttpStatusCode statusCode, string details) : base($"Error calling {resource} on translator. Status {(int)statusCode} - {details}") { StatusCode = statusCode; Details = details; } public HttpStatusCode StatusCode { get; } public string Details { get; } } }
c#
12
0.653558
99
28.722222
18
starcoderdata
const constants = require('./helpers/constants'); const { ensureFolderExistsSync } = require('./helpers/utils'); // Set up folder structure ensureFolderExistsSync(constants.folders.base); ensureFolderExistsSync(constants.folders.database); ensureFolderExistsSync(constants.folders.audio);
javascript
6
0.806897
62
40.428571
7
starcoderdata
require('dotenv').config(); const fs = require('fs'); const dir = './logs'; if (!fs.existsSync(dir)){ console.log('Logs folder created'); fs.mkdirSync(dir); } console.log(`${process.env.NODE_ENV.includes('production') ? 'Running Production Env' : 'Running Development Env'}`); const DiscordBot = require('./idle-rpg/v2/DiscordBot'); const { errorLog } = require('./idle-rpg/utils/logger'); process.on('unhandledRejection', (err) => { console.log(err); errorLog.error({ err }); });
javascript
8
0.674286
117
28.166667
18
starcoderdata
#include<bits/stdc++.h> #define fi first #define se second #define pb push_back #define SZ(x) ((int)x.size()) #define L(i,u) for (register int i=head[u]; i; i=nxt[i]) #define rep(i,a,b) for (register int i=(a); i<=(b); i++) #define per(i,a,b) for (register int i=(a); i>=(b); i--) using namespace std; typedef long long ll; typedef unsigned int ui; typedef pair<int,int> Pii; typedef vector<int> Vi; inline void read(int &x) { x=0; char c=getchar(); int f=1; while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();} while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f; } inline ui R() { static ui seed=416; return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13; } const int N = 2020, M = 403000, inf = 0x3f3f3f3f; int n,m,head[N],nxt[M],to[M],edgenum,a[M],b[M],d[N],mx[N],res[M];Vi e[N]; void add(int u, int v){ to[++edgenum]=v;nxt[edgenum]=head[u];head[u]=edgenum; } Vi g[N]; int tot; inline void dfs(int u, int *d){ rep(i,0,SZ(g[u])-1)if(d[g[u][i]]==inf)d[g[u][i]]=d[u],dfs(g[u][i],d); // L(i,u) // for(int i=head[u];i;i=nxt[i]) // {tot++;if(d[to[i]]==inf)d[to[i]]=d[u],dfs(to[i],d);} } int main() {//freopen("1.in","r",stdin); read(n);read(m);rep(i,1,m)read(a[i]),read(b[i]),add(a[i],b[i]),e[b[i]].pb(i); rep(i,1,m)g[a[i]].pb(b[i]); rep(u,1,n){ // printf("u = %d %d\n",u,tot); // int f=1,r=1; memset(d,inf,4*(n+2));memset(mx,inf,4*(n+2)); // L(i,u)q[r++]=to[i]; d[u]=mx[u]=0; /*while(f!=r){ int u=q[f++]; L(i,u)if(d[to[i]]>d[u]||mx[to[i]]<mx[u]) mx[to[i]]=mx[u],d[to[i]]=d[u],q[r++]=to[i]; }*/ static int s[N];int len=0;L(i,u)s[++len]=to[i]; rep(i,1,len)if(d[s[i]]==inf)d[s[i]]=s[i],dfs(s[i],d); per(i,len,1)if(mx[s[i]]==inf)mx[s[i]]=s[i],dfs(s[i],mx); L(i,u)res[i]^=d[to[i]]!=to[i]||mx[to[i]]!=to[i]; per(i,SZ(e[u])-1,0)res[e[u][i]]^=d[a[e[u][i]]]<inf; } rep(i,1,m)printf("%s\n",res[i]?"diff":"same"); return 0; }
c++
14
0.54472
78
31
58
codenet
<?php ini_set('zlib.output_compression', 'On'); if (!defined('KEY')) { require_once "../../app/configuration.php"; } require_once ROOT_DIR . '/libraries/minify/src/Minify.php'; require_once ROOT_DIR . '/libraries/minify/src/CSS.php'; require_once ROOT_DIR . '/libraries/minify/src/JS.php'; require_once ROOT_DIR . '/libraries/minify/src/Exception.php'; require_once ROOT_DIR . '/libraries/minify/src/Exceptions/BasicException.php'; require_once ROOT_DIR . '/libraries/minify/src/Exceptions/FileImportException.php'; require_once ROOT_DIR . '/libraries/minify/src/Exceptions/IOException.php'; require_once ROOT_DIR . '/libraries/path-converter/src/ConverterInterface.php'; require_once ROOT_DIR . '/libraries/path-converter/src/Converter.php'; use MatthiasMullie\Minify; $FILE_TYPE = "text/css"; $CACHE_LENGTH = "31356000"; $CREATE_ARCHIVE = "true"; if (is_dir(ROOT_DIR."/".THEME_PATH."/css/archives/")) { $ARCHIVE_FOLDER = ROOT_DIR."/".THEME_PATH."/css/archives"; } else { $ARCHIVE_FOLDER = ROOT_DIR.'/sites/'.KEY.'/cache/cache/'.THEME.'_css_archives'; } $row = 0; $cssFiles = array(); if (ACCESSIBILITY_MODE) { if (file_exists(ROOT_DIR."/".THEME_PATH."/css/files-accessibility-mode.json")) { $cssFiles = file_get_contents(ROOT_DIR."/".THEME_PATH."/css/files-accessibility-mode.json"); $cssFiles = json_decode($cssFiles,true); $sDocRoot = ROOT_DIR."/".THEME_PATH.'/css'; } else { $cssFiles = array('master-accessibility.css'); $sDocRoot = ROOT_DIR."/asset-proxy/css"; } $cacheappend=".a"; } else { $cacheappend=""; if (file_exists(ROOT_DIR."/".THEME_PATH."/css/files.json")) { $cssFiles = file_get_contents(ROOT_DIR."/".THEME_PATH."/css/files.json"); $cssFiles = json_decode($cssFiles,true); } else { if (($handle = fopen(ROOT_DIR."/".THEME_PATH."/css/files.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); if ($row!=0) { for ($c=0; $c < $num; $c++) { $cssFiles[$c] = $data[$c]; } } $row++; } fclose($handle); } } $sDocRoot = ROOT_DIR."/".THEME_PATH.'/css'; } // files to merge $aFiles = $cssFiles; /****************** end of config ********************/ /* if etag parameter is present then the script is being called directly, otherwise we're including it in another script with require or include. If calling directly we return code othewise we return the etag representing the latest files */ if (isset($_GET['version'])) { $iETag = (int)$_GET['version']; $sLastModified = gmdate('D, d M Y H:i:s', $iETag).' GMT'; // see if the user has an updated copy in browser cache if ( (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $sLastModified) || (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $iETag) ) { header("{$_SERVER['SERVER_PROTOCOL']} 304 Not Modified"); exit; } // create a directory for storing current and archive versions if ($CREATE_ARCHIVE && !is_dir($ARCHIVE_FOLDER)) { mkdir($ARCHIVE_FOLDER); } // get code from archive folder if it exists, otherwise grab latest files, merge and save in archive folder if ($CREATE_ARCHIVE && file_exists($ARCHIVE_FOLDER."/$iETag$cacheappend.cache")) { $sCode = file_get_contents($ARCHIVE_FOLDER."/$iETag$cacheappend.cache"); } else { // get and merge code $sCode = ''; $aLastModifieds = array(); foreach ($aFiles as $sFile) { $aLastModifieds[] = filemtime("$sDocRoot/$sFile"); $sCode .= " ".file_get_contents("$sDocRoot/$sFile"); } // sort dates, newest first rsort($aLastModifieds); $minifier = new Minify\CSS(); $minifier->add($sCode); $sCode = $minifier->minify(); if ($CREATE_ARCHIVE) { if ($iETag == $aLastModifieds[0]) { // check for valid etag, we don't want invalid requests to fill up archive folder $oFile = fopen($ARCHIVE_FOLDER."/$iETag$cacheappend.cache", 'w'); if (flock($oFile, LOCK_EX)) { fwrite($oFile, $sCode); flock($oFile, LOCK_UN); } fclose($oFile); } else { // archive file no longer exists or invalid etag specified header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found"); exit; } } } // send HTTP headers to ensure aggressive caching header('Expires: '.gmdate('D, d M Y H:i:s', time() + $CACHE_LENGTH).' GMT'); // 1 year from now header('Content-Type: '.$FILE_TYPE); # header('Content-Length: '.strlen($sCode)); header("Last-Modified: $sLastModified"); header("ETag: $iETag"); header('Cache-Control: max-age='.$CACHE_LENGTH); // output merged code echo $sCode; } else { // get file last modified dates $aLastModifieds = array(); foreach ($aFiles as $sFile) { $aLastModifieds[] = filemtime("$sDocRoot/$sFile"); } // sort dates, newest first rsort($aLastModifieds); // output latest timestamp echo $aLastModifieds[0]; } ?>
php
19
0.564232
129
33.314815
162
starcoderdata
package app import ( "github.com/wailsapp/wails" "hamster-client/module/p2p" "time" ) type P2p struct { log *wails.CustomLogger p2pServer p2p.Service } func NewP2pApp(service p2p.Service) P2p { return P2p{ p2pServer: service, } } func (s *P2p) WailsInit(runtime *wails.Runtime) error { s.log = runtime.Log.New("P2P") go func() { for { runtime.Events.Emit("Links", s.p2pServer.GetLinks()) time.Sleep(5 * time.Second) } }() return nil } // IsP2PSetting determine whether p2p information is configured func (s *P2p) IsP2PSetting() bool { config, err := s.p2pServer.GetSetting() if err != nil { return false } return config.PrivateKey != "" } // Link p2p link func (s *P2p) Link(port int, peerId string) (bool, error) { //make a p2p link err := s.p2pServer.Link(port, peerId) if err != nil { return false, err } return true, nil } // CloseLink close link func (s *P2p) CloseLink(target string) (int, error) { //disconnect p2p return s.p2pServer.Close(target) } // GetLinkStatus query p2p link status func (s *P2p) GetLinkStatus() *[]p2p.LinkInfo { return s.p2pServer.GetLinks() } // WailsShutdown close link func (s *P2p) WailsShutdown() { _ = s.p2pServer.Destroy() }
go
15
0.679123
63
17.938462
65
starcoderdata
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.udf.esri; import com.esri.core.geometry.ogc.OGCGeometry; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Description(name = "ST_GeomFromGeoJSON", value = "_FUNC_(json) - construct an ST_Geometry from GeoJSON", extended = "Example:\n" + " SELECT _FUNC_('{\"type\":\"Point\", \"coordinates\":[1.2, 2.4]}') FROM src LIMIT 1; -- constructs ST_Point\n" + " SELECT _FUNC_('{\"type\":\"LineString\", \"coordinates\":[[1,2], [3,4]]}') FROM src LIMIT 1; -- constructs ST_LineString\n") public class ST_GeomFromGeoJson extends GenericUDF { static final Logger LOG = LoggerFactory.getLogger(ST_GeomFromGeoJson.class.getName()); ObjectInspector jsonOI; @Override public Object evaluate(DeferredObject[] arguments) throws HiveException { DeferredObject jsonDeferredObject = arguments[0]; String json = null; if (jsonOI.getCategory() == Category.STRUCT) { //StructObjectInspector structOI = (StructObjectInspector)jsonOI; // TODO support structs } else { PrimitiveObjectInspector primOI = (PrimitiveObjectInspector) jsonOI; json = (String) primOI.getPrimitiveJavaObject(jsonDeferredObject.get()); } try { OGCGeometry ogcGeom = OGCGeometry.fromGeoJson(json); return GeometryUtils.geometryToEsriShapeBytesWritable(ogcGeom); } catch (Exception e) { LogUtils.Log_InvalidText(LOG, json); } return null; } @Override public String getDisplayString(String[] args) { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()); String delim = "("; for (String arg : args) { sb.append(delim).append(arg); delim = ", "; } sb.append(")"); return sb.toString(); } @Override public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("ST_GeomFromJson takes only one argument"); } ObjectInspector argJsonOI = arguments[0]; if (argJsonOI.getCategory() == Category.PRIMITIVE) { PrimitiveObjectInspector poi = (PrimitiveObjectInspector) argJsonOI; if (poi.getPrimitiveCategory() != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "ST_GeomFromJson argument category must be either a string primitive or struct"); } } else if (argJsonOI.getCategory() != Category.STRUCT) { } else { throw new UDFArgumentTypeException(0, "ST_GeomFromJson argument category must be either a string primitive or struct"); } jsonOI = argJsonOI; return GeometryUtils.geometryTransportObjectInspector; } }
java
14
0.725411
138
36.491071
112
starcoderdata
private void matchTypeUses(Set<String> allIrTypes, JvmMetadata bm, JType jt) { List<TypeUse> typeUses = jt.typeUses; if (typeUses.isEmpty() || jt.matchElement == null) return; Set<String> irAnnotations = jt.matchElement.mp.getAnnotations(); Set<String> irTypeRefs = new HashSet<>(); jt.matchElement.addReferencedTypesTo(irTypeRefs); for (TypeUse typeUse : typeUses) { if (debug) System.out.println("Examining type use: " + typeUse); Collection<String> irTypeIds = typeUse.getIds(); for (String irTypeId : irTypeIds) { // Match type uses against local annotation uses or the global IR types. if (irAnnotations.contains(irTypeId) || irTypeRefs.contains(irTypeId)) matchTypeUse(typeUse, irTypeId); } if (typeUse.referenceId == null) { if (debug) System.out.println("Type use still unresolved, trying slow global matching: " + typeUse + " with type ids = " + irTypeIds); for (String irTypeId : irTypeIds) { if (allIrTypes.contains(irTypeId) || BOXED_REPRESENTATIONS.contains(irTypeId)) matchTypeUse(typeUse, irTypeId); } } if (typeUse.referenceId != null) registerSymbol(bm, typeUse.getUse()); else if (debug) System.out.println("Type use could not be resolved: " + typeUse); } }
java
15
0.567481
143
49.225806
31
inline
import React from 'react'; import moment from 'moment'; import PropTypes from 'prop-types'; import { navigate } from 'react-big-calendar/lib/utils/constants'; import { useDrag, useDrop } from 'react-dnd'; import CalendarEventWrapper from 'components/tasks/calendar/CalendarEventWrapper'; import { useTaskApi } from 'hooks/UseTaskApi'; import 'components/tasks/calendar/WeekListView.css'; function WeekListView(props) { const taskApi = useTaskApi(); const range = WeekListView.range(props.date); return ( <table className="weekList"> {range.map(date => ( <th key={date.getTime()}>{props.localizer.format(date, 'agendaDateFormat')} ))} {range.map(date => (<WeekListColumn key={date.getTime()} {...props} date={date} taskApi={taskApi} />))} ); } WeekListView.propTypes = { accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, date: PropTypes.instanceOf(Date), events: PropTypes.array, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, selected: PropTypes.object }; WeekListView.range = date => { const start = moment(date).startOf('week'); return [...Array(7)].map((_, i) => moment(start).add(i, 'day').toDate()); }; WeekListView.navigate = (date, action) => { switch (action) { case navigate.PREVIOUS: return moment(date).add(-1, 'week').toDate(); case navigate.NEXT: return moment(date).add(1, 'week').toDate(); default: return date; } }; WeekListView.title = (date, { localizer }) => { const start = moment(date).startOf('week').toDate(); const end = moment(date).endOf('week').toDate(); return localizer.format({ start, end }, 'agendaHeaderFormat'); }; function WeekListColumn(props) { const { accessors, date, events, taskApi } = props; const [collectedDropProps, drop] = useDrop({ accept: 'calendar-event', drop: item => { const dropDate = moment(date); const type = item.data.type; const task = item.data.task; if (type === 'startDate' || type === 'dueDate') { const newDate = moment(task[type]); newDate.set('day', dropDate.get('day')); newDate.set('month', dropDate.get('month')); newDate.set('year', dropDate.get('year')); taskApi.updateTask({ ...task, [type]: newDate.toISOString() }); } }, collect: monitor => ({ hovered: monitor.isOver() }) }); return ( <td ref={drop} className={collectedDropProps.hovered ? 'hovered' : null}> {events .filter(event => moment(accessors.start(event)).isSame(moment(date), 'day')) .map(event => (<WeekListCell key={event.id} {...props} event={event} />))} ); } WeekListColumn.propTypes = { accessors: PropTypes.object.isRequired, date: PropTypes.instanceOf(Date), events: PropTypes.array, taskApi: PropTypes.object }; function WeekListCell({ components, event, onDoubleClickEvent, onSelectEvent }) { const { event: Event } = components; // eslint-disable-next-line no-unused-vars const [collectedDragProps, drag] = useDrag({ type: 'calendar-event', item: { data: event } }); return ( <CalendarEventWrapper event={event}> <div className="rbc-event" ref={drag} style={{ cursor: 'pointer' }} onClick={() => onSelectEvent(event)} onDoubleClick={() => onDoubleClickEvent(event)}> <Event event={event} /> ); } WeekListCell.propTypes = { accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, event: PropTypes.object, onDoubleClickEvent: PropTypes.func.isRequired, onSelectEvent: PropTypes.func.isRequired }; export default WeekListView;
javascript
20
0.566963
123
30.092199
141
starcoderdata
import React, { createContext, useState, useEffect } from "react"; // Context export const ThemeContext = createContext({ isBlaze: false, setBlaze: () => {}, setZephyr: () => {}, toggleTheme: () => {} }); // Provider export const ThemeProvider = ({ children }) => { useEffect(() => { if (localStorage.getItem("theme") !== null) { document.body.setAttribute("data-theme", "zephyr"); setisBlaze(false); } else { setisBlaze(true); } }, []); const [isBlaze, setisBlaze] = useState(undefined); function setZephyr() { document.body.setAttribute("data-theme", "zephyr"); localStorage.setItem("theme", "zephyr"); setisBlaze(false); } function setBlaze() { document.body.removeAttribute("data-theme"); localStorage.removeItem("theme"); setisBlaze(true); } function toggleTheme() { if (isBlaze) setZephyr() else setBlaze(); } return ( <ThemeContext.Provider value={{ isBlaze, setBlaze, setZephyr, toggleTheme }} > {children} ) }
javascript
17
0.615672
66
20.897959
49
starcoderdata
//// [awaitExpressionInnerCommentEmit.ts] async function foo() { /*comment1*/ await 1; await /*comment2*/ 2; await 3 /*comment3*/ } //// [awaitExpressionInnerCommentEmit.js] async function foo() { /*comment1*/ await 1; await /*comment2*/ 2; await 3; /*comment3*/ }
javascript
5
0.608696
41
21.307692
13
starcoderdata
<?php namespace App\Http\Controllers\Admin; use illuminate\Http\request; use App\Models\Contents; use Image; use Session; class ContentsController extends Controller { public function __construct(){ $this->middleware('block'); $this->middleware('role'); parent::__construct(); } public function index(){ $contents = Contents::get(); foreach ($contents as $value) { $this->data[$value->name] = $value->value; } return $this->render_view('pages.preferences.settings.contents.index'); } public function addContents(request $request){ foreach ($request->except(['_token']) as $value => $key) { $contents = Contents::where('name', $value)->first(); if($request->file($value)){ $this->validate($request,['home_header' => 'image|mimes:jpeg,png,jpg,gif,svg,tif|max:2048|dimensions:min_width=1200,max_width=1200,min_height=450,max_height=450']); $this->validate($request,['contact_us_header' => 'image|mimes:jpeg,png,jpg,gif,svg,tif|max:2048|dimensions:min_width=1200,max_width=1200,min_height=450,max_height=450']); $this->validate($request,['gallery_header' => 'image|mimes:jpeg,png,jpg,gif,svg,tif|max:2048|dimensions:min_width=1200,max_width=1200,min_height=450,max_height=450']); $this->validate($request,['footer_background' => 'image|mimes:jpeg,png,jpg,gif,svg,tif|max:2048|dimensions:min_width=1200,max_width=1263,min_height=169,max_height=169']); $img = Image::make($key); $key = str_random(5).'.'.explode('/',$img->mime)[1]; $img->save('images/frontend/contents/'.$key); } if(!$contents){ $contents = new Contents; $contents->name = $value; } $contents->value = $key; $contents->save(); } $request->session()->flash('message', 'Data Successfully Submited!'); return redirect()->back(); } }
php
18
0.59002
186
42.489362
47
starcoderdata
import lasagne.layers #from config import Configuration as Cfg #if Cfg.leaky_relu: # from lasagne.nonlinearities import leaky_rectify as nonlinearity #else: # from lasagne.nonlinearities import rectify as nonlinearity nonlinearity = None class DenseLayer(lasagne.layers.DenseLayer): # for convenience isconv, isbatchnorm, isdropout, ismaxpool, isactivation = (False,) * 5 isdense = True def __init__(self, incoming_layer, num_units, W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.), name=None, nonlinearity=nonlinearity, **kwargs): lasagne.layers.DenseLayer.__init__(self, incoming_layer, num_units, name=name, W=W, b=b, nonlinearity=nonlinearity, **kwargs) self.inp_ndim = 2 self.use_dc = True
python
10
0.611857
79
34.76
25
starcoderdata
using System; using System.Runtime.InteropServices; namespace Hessian.Platform { public abstract class EndianBitConverter { #region T -> byte[] public byte[] GetBytes(bool value) { // One byte, no endianness return BitConverter.GetBytes(value); } public byte[] GetBytes(char value) { return GetBytes(value, sizeof(char)); } public byte[] GetBytes(short value) { return GetBytes(value, sizeof(short)); } public byte[] GetBytes(ushort value) { return GetBytes(value, sizeof(ushort)); } public byte[] GetBytes(int value) { return GetBytes(value, sizeof(int)); } public byte[] GetBytes(uint value) { return GetBytes(value, sizeof(uint)); } public byte[] GetBytes(long value) { return GetBytes(value, sizeof(long)); } public byte[] GetBytes(ulong value) { return GetBytes((long)value, sizeof(ulong)); } public byte[] GetBytes(float value) { return GetBytes(SingleToInt32(value), sizeof(int)); } public byte[] GetBytes(double value) { return GetBytes(DoubleToInt64(value), sizeof(long)); } private byte[] GetBytes(long value, int size) { var buffer = new byte[size]; CopyBytes(value, buffer, 0, size); return buffer; } #endregion T -> byte[] #region byte[] -> T public bool ToBoolean(byte[] value, int index) { // one byte, no endianness return BitConverter.ToBoolean(value, index); } public char ToChar(byte[] value, int index) { return (char)FromBytes(value, index, sizeof(char)); } public short ToInt16(byte[] value, int index) { return (short)FromBytes(value, index, sizeof(short)); } public ushort ToUInt16(byte[] value, int index) { return (ushort)FromBytes(value, index, sizeof(ushort)); } public int ToInt32(byte[] value, int index) { return (int)FromBytes(value, index, sizeof(int)); } public uint ToUInt32(byte[] value, int index) { return (uint)FromBytes(value, index, sizeof(uint)); } public long ToInt64(byte[] value, int index) { return FromBytes(value, index, sizeof(long)); } public ulong ToUInt64(byte[] value, int index) { return (ulong)FromBytes(value, index, sizeof(ulong)); } public float ToSingle(byte[] value, int index) { var int32 = (int)FromBytes(value, index, sizeof(int)); return Int32ToSingle(int32); } public double ToDouble(byte[] value, int index) { var int64 = FromBytes(value, index, sizeof(long)); return Int64ToDouble(int64); } #endregion byte[] -> T protected abstract long FromBytes(byte[] bytes, int offset, int count); protected abstract void CopyBytes(long source, byte[] buffer, int index, int count); private static int SingleToInt32(float value) { return new JonSkeetUnion32(value).AsInt; } private static float Int32ToSingle(int value) { return new JonSkeetUnion32(value).AsFloat; } private static long DoubleToInt64(double value) { return new JonSkeetUnion64(value).AsLong; } private static double Int64ToDouble(long value) { return new JonSkeetUnion64(value).AsDouble; } [StructLayout(LayoutKind.Explicit)] private struct JonSkeetUnion32 { [FieldOffset(0)] private readonly int i; [FieldOffset(0)] private readonly float f; public int AsInt { get { return i; } } public float AsFloat { get { return f; } } public JonSkeetUnion32(int value) { f = 0; i = value; } public JonSkeetUnion32(float value) { i = 0; f = value; } } [StructLayout(LayoutKind.Explicit)] private struct JonSkeetUnion64 { [FieldOffset(0)] private readonly long l; [FieldOffset(0)] private readonly double d; public long AsLong { get { return l; } } public double AsDouble { get { return d; } } public JonSkeetUnion64(long value) { d = 0; l = value; } public JonSkeetUnion64(double value) { l = 0; d = value; } } } }
c#
16
0.502112
92
23.570755
212
starcoderdata
# encoding: utf-8 # # main.py from pytest import mark def test_main(client): response = client.get("/") assert response.status_code == 200 assert response.json() == {"Hello SDSS": "This is the FastAPI World", 'release': "WORK"} @mark.parametrize('release', ['WORK', 'DR17']) def test_main_with_release(client, release): response = client.get("/", params={"release": release}) assert response.status_code == 200 assert response.json() == {"Hello SDSS": "This is the FastAPI World", 'release': release}
python
12
0.648699
93
28.888889
18
starcoderdata
private Tenant[] getAllTenants() throws MigrationClientException { // Add the super tenant. Tenant superTenant = new Tenant(); superTenant.setDomain("carbon.super"); superTenant.setId(-1234); superTenant.setActive(true); // Add the rest. Set<Tenant> tenants = Utility.getTenants(); tenants.add(superTenant); return tenants.toArray(new Tenant[0]); }
java
8
0.627635
66
29.571429
14
inline
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Created on Thu Feb 25 10:15:48 2021 Plotting DCBC curves INPUTS: struct: DCBC evaluation result OUTPUT: The figure of within- and between parcels correlation curve Author: ''' import numpy as np import matplotlib.pyplot as plt from eval_DCBC import scan_subdirs def plot_single(within, between, subjects, maxDist=35, binWidth=1, within_color='k', between_color='r'): fig = plt.figure() # Obtain basic info from evaluation result numBins = int(np.floor(maxDist / binWidth)) num_sub = len(subjects) x = np.arange(0, maxDist, binWidth) + binWidth / 2 y_within = within.reshape(num_sub, -1) y_between = between.reshape(num_sub, -1) plt.errorbar(x, y_within.mean(0), yerr=y_within.std(0), ecolor=within_color, color=within_color, elinewidth=0.5, capsize=2, linestyle='dotted', label='within') plt.errorbar(x, y_between.mean(0), yerr=y_between.std(0), ecolor=between_color, color=between_color, elinewidth=0.5, capsize=2, linestyle='dotted', label='between') plt.legend(loc='upper right') plt.show() def plot_wb_curve(T, path, sub_list=None, hems='all', within_color='k', between_color='r'): fig = plt.figure() # Obtain basic info from evaluation result T bin_width = [value for key, value in T.items()][0]['binWidth'] max_dist = [value for key, value in T.items()][0]['maxDist'] k = len([value for key, value in T.items()][0]['corr_within']) x = np.arange(0,max_dist,bin_width) + bin_width/2 # if hems is 'all' and any([x for x in T.keys() if 'L' in x]) and any([x for x in T.keys() if 'R' in x]): # # subjectsDir = [x for x in T.keys()] # pass # elif hems is 'L' or 'R' and any([x for x in T.keys() if hems in x]): # # subjectsDir = [x for x in T.keys() if hems in x] # pass # else: # raise TypeError("Input hemisphere's data has not been found!") if sub_list is not None: subjects_dir = sub_list else: subjects_dir = scan_subdirs(path) y_within, y_between = np.empty([1, k]), np.empty([1, k]) for sub in subjects_dir: data = [value for key, value in T.items() if sub in key] if len(data) == 2 and hems is 'all': within = (np.asarray(data[0]["corr_within"]) + np.asarray(data[1]["corr_within"])) / 2 between = (np.asarray(data[0]["corr_between"]) + np.asarray(data[1]["corr_between"])) / 2 elif len(data) == 1 and data[0]["hemisphere"] is hems: within = data[0]["corr_within"] between = data[0]["corr_between"] else: raise Exception("Incomplete DCBC evaluation. Missing result of %s." % sub) y_within = np.vstack((y_within, within)) y_between = np.vstack((y_between, between)) sub_list = T.keys() y_within = np.delete(y_within, 0, axis=0) y_between = np.delete(y_between, 0, axis=0) plt.errorbar(x, y_within.mean(0), yerr=y_within.std(0), ecolor=within_color, color=within_color, label='within') plt.errorbar(x, y_between.mean(0), yerr=y_between.std(0), ecolor=between_color, color=between_color, label='between') plt.legend(loc='upper right') plt.show() def plot_DCBC(T, color='r'): # todo: to plot DCBC value print('working on this function') # T = dict() # T['s02_L']={"binWidth": 1, # "maxDist": 35, # "hemisphere": 'L', # "num_within": [1,2,3,4,5,6,7,8,9,10], # "num_between": [0,1,2,3,4,5,6,7,8,9], # "corr_within": np.random.rand(35), # "corr_between": np.random.rand(35), # "weight": [0,1,2,3,4,5,6,7,8,9], # "DCBC": 10} # T['s02_R']={"binWidth": 1, # "maxDist": 35, # "hemisphere": 'R', # "num_within": [1,2,3,4,5,6,7,8,9,10], # "num_between": [0,1,2,3,4,5,6,7,8,9], # "corr_within": np.random.rand(35), # "corr_between": np.random.rand(35), # "weight": [0,1,2,3,4,5,6,7,8,9], # "DCBC": 10} # T['s03_L']={"binWidth": 1, # "maxDist": 35, # "hemisphere": 'L', # "num_within": [1,2,3,4,5,6,7,8,9,10], # "num_between": [0,1,2,3,4,5,6,7,8,9], # "corr_within": np.random.rand(35), # "corr_between": np.random.rand(35), # "weight": [0,1,2,3,4,5,6,7,8,9], # "DCBC": 10} # T['s03_R']={"binWidth": 1, # "maxDist": 35, # "hemisphere": 'R', # "num_within": [1,2,3,4,5,6,7,8,9,10], # "num_between": [0,1,2,3,4,5,6,7,8,9], # "corr_within": np.random.rand(35), # "corr_between": np.random.rand(35), # "weight": [0,1,2,3,4,5,6,7,8,9], # "DCBC": 10} # # # if __name__ == '__main__': # plot_wb_curve(T, path='data', sub_list=['s02', 's03'])
python
16
0.545747
121
35.29927
137
starcoderdata
Node* leftRotate(Node* root) { Node* x = root->right; Node* t = x->left; root->right = t; x->left = root; //Update the height x = updateHeight(x); root = updateHeight(root); return x; }
c
7
0.472656
34
18.769231
13
inline
import numpy as np np.set_printoptions(precision=4, suppress=True) from nmpc_position_controller.dynamics import discrete_dynamics def cost(g, z, Ts, N, zref, Q, k, last_g, L): R = np.diag([0.1, 0.1]) zk = z gk = g[0].reshape(-1, 1) J = 0.0 zref = zref.reshape(-1, 1) print(zref.T) last_g = last_g.reshape(-1, 1) for i in range(N+1): zk1 = discrete_dynamics(zk, gk, Ts, k, L) print((zk1-zref).T) J += np.dot(np.dot((zk1-zref).T, Q), zk1-zref)[0,0] # Eq 61 in Ecc # print(J) # if i == 0: # J += np.dot(np.dot((gk-last_g).T, R), gk-last_g)[0,0] # else: # pass # J += np.dot(np.dot((gk-last_g).T, R), gk-last_g) # for ct=1:N # zk1 = DicreteDynamic(zk, gk, Ts,k,L); # J = J + (zk1-zref)'*Q*(zk1-zref); % Eq 61 in Ecc # if ct==1 # J = J + (gk-last_g')*R*(gk-last_g')'; # else # J = J + (gk-g(ct-1,:))*R*(gk-g(ct-1,:))'; # end # zk = zk1; # if ct<N # gk = g(ct+1,:); # end # end def control(z, zref, t, gamma, k, L, last_g, last_gopt): x0, dx0, y0, dy0, phix, dphix, phiy, dphiy = z # Eq. 55 in ECC Ts = 0.2 # Time step N = 4 # Prediction step (in time N*Ts) samptime = 0.6 # Do a new prediction every samptime Q = np.diag([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]) # Eq. 64 in Ecc min_g = -gamma*np.ones((N, 2)) # contraint output Eq 59 max_g = gamma*np.ones((N, 2)) # constraint output Eq 59 gopt = np.zeros((N, 2)) # init optimal output mod = t % samptime if mod == 0: # gopt = MPCred(z,zref,Ts,N,last_gopt,Q,min_g,max_g,k,last_g,L); %NMPC n = 1 else: gopt = last_gopt n = round(mod)/(Ts+1) g = gopt[-1] # current NMPC output, eq 56 in ECC # Lyapunov damping controller kp, kd = k cx = np.cos(phix) sx = np.sin(phix) cy = np.cos(phiy) sy = np.sin(phiy) uy = - L*cy/cx*(kd*dphix + kp*phix) - 2*L*sy/cx + 9.81*sx*sy**2/cx ux = L/cy*(kd*dphiy + kp*phiy) - L*sy*dphix**2 - uy*sx*sy/cy # Final controller dw = np.array([ux + g[0], uy + g[1]]) # Eq 65-66 in ECC
python
15
0.515901
82
27.3
80
starcoderdata
<?php session_start(); $tableName = 'Procedures_Data'; $queryUserId = $_SESSION["userId"]; $scanTableForwards = true; require 'query_dynamodb.php'; foreach ($result['Items'] as $procedure) { echo " . $marshaler->unmarshalValue($procedure['procedureName']) . " . " type=\"button\" class=\"edit_btn\" onclick=\"editProcedure('user', this)\">Bearbeiten . " type=\"button\" class=\"delete_btn\" onclick=\"deleteProcedure(this)\">Löschen . " type=\"button\" class=\"show_btn\" onclick=\"expandRow(this)\">&#9666; $proc = json_decode($marshaler->unmarshalValue($procedure['jsonFile'])); $steps = $proc->steps; $lastStepIndex = count($steps) - 1; $triggerTime = "" . $proc->triggerParameters[0]->TIME; if ($triggerTime != "") $triggerTime = ", " . substr($triggerTime, 0, 2) . ":" . substr($triggerTime, -2) . " Uhr"; $detailsTable = "<table id=\"procedure_detail_table\">\n" . "<tr id=\"heading_row\"><td colspan=\"2\">Auslöser . " colspan=\"2\">" . $proc->triggerParameters[0]->DAYS . $triggerTime . " for ($i = 0; $i < $lastStepIndex; $i++) { $detailsTable .= "<tr id=\"heading_row\"><td colspan=\"2\">Schritt " . ($i+1) . " . " . $steps[$i]->instructionText . " . " . $steps[$i]->helpText . " . " . $steps[$i]->confirmText . " } $detailsTable .= "<tr id=\"heading_row\"><td colspan=\"2\">Letzter Schritt . " . $steps[$lastStepIndex]->finishedText . " . " echo "<tr style=\"display:none;\"><td colspan=\"4\">" . $detailsTable . " } ?>
php
21
0.577591
121
54.911765
34
starcoderdata
function ajaxResponse () { if (this.readyState == 4 && this.status == 200) { document.getElementById("response").innerHTML = this.responseText; } } function jsend (verb) { const content = document.getElementById("request").value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = ajaxResponse; xhttp.open(verb, content, true); xhttp.send(); }
javascript
11
0.717033
68
27
13
starcoderdata
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Magento.RestClient.Abstractions; using Magento.RestClient.Abstractions.Abstractions; using Magento.RestClient.Abstractions.Domain; using Magento.RestClient.Abstractions.Repositories; using Magento.RestClient.Data.Models.Bulk; using Magento.RestClient.Data.Requests; using Serilog; namespace Magento.RestClient.Extensions { public static class BulkExtensions { public async static Task CreateOrUpdate(this IAdminContext context, IEnumerable models) { var productModels = models.ToList(); Log.Information("Upserting {Count} products in bulk", productModels.Count); var sw = Stopwatch.StartNew(); var products = productModels.Select(model => model.GetProduct()).ToArray(); var createProductsResponse = await context.Bulk.CreateOrUpdateProducts(products).ConfigureAwait(false); await context.Bulk.AwaitBulkOperations(createProductsResponse).ConfigureAwait(false); sw.Stop(); Log.Information("Upserted {Count} products in {Elapsed}", productModels.Count, sw.Elapsed); var mediaRequests = productModels.SelectMany(model => model.MediaEntries.Where(entry => entry.Id == null), (model, entry) => new CreateOrUpdateMediaRequest() { Sku = model.Sku, Entry = entry }).ToArray(); var createOrUpdateMediaResponse = await context.Bulk.CreateOrUpdateMedia(mediaRequests).ConfigureAwait(false); await context.Bulk.AwaitBulkOperations(createOrUpdateMediaResponse).ConfigureAwait(false); return createProductsResponse; } } }
c#
23
0.790206
109
37.488372
43
starcoderdata
#include using namespace std; // Find element at given index after a number of rotations // An array consisting of N integers is given. There are several left circular // Rotations of range[L..R] that we perform. After performing these rotations, // we need to find element at a given index. // Reference link: https://www.geeksforgeeks.org/find-element-given-index-number-rotations/ // Function to compute the element at // given index int findElement(int arr[], int ranges[][2], int rotations, int index) { for (int i = rotations - 1; i >= 0; i--) { // Range[left...right] int left = ranges[i][0]; int right = ranges[i][1]; // Rotation will not have any effect if (left <= index && right >= index) { if (index == left) index = right; else index--; } } // Returning new element return arr[index]; } // Driver int main() { int arr[] = {1, 2, 3, 4, 5}; // No. of rotations int rotations = 2; // Ranges according to 0-based indexing int ranges[rotations][2] = {{0, 2}, {0, 3}}; int index = 1; cout << findElement(arr, ranges, rotations, index); return 0; }
c++
11
0.644082
91
26.244444
45
starcoderdata
# Copyright 2022 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """ test_dict_get """ from mindspore import Tensor, jit, context context.set_context(mode=context.GRAPH_MODE) def test_dict_get_1(): """ Feature: dict get. Description: support dict get. Expectation: No exception. """ @jit def dict_net_1(): x = {'a': 1, 'b': 2} res = x.get('a') return Tensor(res) out = dict_net_1() assert out == 1 def test_dict_get_3(): """ Feature: dict get. Description: support dict get set default value. Expectation: No exception. """ @jit def dict_net_3(): dict_x = {'a': 1, 'b': 2} the_key = 'a' the_value = dict_x.get(the_key, 3) return Tensor(the_value) out = dict_net_3() assert out == 1 def test_dict_get_4(): """ Feature: dict get. Description: support dict get set default value. Expectation: No exception. """ @jit def dict_net_4(): dict_x = {'a': 1, 'b': 2} the_key = 'c' the_value = dict_x.get(the_key, 3) return Tensor(the_value) out = dict_net_4() assert out == 3 def test_dict_get_5(): """ Feature: dict get. Description: support dict get set default value. Expectation: No exception. """ @jit def dict_net_5(): dict_x = {"x": Tensor([3]), "y": Tensor([5])} the_key = 'c' the_value = dict_x.get(the_key, Tensor([7])) return Tensor(the_value) out = dict_net_5() assert out == 7 def test_dict_get_6(): """ Feature: dict get. Description: support dict get set default value. Expectation: No exception. """ @jit def dict_net_6(): dict_x = {"1": Tensor(1), "2": (1, 2)} the_key = '2' the_value = dict_x.get(the_key, Tensor([7])) return Tensor(the_value) out = dict_net_6() assert (out.asnumpy() == (1, 2)).all() def test_dict_get_7(): """ Feature: dict get. Description: support dict get set default value. Expectation: No exception. """ @jit def dict_net_7(): dict_x = {"1": Tensor(1), "2": (1, 2)} the_value = dict_x.get("3", (3, 4)) return Tensor(the_value) out = dict_net_7() assert (out.asnumpy() == (3, 4)).all() def test_dict_get_8(): """ Feature: dict get. Description: support dict get set default value. Expectation: No exception. """ @jit def dict_net_8(x, y, z): dict_x = {"1": x, "2": y} default_value = dict_x.get("3", z) return default_value input_x = Tensor(1) input_y = Tensor(2) input_z = Tensor(3) out = dict_net_8(input_x, input_y, input_z) assert out == 3
python
13
0.561085
78
24.815385
130
research_code
# ********************************************************************************* # REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this list # of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # # Neither the name of the copyright holder nor the names of its contributors may be # used to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. # ********************************************************************************* def nested_to_flat(nested_output): """ Convenience function for comparing two results dictionary. Used in many built-in tests (before passing both dicts to check_common_outputs). Arguments: nested_output: dict, API response """ base = { 'run_uuid': nested_output['Scenario']['run_uuid'], 'api_version': nested_output['Scenario']['api_version'], 'status': nested_output['Scenario']['status'], 'year_one_electric_load_series': nested_output['Scenario']['Site']['LoadProfile']['year_one_electric_load_series_kw'], 'lcc': nested_output['Scenario']['Site']['Financial']['lcc_us_dollars'], 'lcc_bau': nested_output['Scenario']['Site']['Financial']['lcc_bau_us_dollars'], 'npv': nested_output['Scenario']['Site']['Financial']['npv_us_dollars'], 'net_capital_costs_plus_om': nested_output['Scenario']['Site']['Financial']['net_capital_costs_plus_om_us_dollars'], 'avoided_outage_costs_us_dollars': nested_output['Scenario']['Site']['Financial']['avoided_outage_costs_us_dollars'], 'microgrid_upgrade_cost_us_dollars': nested_output['Scenario']['Site']['Financial']['microgrid_upgrade_cost_us_dollars'], 'pv_kw': nested_output['Scenario']['Site']['PV']['size_kw'], 'year_one_energy_produced': nested_output['Scenario']['Site']['PV']['year_one_energy_produced_kwh'], 'pv_kw_ac_hourly': nested_output['Scenario']['Site']['PV']['year_one_power_production_series_kw'], 'average_yearly_pv_energy_produced': nested_output['Scenario']['Site']['PV']['average_yearly_energy_produced_kwh'], 'average_annual_energy_exported': nested_output['Scenario']['Site']['PV']['average_yearly_energy_exported_kwh'], 'year_one_pv_to_battery_series': nested_output['Scenario']['Site']['PV']['year_one_to_battery_series_kw'], 'year_one_pv_to_load_series': nested_output['Scenario']['Site']['PV']['year_one_to_load_series_kw'], 'year_one_pv_to_grid_series': nested_output['Scenario']['Site']['PV']['year_one_to_grid_series_kw'], 'existing_pv_om_cost_us_dollars': nested_output['Scenario']['Site']['PV']['existing_pv_om_cost_us_dollars'], 'batt_kw': nested_output['Scenario']['Site']['Storage']['size_kw'], 'batt_kwh': nested_output['Scenario']['Site']['Storage']['size_kwh'], 'year_one_battery_to_load_series': nested_output['Scenario']['Site']['Storage']['year_one_to_load_series_kw'], 'year_one_battery_to_grid_series': nested_output['Scenario']['Site']['Storage']['year_one_to_grid_series_kw'], 'year_one_battery_soc_series': nested_output['Scenario']['Site']['Storage']['year_one_soc_series_pct'], 'year_one_energy_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_energy_cost_us_dollars'], 'year_one_demand_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_demand_cost_us_dollars'], 'year_one_fixed_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_fixed_cost_us_dollars'], 'year_one_min_charge_adder': nested_output['Scenario']['Site']['ElectricTariff']['year_one_min_charge_adder_us_dollars'], 'year_one_energy_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_energy_cost_bau_us_dollars'], 'year_one_demand_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_demand_cost_bau_us_dollars'], 'year_one_fixed_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_fixed_cost_bau_us_dollars'], 'year_one_min_charge_adder_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_min_charge_adder_bau_us_dollars'], 'total_energy_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_energy_cost_us_dollars'], 'total_demand_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_demand_cost_us_dollars'], 'total_fixed_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_fixed_cost_us_dollars'], 'total_min_charge_adder': nested_output['Scenario']['Site']['ElectricTariff']['total_min_charge_adder_us_dollars'], 'total_energy_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['total_energy_cost_bau_us_dollars'], 'total_demand_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['total_demand_cost_bau_us_dollars'], 'total_fixed_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['total_fixed_cost_bau_us_dollars'], 'total_min_charge_adder_bau': nested_output['Scenario']['Site']['ElectricTariff']['total_min_charge_adder_bau_us_dollars'], 'year_one_bill': nested_output['Scenario']['Site']['ElectricTariff']['year_one_bill_us_dollars'], 'year_one_bill_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_bill_bau_us_dollars'], 'year_one_export_benefit': nested_output['Scenario']['Site']['ElectricTariff']['year_one_export_benefit_us_dollars'], 'year_one_grid_to_load_series': nested_output['Scenario']['Site']['ElectricTariff']['year_one_to_load_series_kw'], 'year_one_grid_to_battery_series': nested_output['Scenario']['Site']['ElectricTariff']['year_one_to_battery_series_kw'], 'year_one_energy_cost_series': nested_output['Scenario']['Site']['ElectricTariff']['year_one_energy_cost_series_us_dollars_per_kwh'], 'year_one_demand_cost_series': nested_output['Scenario']['Site']['ElectricTariff']['year_one_demand_cost_series_us_dollars_per_kw'], 'year_one_utility_kwh': nested_output['Scenario']['Site']['ElectricTariff']['year_one_energy_supplied_kwh'], 'year_one_payments_to_third_party_owner': None, 'total_payments_to_third_party_owner': None, 'year_one_coincident_peak_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_coincident_peak_cost_us_dollars'], 'year_one_coincident_peak_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_coincident_peak_cost_bau_us_dollars'], 'total_coincident_peak_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_coincident_peak_cost_us_dollars'], 'total_coincident_peak_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['total_coincident_peak_cost_bau_us_dollars'] } if nested_output['Scenario']['Site'].get('Wind') is not None: base.update({ 'wind_kw':nested_output['Scenario']['Site']['Wind']['size_kw'], 'average_yearly_wind_energy_produced':nested_output['Scenario']['Site']['Wind']['average_yearly_energy_produced_kwh'], 'average_annual_energy_exported_wind': nested_output['Scenario']['Site']['Wind']['average_yearly_energy_exported_kwh'], 'year_one_wind_to_battery_series': nested_output['Scenario']['Site']['Wind']['year_one_to_battery_series_kw'], 'year_one_wind_to_load_series': nested_output['Scenario']['Site']['Wind']['year_one_to_load_series_kw'], 'year_one_wind_to_grid_series': nested_output['Scenario']['Site']['Wind']['year_one_to_grid_series_kw'] }) if nested_output['Scenario']['Site'].get('Generator') is not None: base.update({ 'gen_kw':nested_output['Scenario']['Site']['Generator']['size_kw'], 'average_yearly_gen_energy_produced':nested_output['Scenario']['Site']['Generator']['average_yearly_energy_produced_kwh'], 'average_annual_energy_exported_gen': nested_output['Scenario']['Site']['Generator']['average_yearly_energy_exported_kwh'], 'year_one_gen_to_battery_series': nested_output['Scenario']['Site']['Generator']['year_one_to_battery_series_kw'], 'year_one_gen_to_load_series': nested_output['Scenario']['Site']['Generator']['year_one_to_load_series_kw'], 'year_one_gen_to_grid_series': nested_output['Scenario']['Site']['Generator']['year_one_to_grid_series_kw'], 'fuel_used_gal': nested_output['Scenario']['Site']['Generator']['fuel_used_gal'], 'existing_gen_total_fixed_om_cost_us_dollars': nested_output['Scenario']['Site']['Generator']['existing_gen_total_fixed_om_cost_us_dollars'], 'existing_gen_total_variable_om_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'existing_gen_total_variable_om_cost_us_dollars'], 'total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'total_fuel_cost_us_dollars'], 'gen_total_variable_om_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'total_variable_om_cost_us_dollars'], 'existing_gen_total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'existing_gen_total_fuel_cost_us_dollars'], }) return base def nested_to_flat_chp(nested_output): base = { 'run_uuid': nested_output['Scenario']['run_uuid'], 'api_version': nested_output['Scenario']['api_version'], 'status': nested_output['Scenario']['status'], 'year_one_electric_load_series': nested_output['Scenario']['Site']['LoadProfile'][ 'year_one_electric_load_series_kw'], 'lcc': nested_output['Scenario']['Site']['Financial']['lcc_us_dollars'], 'lcc_bau': nested_output['Scenario']['Site']['Financial']['lcc_bau_us_dollars'], 'npv': nested_output['Scenario']['Site']['Financial']['npv_us_dollars'], 'net_capital_costs_plus_om': nested_output['Scenario']['Site']['Financial'][ 'net_capital_costs_plus_om_us_dollars'], 'avoided_outage_costs_us_dollars': nested_output['Scenario']['Site']['Financial'][ 'avoided_outage_costs_us_dollars'], 'microgrid_upgrade_cost_us_dollars': nested_output['Scenario']['Site']['Financial'][ 'microgrid_upgrade_cost_us_dollars'], 'year_one_energy_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_energy_cost_us_dollars'], 'year_one_demand_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_demand_cost_us_dollars'], 'year_one_fixed_cost': nested_output['Scenario']['Site']['ElectricTariff']['year_one_fixed_cost_us_dollars'], 'year_one_min_charge_adder': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_min_charge_adder_us_dollars'], 'year_one_energy_cost_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_energy_cost_bau_us_dollars'], 'year_one_demand_cost_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_demand_cost_bau_us_dollars'], 'year_one_fixed_cost_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_fixed_cost_bau_us_dollars'], 'year_one_min_charge_adder_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_min_charge_adder_bau_us_dollars'], 'total_energy_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_energy_cost_us_dollars'], 'total_demand_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_demand_cost_us_dollars'], 'total_fixed_cost': nested_output['Scenario']['Site']['ElectricTariff']['total_fixed_cost_us_dollars'], 'total_min_charge_adder': nested_output['Scenario']['Site']['ElectricTariff'][ 'total_min_charge_adder_us_dollars'], 'total_energy_cost_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'total_energy_cost_bau_us_dollars'], 'total_demand_cost_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'total_demand_cost_bau_us_dollars'], 'total_fixed_cost_bau': nested_output['Scenario']['Site']['ElectricTariff']['total_fixed_cost_bau_us_dollars'], 'total_min_charge_adder_bau': nested_output['Scenario']['Site']['ElectricTariff'][ 'total_min_charge_adder_bau_us_dollars'], 'year_one_bill': nested_output['Scenario']['Site']['ElectricTariff']['year_one_bill_us_dollars'], 'year_one_bill_bau': nested_output['Scenario']['Site']['ElectricTariff']['year_one_bill_bau_us_dollars'], 'year_one_export_benefit': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_export_benefit_us_dollars'], 'year_one_grid_to_load_series': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_to_load_series_kw'], 'year_one_grid_to_battery_series': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_to_battery_series_kw'], 'year_one_energy_cost_series': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_energy_cost_series_us_dollars_per_kwh'], 'year_one_demand_cost_series': nested_output['Scenario']['Site']['ElectricTariff'][ 'year_one_demand_cost_series_us_dollars_per_kw'], 'year_one_utility_kwh': nested_output['Scenario']['Site']['ElectricTariff']['year_one_energy_supplied_kwh'], 'year_one_payments_to_third_party_owner': None, 'total_payments_to_third_party_owner': None, 'total_om_costs': nested_output['Scenario']['Site']['Financial'][ 'total_om_costs_us_dollars'], 'year_one_om_costs': nested_output['Scenario']['Site']['Financial'][ 'year_one_om_costs_us_dollars'] } if nested_output['Scenario']['Site'].get('PV') is not None: base.update({ 'pv_kw': nested_output['Scenario']['Site']['PV']['size_kw'], 'year_one_energy_produced': nested_output['Scenario']['Site']['PV']['year_one_energy_produced_kwh'], 'pv_kw_ac_hourly': nested_output['Scenario']['Site']['PV']['year_one_power_production_series_kw'], 'average_yearly_pv_energy_produced': nested_output['Scenario']['Site']['PV'][ 'average_yearly_energy_produced_kwh'], 'average_annual_energy_exported': nested_output['Scenario']['Site']['PV']['average_yearly_energy_exported_kwh'], 'year_one_pv_to_battery_series': nested_output['Scenario']['Site']['PV']['year_one_to_battery_series_kw'], 'year_one_pv_to_load_series': nested_output['Scenario']['Site']['PV']['year_one_to_load_series_kw'], 'year_one_pv_to_grid_series': nested_output['Scenario']['Site']['PV']['year_one_to_grid_series_kw'], 'existing_pv_om_cost_us_dollars': nested_output['Scenario']['Site']['PV']['existing_pv_om_cost_us_dollars'], }) if nested_output['Scenario']['Site'].get('Storage') is not None: base.update({ 'batt_kw': nested_output['Scenario']['Site']['Storage']['size_kw'], 'batt_kwh': nested_output['Scenario']['Site']['Storage']['size_kwh'], 'year_one_battery_to_load_series': nested_output['Scenario']['Site']['Storage']['year_one_to_load_series_kw'], 'year_one_battery_to_grid_series': nested_output['Scenario']['Site']['Storage']['year_one_to_grid_series_kw'], 'year_one_battery_soc_series': nested_output['Scenario']['Site']['Storage']['year_one_soc_series_pct'], }) if nested_output['Scenario']['Site'].get('Generator') is not None: base.update({ 'gen_kw':nested_output['Scenario']['Site']['Generator']['size_kw'], 'average_yearly_gen_energy_produced':nested_output['Scenario']['Site']['Generator']['average_yearly_energy_produced_kwh'], 'average_annual_energy_exported_gen': nested_output['Scenario']['Site']['Generator']['average_yearly_energy_exported_kwh'], 'year_one_gen_to_battery_series': nested_output['Scenario']['Site']['Generator']['year_one_to_battery_series_kw'], 'year_one_gen_to_load_series': nested_output['Scenario']['Site']['Generator']['year_one_to_load_series_kw'], 'year_one_gen_to_grid_series': nested_output['Scenario']['Site']['Generator']['year_one_to_grid_series_kw'], 'fuel_used_gal': nested_output['Scenario']['Site']['Generator']['fuel_used_gal'], 'existing_gen_total_fixed_om_cost_us_dollars': nested_output['Scenario']['Site']['Generator']['existing_gen_total_fixed_om_cost_us_dollars'], 'existing_gen_total_variable_om_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'existing_gen_total_variable_om_cost_us_dollars'], 'total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'total_fuel_cost_us_dollars'], 'gen_total_variable_om_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'total_variable_om_cost_us_dollars'], 'existing_gen_total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['Generator'][ 'existing_gen_total_fuel_cost_us_dollars'], }) if nested_output['Scenario']['Site'].get('CHP') is not None: base.update({ 'chp_kw': nested_output['Scenario']['Site']['CHP']['size_kw'], 'chp_year_one_fuel_used_mmbtu': nested_output['Scenario']['Site']['CHP']['year_one_fuel_used_mmbtu'], 'chp_year_one_electric_energy_produced_kwh': nested_output['Scenario']['Site']['CHP'][ 'year_one_electric_energy_produced_kwh'], 'chp_year_one_thermal_energy_produced_mmbtu': nested_output['Scenario']['Site']['CHP'][ 'year_one_thermal_energy_produced_mmbtu'], }) if nested_output['Scenario']['Site'].get('Boiler') is not None: base.update({ 'boiler_yearly_fuel_consumption_mmbtu': nested_output['Scenario']['Site']['Boiler'][ 'year_one_boiler_fuel_consumption_mmbtu'], 'boiler_yearly_thermal_production_mmbtu': nested_output['Scenario']['Site']['Boiler'][ 'year_one_boiler_thermal_production_mmbtu'], }) if nested_output['Scenario']['Site'].get('ElectricChiller') is not None: base.update({ 'electric_chiller_yearly_electric_consumption_kwh': nested_output['Scenario']['Site']['ElectricChiller'][ 'year_one_electric_chiller_electric_consumption_kwh'], 'electric_chiller_yearly_thermal_production_tonhr': nested_output['Scenario']['Site']['ElectricChiller'][ 'year_one_electric_chiller_thermal_production_tonhr'], }) if nested_output['Scenario']['Site'].get('AbsorptionChiller') is not None: base.update({ 'absorpchl_ton': nested_output['Scenario']['Site']['AbsorptionChiller']['size_ton'], 'absorp_chl_yearly_thermal_consumption_mmbtu': nested_output['Scenario']['Site']['AbsorptionChiller'][ 'year_one_absorp_chl_thermal_consumption_mmbtu'], 'absorp_chl_yearly_thermal_production_tonhr': nested_output['Scenario']['Site']['AbsorptionChiller'][ 'year_one_absorp_chl_thermal_production_tonhr'], }) if nested_output['Scenario']['Site'].get('ColdTES') is not None: base.update({ 'coldtes_gal': nested_output['Scenario']['Site']['ColdTES']['size_gal'], 'coldtes_thermal_series_ton': nested_output['Scenario']['Site']['ColdTES'][ 'year_one_thermal_from_cold_tes_series_ton'], }) if nested_output['Scenario']['Site'].get('HotTES') is not None: base.update({ 'hottes_gal': nested_output['Scenario']['Site']['HotTES']['size_gal'], 'hottes_thermal_series_mmbtu_per_hr': nested_output['Scenario']['Site']['HotTES'][ 'year_one_thermal_from_hot_tes_series_mmbtu_per_hr'], }) if nested_output['Scenario']['Site'].get('FuelTariff') is not None: base.update({ 'total_boiler_fuel_cost_bau': nested_output['Scenario']['Site']['FuelTariff'][ 'total_boiler_fuel_cost_bau_us_dollars'], 'boiler_total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['FuelTariff'][ 'total_boiler_fuel_cost_us_dollars'], 'chp_total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['FuelTariff'][ 'total_chp_fuel_cost_us_dollars'], 'boiler_bau_total_fuel_cost_us_dollars': nested_output['Scenario']['Site']['FuelTariff'][ 'total_boiler_fuel_cost_bau_us_dollars'], }) return base
python
15
0.637021
153
75.532872
289
starcoderdata
package api import ( "github.com/allenai/beaker/api/searchfield" ) type SearchOperator string const ( OpEqual SearchOperator = "eq" OpNotEqual SearchOperator = "neq" OpGreaterThan SearchOperator = "gt" OpGreaterThanEqual SearchOperator = "gte" OpLessThan SearchOperator = "lt" OpLessThanEqual SearchOperator = "lte" OpContains SearchOperator = "ctn" OpNotContains SearchOperator = "nctn" ) type SortOrder string const ( SortAscending SortOrder = "ascending" SortDescending SortOrder = "descending" ) type FilterCombinator string const ( CombinatorAnd FilterCombinator = "and" CombinatorOr FilterCombinator = "or" ) type ImageSearchOptions struct { SortClauses []ImageSortClause `json:"sort_clauses,omitempty"` FilterClauses []ImageFilterClause `json:"filter_clauses,omitempty"` FilterCombinator FilterCombinator `json:"filter_combinator,omitempty"` } type ImageSortClause struct { Field searchfield.Image `json:"field"` Order SortOrder `json:"order"` } type ImageFilterClause struct { Field searchfield.Image `json:"field"` Operator SearchOperator `json:"operator,omitempty"` Value interface{} `json:"value"` } type DatasetSearchOptions struct { SortClauses []DatasetSortClause `json:"sort_clauses,omitempty"` FilterClauses []DatasetFilterClause `json:"filter_clauses,omitempty"` FilterCombinator FilterCombinator `json:"filter_combinator,omitempty"` OmitResultDatasets bool `json:"omit_result_datasets,omitempty"` IncludeUncommitted bool `json:"include_uncommitted,omitempty"` } type DatasetSortClause struct { Field searchfield.Dataset `json:"field"` Order SortOrder `json:"order"` } type DatasetFilterClause struct { Field searchfield.Dataset `json:"field"` Operator SearchOperator `json:"operator,omitempty"` Value interface{} `json:"value"` } type ExperimentSearchOptions struct { SortClauses []ExperimentSortClause `json:"sort_clauses,omitempty"` FilterClauses []ExperimentFilterClause `json:"filter_clauses,omitempty"` FilterCombinator FilterCombinator `json:"filter_combinator,omitempty"` } type ExperimentSortClause struct { Field searchfield.Experiment `json:"field"` Order SortOrder `json:"order"` } type ExperimentFilterClause struct { Field searchfield.Experiment `json:"field"` Operator SearchOperator `json:"operator,omitempty"` Value interface{} `json:"value"` } type GroupSearchOptions struct { SortClauses []GroupSortClause `json:"sort_clauses,omitempty"` FilterClauses []GroupFilterClause `json:"filter_clauses,omitempty"` FilterCombinator FilterCombinator `json:"filter_combinator,omitempty"` } type GroupSortClause struct { Field searchfield.Group `json:"field"` Order SortOrder `json:"order"` } type GroupFilterClause struct { Field searchfield.Group `json:"field"` Operator SearchOperator `json:"operator,omitempty"` Value interface{} `json:"value"` } type GroupTaskSearchOptions struct { SortClauses []GroupTaskSortClause `json:"sort_clauses,omitempty"` ParameterSortClauses []GroupParameterSortClause `json:"parameter_sort_clauses,omitempty"` FilterClauses []GroupTaskFilterClause `json:"filter_clauses,omitempty"` FilterCombinator FilterCombinator `json:"filter_combinator,omitempty"` } type GroupTaskSortClause struct { Field searchfield.GroupTask `json:"field"` Order SortOrder `json:"order"` } type GroupParameterSortClause struct { Type string `json:"type"` Name string `json:"name"` Order SortOrder `json:"order"` } type GroupTaskFilterClause struct { Field searchfield.GroupTask `json:"field"` Operator SearchOperator `json:"operator,omitempty"` Value interface{} `json:"value"` }
go
7
0.717369
90
30.253968
126
starcoderdata
package com.mathandoro.coachplus.views; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Base64; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import com.mathandoro.coachplus.R; import com.mathandoro.coachplus.Settings; import com.mathandoro.coachplus.api.ApiClient; import com.mathandoro.coachplus.helpers.CircleTransform; import com.mathandoro.coachplus.models.RegisterTeam; import com.mathandoro.coachplus.api.Response.ApiResponse; import com.mathandoro.coachplus.models.Team; import com.mathandoro.coachplus.views.layout.ToolbarFragment; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; import com.squareup.picasso.Target; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import java.io.ByteArrayOutputStream; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class TeamRegistrationActivity extends AppCompatActivity implements ToolbarFragment.ToolbarFragmentListener { final int TEAM_IMAGE_SIZE = 512; final int IMAGE_QUALITY = 95; protected Settings settings; protected ImageView teamImageView; protected boolean imageSelected = false; protected ToolbarFragment toolbarFragment; private Bitmap teamBitmap; private Target target = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { teamBitmap = bitmap; } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_team); settings = new Settings(this); toolbarFragment = (ToolbarFragment) getSupportFragmentManager().findFragmentById(R.id.main_activity_fragment_toolbar); toolbarFragment.setListener(this); toolbarFragment.showBackButton(); Button registerTeamButton = findViewById(R.id.createTeamButton); teamImageView = findViewById(R.id.teamImageView); teamImageView.setOnClickListener((View view) -> pickImage()); final EditText teamNameEditText = findViewById(R.id.teamNameEditText); final CheckBox registerTeamPublicToggleButton = findViewById(R.id.registerTeamPublicToggleButton); registerTeamButton.setOnClickListener((View v) -> registerTeam(teamNameEditText.getText().toString(), registerTeamPublicToggleButton.isActivated(), getSelectedImageBase64()) ); } String getSelectedImageBase64(){ if(teamBitmap == null){ return null; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); teamBitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, bos); byte[] bb = bos.toByteArray(); String imageData = Base64.encodeToString(bb, Base64.DEFAULT); String base64ImagePrefix = "data:image/jpeg;base64,"; return base64ImagePrefix + imageData; } void registerTeam(String teamName, boolean isPublic, String teamImageBase64){ RegisterTeam team = new RegisterTeam(teamName, isPublic, teamImageBase64); String token = settings.getToken(); Call registerTeamCall = ApiClient.instance().teamService.registerTeam(token, team); registerTeamCall.enqueue(new Callback { @Override public void onResponse(Call call, Response response) { if(response.code() == 201){ success(); } else{ fail(); } } @Override public void onFailure(Call call, Throwable t) { fail(); } }); } void pickImage(){ CropImage.activity(null) .setGuidelines(CropImageView.Guidelines.ON) .setRequestedSize(TEAM_IMAGE_SIZE, TEAM_IMAGE_SIZE) .setAspectRatio(1,1) .start(this); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { imageSelected = true; Uri resultUri = result.getUri(); RequestCreator requestCreator = Picasso.with(teamImageView.getContext()).load(resultUri); requestCreator.into(target); requestCreator.transform(new CircleTransform()).into(teamImageView); } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); } } } void success(){ Intent returnIntent = new Intent(); setResult(RESULT_OK, returnIntent); finish(); } void fail(){ Intent returnIntent = new Intent(); setResult(RESULT_CANCELED, returnIntent); finish(); } @Override public void onLeftIconPressed() { finish(); } @Override public void onRightIconPressed() { } }
java
15
0.67943
139
34.512195
164
starcoderdata
/*********************************************************************** * * Copyright (c) 2019-2020 * Copyright (c) 2019-2020 * * This file is part of CsPaint. * * CsPaint is free software, released under the BSD 2-Clause license. * For license details refer to LICENSE provided with this project. * * CopperSpice is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * https://opensource.org/licenses/BSD-2-Clause * ***********************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include
c
5
0.663844
72
30.918919
37
starcoderdata
inline void ll_memcpy_nonaliased_aligned_16(char* __restrict dst, const char* __restrict src, size_t bytes) { assert(src != NULL); assert(dst != NULL); assert(bytes > 0); assert((bytes % sizeof(F32))== 0); ll_assert_aligned(src,16); ll_assert_aligned(dst,16); assert((src < dst) ? ((src + bytes) <= dst) : ((dst + bytes) <= src)); // assert(bytes%16==0); char* end = dst + bytes; if (bytes > 64) { // Find start of 64b aligned area within block // void* begin_64 = LL_NEXT_ALIGNED_ADDRESS_64(dst); //at least 64 bytes before the end of the destination, switch to 16 byte copies void* end_64 = end-64; // Prefetch the head of the 64b area now // _mm_prefetch((char*)begin_64, _MM_HINT_NTA); _mm_prefetch((char*)begin_64 + 64, _MM_HINT_NTA); _mm_prefetch((char*)begin_64 + 128, _MM_HINT_NTA); _mm_prefetch((char*)begin_64 + 192, _MM_HINT_NTA); // Copy 16b chunks until we're 64b aligned // while (dst < begin_64) { _mm_store_ps((F32*)dst, _mm_load_ps((F32*)src)); dst += 16; src += 16; } // Copy 64b chunks up to your tail // // might be good to shmoo the 512b prefetch offset // (characterize performance for various values) // while (dst < end_64) { _mm_prefetch((char*)src + 512, _MM_HINT_NTA); _mm_prefetch((char*)dst + 512, _MM_HINT_NTA); _mm_store_ps((F32*)dst, _mm_load_ps((F32*)src)); _mm_store_ps((F32*)(dst + 16), _mm_load_ps((F32*)(src + 16))); _mm_store_ps((F32*)(dst + 32), _mm_load_ps((F32*)(src + 32))); _mm_store_ps((F32*)(dst + 48), _mm_load_ps((F32*)(src + 48))); dst += 64; src += 64; } } // <FS:ND> There is no guarantee that the remaining about of bytes left is a number of 16. If that's not the case using copy4a will overwrite and trash memory behind the end of dst // <FS:ND> 2014-04-06: This still applies, placing a llassert_always( 0 == (bytes%16)) right after login. // Copy remainder 16b tail chunks (or ALL 16b chunks for sub-64b copies) // // while (dst < end) // { // _mm_store_ps((F32*)dst, _mm_load_ps((F32*)src)); // dst += 16; // src += 16; // } bytes = (U8*)end-(U8*)dst; if( bytes > 0 ) memcpy( dst, src, bytes ); // </FS:ND> }
c
15
0.600182
181
26.4625
80
inline
import gql from 'graphql-tag' export default gql` subscription onWalletUpdate { walletUpdate { primaryAccount { id } } } `
javascript
4
0.65534
49
16.166667
12
starcoderdata
Matrix2 Matrix2::operator*(const Matrix2 &m) const { // This could be return Matrix2( data[0][0] * m.data[0][0] + data[0][1] * m.data[1][0], data[0][0] * m.data[0][1] + data[0][1] * m.data[1][1], data[1][0] * m.data[0][0] + data[1][1] * m.data[1][0], data[1][0] * m.data[0][1] + data[1][1] * m.data[1][1] ); }
c++
11
0.516923
113
39.75
8
inline
int savage4_isr(u32 n, void *d) { graph_t *graph = (graph_t *)d; graph->vsync++; /* Clear interrupt source */ low_setfar(savage4.cmdsel, SubsystemCtl, VsyncEna | VsyncInt); return IRQ_IGNORE; }
c
8
0.630841
64
19.6
10
inline
from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from apps.api.serializers import ClientSerializer, ProductSerializer, ProductBills from apps.client.models import Clients from apps.product.models import Products from apps.bill.models import Bills from rest_framework import status import json from django.core.exceptions import ObjectDoesNotExist import csv from django.http import HttpResponse #API clientes @api_view(["GET"]) @csrf_exempt @permission_classes([IsAuthenticated]) def get_clients(request): clients = Clients.objects.all() serializer = ClientSerializer(clients, many=True) return JsonResponse({'clients': serializer.data}, safe=False, status=status.HTTP_200_OK) @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_client(request): payload = json.loads(request.body) user = request.user try: client = Clients.objects.create( document=payload["document"], first_name=payload["first_name"], last_name=payload["last_name"], email=payload["email"] ) serializer = ClientSerializer(client) return JsonResponse({'client': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["PUT"]) @csrf_exempt @permission_classes([IsAuthenticated]) def update_client(request, client_id): payload = json.loads(request.body) try: client = Clients.objects.filter(id=client_id) # returns 1 or 0 client.update(**payload) clientNew = Clients.objects.get(id=client_id) serializer = ClientSerializer(clientNew) return JsonResponse({'client': serializer.data}, safe=False, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["DELETE"]) @csrf_exempt @permission_classes([IsAuthenticated]) def delete_client(request, client_id): try: client = Clients.objects.get(id=client_id) client.delete() return Response(status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'deleted'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) #API productos. @api_view(["GET"]) @csrf_exempt @permission_classes([IsAuthenticated]) def get_products(request): products = Products.objects.all() serializer = ProductSerializer(products, many=True) return JsonResponse({'products': serializer.data}, safe=False, status=status.HTTP_200_OK) @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_product(request): payload = json.loads(request.body) try: product = Products.objects.create( name = payload["name"], description = payload["description"], attribute1 = payload["attribute1"], attribute2 = payload["attribute2"], attribute3 = payload["attribute3"], attribute4 = payload["attribute4"] ) serializer = ProductSerializer(product) return JsonResponse({'product': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["PUT"]) @csrf_exempt @permission_classes([IsAuthenticated]) def update_product(request, product_id): payload = json.loads(request.body) try: product = Products.objects.filter(id=product_id) # returns 1 or 0 product.update(**payload) productNew = Products.objects.get(id=product_id) serializer = ProductSerializer(productNew) return JsonResponse({'product': serializer.data}, safe=False, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["DELETE"]) @csrf_exempt @permission_classes([IsAuthenticated]) def delete_product(request, product_id): try: client = Products.objects.get(id=product_id) client.delete() return Response(status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'deleted'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) #API Facturas. #Bills #ProductBills @api_view(["GET"]) @csrf_exempt @permission_classes([IsAuthenticated]) def get_bills(request): bills = Bills.objects.all() serializer = ProductBills(bills, many=True) return JsonResponse({'bills': serializer.data}, safe=False, status=status.HTTP_200_OK) @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_bill(request): payload = json.loads(request.body) try: client = Clients.objects.get(id=payload["client_id"]) bill = Bills.objects.create( name = payload["name"], client_id = client, company_name = payload["company_name"], nit = payload["nit"], code = payload["code"] ) product = Products.objects.get(id=payload["product"]) bill.product.add(product) serializer = ProductBills(bill) return JsonResponse({'bill': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong' + str(Exception)}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["PUT"]) @csrf_exempt @permission_classes([IsAuthenticated]) def update_bill(request, bill_id): payload = json.loads(request.body) try: bill = Bills.objects.filter(id=bill_id) # returns 1 or 0 bill.update(**payload) billNew = Bills.objects.get(id=bill_id) serializer = ProductBills(billNew) return JsonResponse({'bill': serializer.data}, safe=False, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["DELETE"]) @csrf_exempt @permission_classes([IsAuthenticated]) def delete_bill(request, bill_id): try: bill = Bills.objects.get(id=bill_id) bill.delete() return Response(status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'bill': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'deleted'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["GET"]) @csrf_exempt @permission_classes([IsAuthenticated]) def get_data_on_csv(request): try: clients = Clients.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="NumBillsPerCli.csv"' writer = csv.writer(response) for client in clients: bs = len (Bills.objects.filter(client_id = client)) writer.writerow([client.document, client.first_name + ' ' + client.last_name, bs]) return response except ObjectDoesNotExist as e: return JsonResponse({'bill': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'deleted'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
python
15
0.687901
146
37.619469
226
starcoderdata
#include #include int main(int argc, char **argv) { std::string error; oyoung::python::executor executor(argc, argv); if (not executor.exec(R"( import json print json.dumps({ 'project': { 'name': 'oyoungs/python', 'src_files': [ 'executor.cc' ] } }, indent=2) )", error)) { std::cerr << error << std::endl; } if (not executor.exec_file("test/python/test.py", error)) { std::cerr << error << std::endl; } if (not executor.exec_file("test/python/NotFound.py", error)) { std::cerr << error << std::endl; } return 0; }
c++
9
0.540091
67
16.394737
38
starcoderdata
/* 更新列表数据 */ export function setGroupList(groupList) { return { type: 'employeeGroup/stateWillUpdate', payload: { groupList, }, }; } /* 更新列表数据记录数 */ export function setListCount(count) { return { type: 'employeeGroup/stateWillUpdate', payload: { count, }, }; } /* 获取人员列表数据 */ export function getPersonList(orgId, record) { return { type: 'employeeGroup/getPersonList', payload: { orgId, record, }, }; } /* 获取分组列表数据 */ export function getGroupList(id) { return { type: 'employeeGroup/getGroupList', payload: { id, }, }; } /* 删除分组列表数据 */ export function deleteGroupList(record) { return { type: 'employeeGroup/deleteGroupList', payload: { record, }, }; } /* 获取组织树数据 */ export function getOrgTree() { return { type: 'employeeGroup/getOrgTree', payload: { }, }; } /* 保存分组列表数据 */ export function saveGroupList(groupObj) { return { type: 'employeeGroup/saveGroupList', payload: { groupObj, }, }; } /* 分配至该组 */ export function distributionGroup(orgId, record, newRecord) { return { type: 'employeeGroup/distributionGroup', payload: { newRecord, orgId, record, }, }; } /* 分配负责人 */ export function distributionBlame(newData) { return { type: 'employeeGroup/distributionBlame', payload: { newData, }, }; } export function onClickStyle(rowId) { return { type: 'employeeGroup/stateWillUpdate', payload: { rowId, }, }; }
javascript
8
0.597545
61
14.636364
99
starcoderdata
package com.example.gorda.snapchatclone.loginRegistration; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.gorda.snapchatclone.MainActivity; import com.example.gorda.snapchatclone.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import java.util.Map; public class RegisterActivity extends AppCompatActivity { private Button mRegister; private EditText mEmail, mPassword, mUsername; private TextInputLayout emailLayout, passwordLayout, usernameLayout; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener firebaseAuthStateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { Intent intent = new Intent(getApplication(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } } }; mAuth = FirebaseAuth.getInstance(); mRegister = findViewById(R.id.buttonRegister); mEmail = findViewById(R.id.editTextEmailRegister); mPassword = findViewById(R.id.editTextPasswordRegister); mUsername = findViewById(R.id.editTextUsernameRegister); passwordLayout = findViewById(R.id.editTextPasswordRegisterLay); emailLayout = findViewById(R.id.editTextEmailRegisterLay); usernameLayout = findViewById(R.id.editTextUsernameRegisterLay); mPassword.addTextChangedListener(new MyTextWatcher(mPassword)); mUsername.addTextChangedListener(new MyTextWatcher(mUsername)); mEmail.addTextChangedListener(new MyTextWatcher(mEmail)); mRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!validateEmail()) { return; } if (!validatePassword()) { return; } if (!validateUsername()) { return; } final String username = mUsername.getText().toString(); final String email = mEmail.getText().toString(); final String password = mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener { @Override public void onComplete(@NonNull Task task) { if (!task.isSuccessful()) { Toast.makeText(getApplication(), "Sign in ERROR", Toast.LENGTH_LONG).show(); } else { String userId = mAuth.getCurrentUser().getUid(); DatabaseReference currentUserDB = FirebaseDatabase.getInstance().getReference().child("users").child(userId); Map userInfo = new HashMap(); userInfo.put("email", email); userInfo.put("username", username); userInfo.put("profileImageUrl", "default"); currentUserDB.updateChildren(userInfo); } } }); } }); } private boolean validatePassword() { if (mPassword.getText().toString().trim().isEmpty()) { passwordLayout.setError("Enter your password"); requestFocus(mPassword); return false; } passwordLayout.setErrorEnabled(false); return true; } private boolean validateEmail() { if (mEmail.getText().toString().trim().isEmpty()) { emailLayout.setError("Enter your email"); requestFocus(mEmail); return false; } emailLayout.setErrorEnabled(false); return true; } private boolean validateUsername() { if (mUsername.getText().toString().trim().isEmpty()) { usernameLayout.setError("Enter your username"); requestFocus(mUsername); return false; } usernameLayout.setErrorEnabled(false); return true; } private void requestFocus(View view) { if (view.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } private class MyTextWatcher implements TextWatcher { private View view; private MyTextWatcher(View view) { this.view = view; } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { switch (view.getId()) { case R.id.editTextEmailRegister: validateEmail(); break; case R.id.editTextPasswordRegister: validatePassword(); break; case R.id.editTextUsernameRegister: validateUsername(); break; } } } @Override protected void onStart() { super.onStart(); mAuth.addAuthStateListener(firebaseAuthStateListener); } @Override protected void onStop() { super.onStop(); mAuth.removeAuthStateListener(firebaseAuthStateListener); } }
java
26
0.610782
153
32.929648
199
starcoderdata
def get_trending(args): """Get Trending, shared between full and regular endpoints.""" # construct args time = args.get("time") if args.get("time") is not None else 'week' current_user_id = args.get("user_id") args = { 'time': time, 'genre': args.get("genre", None), 'with_users': True, 'limit': TRENDING_LIMIT, 'offset': 0 } # decode and add user_id if necessary if current_user_id: decoded_id = decode_string_id(current_user_id) args["current_user_id"] = decoded_id tracks = get_trending_tracks(args) return list(map(extend_track, tracks))
python
10
0.599374
71
31
20
inline
from collections.abc import Callable from typing import NamedTuple from profile_generator.model.linalg import Matrix, Vector class ColorSpace(NamedTuple): xyz_matrix: Matrix xyz_inverse_matrix: Matrix white_point: Vector gamma: Callable[[float], float] inverse_gamma: Callable[[float], float]
python
10
0.753165
57
25.333333
12
starcoderdata
package com.jamiahus.ifunieray; /** * Created by jamia on 3/24/2018. */ public class Task { String TaskTitle; String TaskDescription; String Month; int DayOfMonth; int Year; int TaskID; public Task (String inputTaskTitle, String inputTaskDescription, String inputMonth, int inputDayOfMonth, int inputYear, int taskID){ TaskTitle = inputTaskTitle; TaskDescription = inputTaskDescription; Month = inputMonth; DayOfMonth = inputDayOfMonth; Year = inputYear; TaskID = taskID; } public Task (int taskID){ TaskID =taskID; } public int GetTaskID(){ return TaskID; } }
java
7
0.622721
87
21.28125
32
starcoderdata
void startServer() { initServer(); try { server.start(); long jvmUpTime = ManagementFactory.getRuntimeMXBean().getUptime(); log().info("Server started in " + jvmUpTime + "ms on port " + httpPort); Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownRunnable())); if (useStdInShutdown) { // generally for use in IDE via JettyRun, Use CTRL-D in IDE console to shutdown BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); while ((systemIn.readLine()) != null) { // ignore anything except CTRL-D by itself } System.out.println("Shutdown via CTRL-D"); System.exit(0); } } catch (Exception e) { e.printStackTrace(); System.exit(100); } }
java
14
0.616915
96
31.2
25
inline
const Tweet = require('../shared/tweet'); const { whoami, reply } = require('../shared/twitter'); const twitter = require('../shared/twitter'); const BOT_HANDLE = '@captions_please'; let my_id = null; const do_nothing = (context) => { context.res = { status: 200, }; context.done(); }; const respond_no_photos = (context, tweet, has_invalid_media) => { context.log.info('No photos to parse, early return'); // Even on failure, we'll respond 200, as there's nothing to retry here context.res = { status: 200, }; const message = has_invalid_media ? 'I only know how to decode photos, not gifs or videos. Sorry!' : "I didn't find any photos to decode, but I appreciate the shoutout!"; return twitter.reply(tweet.id(), message); }; module.exports = async (context, req) => { if (!req.body.tweet_create_events) { context.log.info('No body, early return'); return do_nothing(context); } context.log('New webhook request:\n' + JSON.stringify(req.body, null, 2)); const tweet = new Tweet(req.body.tweet_create_events[0]); if (!tweet.is_tweet() && !tweet.is_reply() && !tweet.is_quote_tweet()) { context.log.info('Not a tweet or reply, early return'); return do_nothing(context); } if (!tweet.explicitly_contains_handle(BOT_HANDLE)) { context.log.info('Not mentioned in the body message, early return'); return do_nothing(context); } if (!my_id) { my_id = await whoami(); context.log.info('Getting the bot id of ' + my_id); } if (tweet.id() == my_id) { context.log.info('Author is myself, early return'); return do_nothing(context); } let parent_tweet = null; if (!tweet.has_photos()) { if (tweet.is_quote_tweet()) { parent_tweet = new Tweet(tweet.data.quoted_status); } else { parent_tweet = await tweet.get_parent_tweet(); } context.log.info( 'Parent tweet is: ' + JSON.stringify(parent_tweet, null, 2) ); if (!parent_tweet || !parent_tweet.has_photos()) { const has_invalid_media = tweet.has_media() || (parent_tweet && parent_tweet.has_media()); return respond_no_photos(context, tweet, has_invalid_media); } } const tweet_to_scan = parent_tweet || tweet; const item = { to_reply_id: tweet.id(), media: tweet_to_scan.get_photos(), }; context.log('Placing the message on the queue for parsing'); context.log(item); context.bindings.imageQueue = JSON.stringify(item); return do_nothing(context); };
javascript
10
0.643054
76
29.25
84
starcoderdata
int readChunk(char[] c, int off, int len) throws SQLException { if (JdbcDebugCfg.entryActive) debug[methodId_readChunk].methodEntry(); try { int rowsToRead; String data; int copyLen; int copyOffset; int readLen = 0; int dataLen; rowsToRead = (len-1)/clob_.chunkSize_; clob_.prepareGetLobDataStmt(); PreparedStatement GetClobDataStmt = clob_.getGetLobDataStmt(); if ((traceWriter_ != null) && ((traceFlag_ == T2Driver.LOB_LVL) || (traceFlag_ == T2Driver.ENTRY_LVL))) { traceWriter_.println(getTraceId() + "readChunk(<char>," + off + "," + len + ") - GetLobDataStmt params: tableName_=" + clob_.tableName_ + " dataLocator_=" + clob_.dataLocator_ + " currentChunkNo_=" + currentChunkNo_ + " currentChunkNo_+rowsToRead=" + (currentChunkNo_+rowsToRead)); } synchronized (GetClobDataStmt) { GetClobDataStmt.setString(1, clob_.tableName_); GetClobDataStmt.setLong(2, clob_.dataLocator_); GetClobDataStmt.setInt(3, currentChunkNo_); GetClobDataStmt.setInt(4, currentChunkNo_+rowsToRead); ResultSet rs = GetClobDataStmt.executeQuery(); copyLen = len; copyOffset = off; try { while (rs.next()) { data = rs.getString(1); currentChunkNo_++; charsRead_ = data.length(); dataLen = charsRead_; if (c == null) { data.getChars(0, dataLen, chunk_, 0); readLen += dataLen; currentChar_ = 0; break; } else { if (copyLen >= dataLen) { data.getChars(0, dataLen, c, copyOffset); copyLen -= dataLen; readLen += dataLen; copyOffset += dataLen; currentChar_ = dataLen; } else { data.getChars(0, copyLen, c, copyOffset); // copy the rest of data to chunk data.getChars(copyLen, dataLen, chunk_, copyLen); readLen += copyLen; currentChar_ = copyLen; break; } } } } finally { rs.close(); } } if ((traceWriter_ != null) && ((traceFlag_ == T2Driver.LOB_LVL) || (traceFlag_ == T2Driver.ENTRY_LVL))) { traceWriter_.println(getTraceId() + "readChunk(<char>," + off + "," + len + ") - LOB data read: charsRead_=" + charsRead_ + " readLen=" + readLen + " copyLen=" + copyLen + " currentChunkNo_=" + currentChunkNo_); } if (readLen == 0) return -1; else return readLen; } finally { if (JdbcDebugCfg.entryActive) debug[methodId_readChunk].methodExit(); } }
java
24
0.578906
107
25.677083
96
inline
/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * Copyright © 2017-2018 Amdocs * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.aai.sparky.aggregatevnf.search; import static org.junit.Assert.assertNotNull; import javax.ws.rs.core.MediaType; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.onap.aai.restclient.client.OperationResult; import org.onap.aai.restclient.enums.RestAuthenticationMode; import org.onap.aai.sparky.dal.rest.config.RestEndpointConfig; import org.onap.aai.sparky.search.SearchServiceAdapter; import org.onap.aai.sparky.search.entity.QuerySearchEntity; public class AggregateVnfSearchProviderTest { private AggregateVnfSearchProvider aggregateVnfSearchProvider; private RestEndpointConfig restEndpointConfig; private SearchServiceAdapter searchserviceAdapter; private QuerySearchEntity querySearchEntity; private String successResponsePayload; private OperationResult successResult = null; private OperationResult resultValue = null; private String goodDrTargetUrl = "https://0.0.0.0:9502/ui-request/servicegraph"; @Before public void init() throws Exception { restEndpointConfig = new RestEndpointConfig(); successResponsePayload = "good-payload"; successResult = new OperationResult(200, successResponsePayload); restEndpointConfig.setRestAuthenticationMode(RestAuthenticationMode.SSL_BASIC); searchserviceAdapter = Mockito.mock(SearchServiceAdapter.class); resultValue = Mockito.mock(OperationResult.class); aggregateVnfSearchProvider = new AggregateVnfSearchProvider(searchserviceAdapter, "auto-suggest", "schema"); querySearchEntity = new QuerySearchEntity(); } @Test public void updateValues() { assertNotNull(aggregateVnfSearchProvider.search(querySearchEntity)); aggregateVnfSearchProvider.setAutoSuggestIndexName("auto-suggest-index-1"); } @Test public void testProxyMessage_Success() { Mockito.when(searchserviceAdapter.doPost(Mockito.eq(goodDrTargetUrl), Mockito.anyString())).thenReturn(successResult); Mockito.when(resultValue.getResultCode()).thenReturn(200); aggregateVnfSearchProvider.search(querySearchEntity); } }
java
13
0.70784
122
37.580247
81
starcoderdata
def load(self, path): try: self._display.v('Loading site config from %s' % path) self._path = os.path.realpath(path) data = self.load_file(self._path) # Special case for plugin dirs if 'plugin_dirs' in data: if not isinstance(data['plugin_dirs'], list): data['plugin_dirs'] = [data['plugin_dirs']] for idx, entry in enumerate(data['plugin_dirs']): if not entry.startswith('/'): # Normalize path based on location of site config data['plugin_dirs'][idx] = os.path.join(os.path.dirname(self._path), entry) # Special case for default apps if 'default_apps' in data: if not isinstance(data['default_apps'], dict): raise ConfigError('"default_apps" key expects a dict, got: %s' % type(data['default_apps'])) for section, v in data['default_apps'].items(): if not isinstance(v, list): raise ConfigError('"default_apps" key expects a dict with section names and a list of default apps') self._config.update(data) except Exception as e: raise ConfigError(str(e))
python
18
0.534003
124
55.304348
23
inline
from datetime import datetime from flask import jsonify, Blueprint default_rest = Blueprint('default_rest', __name__) @default_rest.route('/') @default_rest.route('/health') @default_rest.route('/ping') def ping(): return "pong", 200 def json_error_message(message): return jsonify({'error': message, 'timestamp': str(datetime.now())})
python
12
0.69914
72
22.266667
15
starcoderdata
async def test_basic_data(client_mock, param: Param): """Test for basic data""" await client_mock.update() assert client_mock.on == True if param.type == "android": assert client_mock.system == SYSTEM_ANDROID_DECRYPTED assert client_mock.sources == MOCK_ANDROID_SOURCES assert client_mock.applications == { app["id"]: app for app in APPLICATIONS["applications"] if "id" in app } assert ( client_mock.application_id == "org.droidtv.nettv.market.MarketMainActivity-org.droidtv.nettv.market" ) assert client_mock.quirk_ambilight_mode_ignored == True assert client_mock.os_type == "MSAF_2019_P" elif param.type == "saphi": assert client_mock.system == SYSTEM_SAPHI_DECRYPTED assert client_mock.sources == MOCK_SAPHI_SOURCES assert client_mock.applications == {} assert client_mock.application_id == None assert client_mock.quirk_ambilight_mode_ignored == True assert client_mock.os_type == "Linux" assert client_mock.channels == { "1648": {"ccid": 1648, "preset": "1", "name": "Irdeto scrambled"}, "1649": {"ccid": 1649, "preset": "2"}, } assert client_mock.powerstate == POWERSTATE["powerstate"] assert client_mock.screenstate == SCREENSTATE["screenstate"] assert client_mock.huelamp_power == HUELAMPPOWER["power"]
python
11
0.633286
85
42
33
inline
<?php namespace App\Http\Livewire\Admin\Projects; use App\Models\Project; use Livewire\Component; use Livewire\WithFileUploads; class Index extends Component { use WithFileUploads; public $project_id,$project_name, $project_description, $project_type, $url,$project_image, $iteration; public function render() { return view('livewire.admin.projects.index',[ 'portfolios'=> Project::all(), ])->slot('main'); } /** * The attributes that are mass assignable. * * @var array */ private function resetInputFields(){ $this->project_name = ''; $this->project_description = ''; $this->project_type = ''; $this->url = ''; } /** * The attributes that are mass assignable. * * @var array */ public function store() { $this->validate([ 'project_name' => 'required|string|max:255', 'project_type' => 'required|string|max:100', 'url' => 'nullable|string|max:255', 'project_description' => 'nullable', 'project_image' => 'nullable |mimes:jpg, jpeg, png, bmp, gif' ]); $project_img=""; if($this->project_image != ''){ $project_img= $this->project_image->store("images.portfolio", "public"); } Project::updateOrCreate(['id' => $this->project_id], [ 'project_name' => $this->project_name, 'project_type' => $this->project_type, 'url' => $this->url, 'project_description' => $this->project_description, 'project_image' => $project_img, ]); $this->emit('closeModalEvent'); session()->flash('message', $this->project_id ? 'Portfolio Updated Successfully.' : 'Portfolio Created Successfully.'); $this->project_image =null; $this->iteration++; $this->resetInputFields(); } /** * The attributes that are mass assignable. * * @var array */ public function edit($id) { $project = Project::findOrFail($id); $this->project_id = $id; $this->project_name = $project->project_name; $this->project_type = $project->project_type; $this->url = $project->url; $this->project_description = $project->project_description; $this->project_image = $project->project_image; } public function delete($id){ $project = Project::findOrfail($id); $project->delete(); session()->flash('message', 'project delete successfully'); } }
php
14
0.535754
103
27.114583
96
starcoderdata
angular.module('ex1').controller('HomeCtrl',function($scope,$interval,equationResolverService){ $scope.resolve=function(){ // action function - click on resolve button in app $scope.outputResolve=equationResolverService.resolve($scope.aValue, $scope.bValue); // return resolve of equatation // lighting resolve - just visual effects $scope.colorOfResolve='#6FD49A' ; $interval(function(){ $scope.colorOfResolve='white';} ,3000); } ; });
javascript
14
0.704981
124
46.545455
11
starcoderdata
package CF.R135div2; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class SpecialOfferSuperPrice999Bourles { static BufferedReader input; static StringTokenizer _stk; static String readln() throws IOException { String l = input.readLine(); if (l != null) _stk = new StringTokenizer(l, " "); return l; } static String next() { return _stk.nextToken(); } static long nextInt() { return Long.parseLong(next()); } // static void dbg(Object... o) { // System.out.println(Arrays.deepToString(o)); // } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); input = new BufferedReader(new InputStreamReader(System.in)); input = new BufferedReader(new FileReader( "SpecialOfferSuperPrice999Bourles")); while (true) { if (readln() == null) { break; } numero = new StringBuilder(next()); restar = new StringBuilder(); d = nextInt(); end = false; first = true; finito = false; for (int i = numero.length() - 1; i > -1; i--) { restar.insert(0, numero.charAt(i)); if (Long.parseLong(restar.toString()) + 1 > d) { end = true; break; } first = false; } n = Long.parseLong(numero.toString()); // // dbg("end, restar, numero, d no if//", end, restar, numero, d); // if (!end) { // restar.insert(0, (numero.charAt(0) - '0') - 1); // r = Long.parseLong(restar.toString()); // if ((r + 1) < d) { // // r = Integer.parseInt(restar.toString()); // System.out.println(n - (r + 1)); // finito = true; // } // } if (!finito) { restar.replace(0, 1, "0"); r = Long.parseLong(restar.toString()); // dbg("end, restar, numero, d end t//", end, restar, numero, // d); if (first) { System.out.println(n - (r)); } else { System.out.println(n - (r + 1)); } } } } static StringBuilder numero, restar; static long d, n, r; static boolean end, first, finito; }
java
17
0.616496
70
22.075269
93
starcoderdata
def generate_levels(N, minN, maxN, mode='lin'): """Auto-generate evenly-spaced level values between the min and max value. Input: ------ N: int or float, number of levels (int) to generate (lin or log mode); or the ratio (float) to use to separate levels (ratio mode). minN: float, minimum level value maxN: float, maximum level value mode: str, options are 'lin' (default), 'log', or 'ratio'. lin: N linearly spaced values between minN and maxN log: N logarithmically spaced values between minN and maxN ratio: levels that are spaced by a constant ratio N. minN will be used as minimum level value and the maximum level value is less than or equal to maxN. Returns: -------- levels: list of floats, evenly spaced values according to mode """ if mode == 'lin': levels = list(np.linspace(minN, maxN, num=N, endpoint=True)) return levels if mode == 'log': base = 10. start = m.log(minN, base) stop = m.log(maxN, base) levels = list(np.logspace(start, stop, num=N, endpoint=True, base=base)) return levels if mode == 'ratio': # set minN as the minimum and get all other values until maxN tmpmax = 0. levels = [minN] while tmpmax < maxN: next_val = levels[-1] * float(N) if next_val <= maxN: levels.append(next_val) tmpmax = next_val else: break return levels raise RuntimeError("Level generation mode {} not " + "recognized.".format(mode))
python
12
0.53915
72
34.78
50
inline
<?php namespace ModStart\Field; class CascadeGroup extends AbstractField { protected $isLayoutField = true; public static function getAssets() { return [ 'style' => '.ub-field-cascade-group{} .ub-field-cascade-group.cascade-group-hide{visibility:hidden;height:0;width:0;overflow:hidden;}', ]; } /** * @return string */ public function render() { $column = $this->column(); return <<<HTML <div class="ub-field-cascade-group cascade-group-hide" id="$column"> HTML; } /** * @return void */ public function end() { $this->context->html($this->column() . '_end')->html(' } }
php
14
0.568022
147
19.970588
34
starcoderdata
/*! For license information please see https://www.ajizablg.com/simple-video-capture/oss-licenses.json */ import '../scss-dest/default.css'; import '../scss-dest/main.css'; import '../scss-dest/reset.css'; import '../scss-dest/controls.css'; import '../node_modules/vncho-lib/css/explanations.css'; import '../node_modules/vncho-lib/css/header.css'; import '../scss-dest/indicator.css'; import '../scss-dest/main-notice.css'; import '../scss-dest/preview.css'; import '../scss-dest/results.css';
javascript
3
0.714286
105
37.307692
13
starcoderdata
package de.adito; import de.adito.aditoweb.common.jdito.plugin.IPluginFacade; import de.adito.aditoweb.common.jdito.plugin.PluginException; import de.adito.aditoweb.common.jdito.plugin.impl.AbstractPlugin; /** * Demo Plugin for Adito. * * @author d.buechler, 05.11.2020. */ public class DemoPlugin extends AbstractPlugin { public String getDescription() { return "Demo Plugin"; } public void initStatic() { } public void init() { } @Override public Object[] execute(Object[] objects, IPluginFacade iPluginFacade) throws PluginException { return new Object[]{"Erfolgreiche Pluginausführung"}; } }
java
9
0.737374
97
22.1
30
starcoderdata
<?php namespace App\Http\Controllers\staff; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Carbon; class dashboard extends Controller { public function __construct() { Carbon::setlocale('fr'); $this->middleware('Permission:class,modifier', ['only' => 'class']); $this->middleware('Permission:class,voir', ['only' => 'class1']); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('staff.home'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function class() { return 'class => modifier'; } public function class1() { return 'class => voir'; } }
php
12
0.602198
76
20.666667
42
starcoderdata
@Test void testCalculateSettlementMoves_valid() { // player can afford settlement testPlayer.setWallet(new Settlement().getPrice()); testPlayer = playerService.save(testPlayer); // setup board, create settlement with two adjacent roads Coordinate coordinate = testBoard.getAllCoordinates().get(0); Settlement settlement = new Settlement(); settlement.setCoordinate(coordinate); settlement.setUserId(testPlayer.getUserId()); testBoard.addSettlement(settlement); Road road1 = new Road(); road1.setCoordinate1(coordinate); road1.setCoordinate2(coordinate.getNeighbors().get(0)); road1.setUserId(testPlayer.getUserId()); testBoard.addRoad(road1); Road road2 = new Road(); road2.setCoordinate1(coordinate.getNeighbors().get(0)); road2.setCoordinate2(coordinate.getNeighbors().get(0).getNeighbors().get(0)); road2.setUserId(testPlayer.getUserId()); testBoard.addRoad(road2); // perform List<BuildMove> moves = MoveCalculator.calculateSettlementMoves(testGame); moveRepository.saveAll(moves); // assert moveService.findMovesForGameAndPlayer(testGame.getId(), testPlayer.getUserId()); assertEquals(1, moves.size(), "for every open road end point, a move gets added"); assertEquals(BuildMove.class, moves.get(0).getClass(), "the added move must be a build move"); assertEquals(Settlement.class, moves.get(0).getBuilding().getClass(), "the building must be a settlement"); }
java
11
0.655738
88
36.454545
44
inline
#include "EngineImpl.h" #include "../Engine/HGObject.h" #include "Font.hpp" #include "Texture.h" #include "Asset.h" using namespace HG; using namespace HGEngine::V1SDL; Font* HGEngine::V1SDL::Asset::CreateFont( const char *strFontName, const char *strFontFilePath, const un32 unPtSize ) { auto pF = new Font( strFontName, ( m_strHomeDir + strFontFilePath ).c_str(), unPtSize ); return pF; } Texture* HGEngine::V1SDL::Asset::CreateTexture( const char* strTextureName, const char* strTextureFilePath ) { auto pF = new Texture( strTextureName, ( m_strHomeDir + strTextureFilePath ).c_str() ); return pF; }
c++
11
0.7312
119
31.894737
19
starcoderdata
func (s *Server) Route() { switch s.db { case nil: // No connection to the database to share. s.r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { s.OopsHandler(w, r, errors.WithMessage(db.ErrMissing, "database")) }) default: s.r.HandleFunc("/", s.HomeHandler) s.r.HandleFunc("/node", s.NodesHandler) s.r.HandleFunc("/node/{naddr}/delete", s.NodeHandler) s.r.HandleFunc("/env/{eid:[0-9]+}/", s.EnvHandler) s.r.HandleFunc("/project", s.ProjectsHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/", s.ProjectHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/env", s.EnvsHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/env/{eid:[0-9]+}/{do}", s.EnvHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/var", s.VarsHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/var/{vid:[0-9]+}", s.VarHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/var/{vid:[0-9]+}/delete", s.VarHandler) s.r.HandleFunc("/project/{pid:[a-z-]+}/deploy", s.DeployHandler) s.r.HandleFunc("/vars", s.CacheHandler) s.r.HandleFunc("/favicon.ico", s.StaticHandler) } }
go
16
0.644258
80
43.666667
24
inline
// ***************************************************************************** /*! \file src/Control/Walker/Options/DiffEq.hpp \copyright 2012-2015 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Differential equation options and associations for walker \details Differential equation options and associations for walker */ // ***************************************************************************** #ifndef WalkerDiffEqOptions_h #define WalkerDiffEqOptions_h #include #include "TaggedTuple.hpp" #include "Toggle.hpp" #include "Keywords.hpp" #include "Walker/Options/InitPolicy.hpp" #include "Walker/Options/CoeffPolicy.hpp" namespace walker { namespace ctr { //! Differential equation types enum class DiffEqType : uint8_t { NO_DIFFEQ=0, OU, DIAG_OU, SKEWNORMAL, GAMMA, BETA, NUMFRACBETA, MASSFRACBETA, MIXNUMFRACBETA, MIXMASSFRACBETA, DIRICHLET, MIXDIRICHLET, GENDIR, WRIGHTFISHER, POSITION, DISSIPATION, VELOCITY }; //! Pack/Unpack: forward overload to generic enum class packer inline void operator|( PUP::er& p, DiffEqType& e ) { PUP::pup( p, e ); } //! Differential equation key used to access a diff eq in a factory using DiffEqKey = tk::tuple::tagged_tuple< tag::diffeq, DiffEqType, tag::initpolicy, ctr::InitPolicyType, tag::coeffpolicy, ctr::CoeffPolicyType >; //! Class with base templated on the above enum class with associations class DiffEq : public tk::Toggle< DiffEqType > { public: // List valid expected choices to make them also available at compile-time using keywords = brigand::list< kw::ornstein_uhlenbeck , kw::diag_ou , kw::skewnormal , kw::gamma , kw::beta , kw::numfracbeta , kw::massfracbeta , kw::mixnumfracbeta , kw::mixmassfracbeta , kw::dirichlet , kw::mixdirichlet , kw::gendir , kw::wrightfisher , kw::position , kw::dissipation , kw::velocity >; //! Constructor: pass associations references to base, which will handle //! class-user interactions explicit DiffEq() : tk::Toggle< DiffEqType >( "Differential equation", //! Enums -> names { { DiffEqType::NO_DIFFEQ, "n/a" }, { DiffEqType::OU, kw::ornstein_uhlenbeck::name() }, { DiffEqType::DIAG_OU, kw::diag_ou::name() }, { DiffEqType::SKEWNORMAL, kw::skewnormal::name() }, { DiffEqType::GAMMA, kw::gamma::name() }, { DiffEqType::BETA, kw::beta::name() }, { DiffEqType::NUMFRACBETA, kw::numfracbeta::name() }, { DiffEqType::MASSFRACBETA, kw::massfracbeta::name() }, { DiffEqType::MIXNUMFRACBETA, kw::mixnumfracbeta::name() }, { DiffEqType::MIXMASSFRACBETA, kw::mixmassfracbeta::name() }, { DiffEqType::DIRICHLET, kw::dirichlet::name() }, { DiffEqType::MIXDIRICHLET, kw::mixdirichlet::name() }, { DiffEqType::GENDIR, kw::gendir::name() }, { DiffEqType::WRIGHTFISHER, kw::wrightfisher::name() }, { DiffEqType::POSITION, kw::position::name() }, { DiffEqType::DISSIPATION, kw::dissipation::name() }, { DiffEqType::VELOCITY, kw::velocity::name() } }, //! keywords -> Enums { { "no_diffeq", DiffEqType::NO_DIFFEQ }, { kw::ornstein_uhlenbeck::string(), DiffEqType::OU }, { kw::diag_ou::string(), DiffEqType::DIAG_OU }, { kw::skewnormal::string(), DiffEqType::SKEWNORMAL }, { kw::gamma::string(), DiffEqType::GAMMA }, { kw::beta::string(), DiffEqType::BETA }, { kw::numfracbeta::string(), DiffEqType::NUMFRACBETA }, { kw::massfracbeta::string(), DiffEqType::MASSFRACBETA }, { kw::mixnumfracbeta::string(), DiffEqType::MIXNUMFRACBETA }, { kw::mixmassfracbeta::string(), DiffEqType::MIXMASSFRACBETA }, { kw::dirichlet::string(), DiffEqType::DIRICHLET }, { kw::mixdirichlet::string(), DiffEqType::MIXDIRICHLET }, { kw::gendir::string(), DiffEqType::GENDIR }, { kw::wrightfisher::string(), DiffEqType::WRIGHTFISHER }, { kw::position::string(), DiffEqType::POSITION }, { kw::dissipation::string(), DiffEqType::DISSIPATION }, { kw::velocity::string(), DiffEqType::VELOCITY } } ) {} }; } // ctr:: } // walker:: #endif // WalkerDiffEqOptions_h
c++
17
0.492344
80
44.5
122
starcoderdata
<?php function proximo_registro ($bd_base,$tabla) { $sql_prox="SHOW TABLE STATUS FROM ".$bd_base." LIKE '".$tabla."'"; $con=mysql_query($sql_prox) or die (mysql_error()); $res=mysql_fetch_array($con); $num=$res[Auto_increment]; return $num; } /********************************/ function validar_tamano_imagen($imagen, $max_ancho, $max_alto) { if(empty($_FILES[$image]["name"])) {$error.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font face='arial narrow, arial' size='2' color='red'>Debe insertar todas las imagenes solicitadas. \n $extensiones = array("jpg"); $extension_archivo=explode(".", $_FILES[$imagen]["name"]); if(!in_array($extension_archivo, $extensiones)) {$error.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font face='arial narrow, arial' size='2' color='red'>La imagen debe ser JPG \n $img_info = getimagesize($_FILES[$imagen]["tmp_name"]); // $ancho=$img_info[0]; $alto=$img_info[1]; if($ancho > $mas_ancho) {$error.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font face='arial narrow, arial' size='2' color='red'>El ancho de la imagen debe tener un máximo de ".$max_ancho." pixeles \n if($alto > $nax_alto) {$error.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font face='arial narrow, arial' size='2' color='red'>El alto de la imagen debe tener un máximo de ".$max_alto." pixeles \n return $error; } /********************************/ function subir_imagen($nombre_imagen, $directorio, $nuevo_nombre ) { if(move_uploaded_file($_FILES[$nombre_imagen]['tmp_name'], $directorio.$_FILES[$nombre_imagen]['name'])) { chmod($directorio.$_FILES[$nombre_imagen]["name"], 0777); rename( $directorio.$_FILES[$nombre_imagen]["name"], $directorio.$nuevo_nombre.".jpg"); return $subida=TRUE; } else { return $subida=FALSE; } } /*******************************/ function formato_fecha_americano($fecha) { $fechas = explode("-",$fecha); return $gfecha = $fechas[2]."-".$fechas[1]."-".$fechas[0]; } ?>
php
13
0.586291
210
42.787234
47
starcoderdata
from dataclasses import dataclass, field from typing import Any @dataclass(order=True) class PrioritizedItem: priority: int item: Any = field(compare=False)
python
9
0.760479
40
19.875
8
starcoderdata
<?php namespace Pwnraid\Bnet\Warcraft\BattlePets; use Pwnraid\Bnet\Core\AbstractRequest; class BattlePetRequest extends AbstractRequest { public function ability($abilityId) { $data = $this->client->get('battlePet/ability/'.$abilityId); if ($data === null) { return null; } return new AbilityEntity($data); } public function species($speciesId) { $data = $this->client->get('battlePet/species/'.$speciesId); if ($data === null) { return null; } return new SpeciesEntity($data); } public function stats($speciesId, $level = 1, $breedId = 3, $qualityId = 1) { $data = $this->client->get('battlePet/stats/'.$speciesId, [ 'query' => [ 'level' => $level, 'breedId' => $breedId, 'qualityId' => $qualityId, ], ]); if ($data === null) { return null; } return new StatsEntity($data); } public function types() { $data = $this->client->get('data/pet/types'); $types = []; foreach ($data['petTypes'] as $type) { $types[] = new TypeEntity($type); } return $types; } }
php
15
0.502329
79
21.206897
58
starcoderdata
#include "../include/device.h" #include "../include/wlan.h" #include "../include/socket.h" #include "../include/netapp.h" void GeneralEvtHdlr(SlDeviceEvent_t *slGeneralEvent) { } void WlanEvtHdlr(SlWlanEvent_t *slWlanEvent) { } void NetAppEvtHdlr(SlNetAppEvent_t *slNetAppEvent) { } void HttpServerCallback(SlHttpServerEvent_t *slHttpServerEvent, SlHttpServerResponse_t *slHttpServerResponse) { } void SockEvtHdlr(SlSockEvent_t *slSockEvent) { }
c
6
0.720833
63
15
30
starcoderdata
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.insaneio.insane.cryptography; import com.insaneio.insane.string.Strings; /** * @author on 14/10/2014. */ public class HashSaltPair { private String Hash; private String Salt; public HashSaltPair() { } public HashSaltPair(String Hash, String Salt) { this.Hash = Hash; this.Salt = Salt; } public String getHash() { return Hash; } public void setHash(String Hash) { this.Hash = Hash; } public String getSalt() { return Salt; } public void setSalt(String Salt) { this.Salt = Salt; } @Override public String toString() { return Strings.format("Hash{0}{1}{0}Salt{0}{2}", Strings.NEW_LINE, Hash, Salt); } }
java
9
0.599589
88
16.709091
55
starcoderdata
def original_name(url: str) -> str: """Extract the media file name from its URL.""" # Extract the media filename from the URL name = parse_url(url).path.split("/")[2] # If there's a colon in the filename, # it means there's an image size tag. # We want to remove this from the filename if ":" in name: name = name[: name.find(":")] return name
python
12
0.614583
51
34
11
inline
// Package runsafe contains things that leverage the unsafe builtin package. Its contents should be treated as experimental and unstable. package runsafe import ( "bufio" "bytes" "context" "fmt" "regexp" "runtime" "strings" "time" "unsafe" ) // (stuff)(package name).(function name)(type descriptor address, type value address(stuff) var pattern = regexp.MustCompile(`^.+[a-zA-Z][a-zA-Z0-9\-_]*\.[a-zA-Z][a-zA-Z0-9\-_]*\((?P (?P // RecoverCtx returns (from the bottom up) the first context that's encountered in the callstack // it stops the current goroutine to build a stacktrace, walks up the stack to find contexts, and returns the first one // if no context is encountered, an empty context and an UnrecoverableContext Error are returned // this is not guaranteed to work: many things can go wrong, chief among them is that inlined functions elide their parameter memory addresses // see https://dave.cheney.net/2019/12/08/dynamically-scoped-variables-in-go for a more thorough explanation on how this works func RecoverCtx() (context.Context, error) { return emptyItab(context.Background()) } //go:noinline // type descriptors addresses are seemingly constant for a given goroutine // We leverage this to identify parameter addresses that are a context.Context // Specifically, we must build up each of the concrete context.Context implementations // so that we have the full legal set of context descriptors. func emptyItab(_ context.Context) (context.Context, error) { return valueItab(context.WithValue(context.Background(), "", "")) } //go:noinline func valueItab(_ context.Context) (context.Context, error) { ctx, c := context.WithCancel(context.Background()) defer c() return cancelItab(ctx) } //go:noinline func cancelItab(_ context.Context) (context.Context, error) { ctx, c := context.WithDeadline(context.Background(), time.Now()) defer c() return timerItab(ctx) } //go:noinline func timerItab(_ context.Context) (context.Context, error) { return doGetCtx() } // doGetCtx contains the actual logic for context recovery. // The inflated callstack is required to protect against false positives func doGetCtx() (context.Context, error) { var buf [8192]byte n := runtime.Stack(buf[:], false) // get the current callstack as a string sc := bufio.NewScanner(bytes.NewReader(buf[:n])) var ( deadlineType, cancelType, valueType, emptyType uintptr // hold the type descriptor pointers for each of the context implementations stackMatch int // used to count our way up the stack, as the stack is constant the lowest few levels and we need to leverage that ) for sc.Scan() { // for each line (walking up the stack from here) // if the line doesn't match, skip. matches := pattern.FindStringSubmatch(sc.Text()) if matches == nil { continue } // if this is the first iteration, then it's just our function. skip it. if stackMatch == 0 && strings.Contains(sc.Text(), "doGetCtx") { continue } stackMatch++ // grab the two memory addresses (itab and type value) var p1, p2 uintptr _, err1 := fmt.Sscanf(matches[1], "%v", &p1) _, err2 := fmt.Sscanf(matches[2], "%v", &p2) if err1 != nil || err2 != nil { continue } // build up the legal values for each implementation of context // the stackMatch must match the known location in the stack. // Otherwise we might return a malformed context if stackMatch == 1 && strings.Contains(sc.Text(), "timerItab") { deadlineType = p1 } else if stackMatch == 2 && strings.Contains(sc.Text(), "cancelItab") { cancelType = p1 } else if stackMatch == 3 && strings.Contains(sc.Text(), "valueItab") { valueType = p1 } else if stackMatch == 4 && strings.Contains(sc.Text(), "emptyItab") { emptyType = p1 } else if p1 != emptyType && p1 != valueType && p1 != cancelType && p1 != deadlineType { // if we're in the caller's code, and the first parameter isn't a known context implementation, then skip this stack frame continue } if stackMatch <= 4 { // we're still building the legal context implementations continue } // at this point we're done building the legal context implementations, and this matched one. // rebuild a context from the addresses, and return idata := [2]uintptr{p1, p2} return *(*context.Context)(unsafe.Pointer(&idata)), nil } // no context was found. Return a non-nil context to be polite, but also return an error. return context.Background(), UnrecoverableContext{} } // UnrecoverableContext is an error indicating that the context could not be dynamically recovered type UnrecoverableContext struct{} func (UnrecoverableContext) Error() string { return "unable to recover context" }
go
14
0.714345
171
38.598361
122
starcoderdata
protected IDataSet getDataSet() throws Exception { String testDataFileName = getTestDataFileName(); InputStream testDataStream = getResource(getClass().getPackage(), testDataFileName); if (testDataStream == null) { testDataStream = handleTestDataFileNotFound(); // if it is still null, fail gracefully if (testDataStream == null) { throw new NullPointerException( "Test data resource " + getResourceName(getClass().getPackage(), testDataFileName) + " not found and fallback call to handleTestDataFileNotFound() did not provide a substitute."); } } //NOTE: if you are using Apache Crimson, and you try to use local DTDs for your datasets (generated // by DbUnit), you will get an error stating that you're using a relative URI without providing // a baseURI. I upgraded to the latest Xerces, and the problem went away return new FlatXmlDataSet(testDataStream); }
java
17
0.632519
116
60.705882
17
inline
import * as _ from "lodash"; import React from "react"; import { connect } from "react-redux"; import ResultItem from "./ResultItem"; import "@/styles/main.scss"; import "@/styles/input.css"; const mapStateToProps = state => { return { results: state.results.results }; }; const mapDispatchToProps = dispatch => ({}); class Results extends React.Component { constructor() { super(); this.hoverEvent = this.hoverEvent.bind(this); } // TODO hoverEvent(r) { console.log("asddsasdsa", r); } render() { return ( {this.props.results.map((result, key) => ( <ResultItem index={`result--${key}`} result={result} /> ))} ); } } export default connect( mapStateToProps, mapDispatchToProps )(Results); export { Results, mapStateToProps };
javascript
18
0.618532
65
17.886364
44
starcoderdata
@Test public void testLibrary() { System.err.println("====================================== testLibrary"); s.rawEval("library(lhs)"); // this next call was failing with rserve 0.6-0 s.rawEval("library(rgenoud)"); }
java
7
0.496094
81
31.125
8
inline
/* * Copyright 2006, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. */ #ifndef _SPLIT_LAYOUT_BUILDER_H #define _SPLIT_LAYOUT_BUILDER_H #include class BSplitLayoutBuilder { public: BSplitLayoutBuilder( orientation orientation = B_HORIZONTAL, float spacing = B_USE_DEFAULT_SPACING); BSplitLayoutBuilder(BSplitView* view); BSplitView* SplitView() const; BSplitLayoutBuilder& GetSplitView(BSplitView** view); BSplitLayoutBuilder& Add(BView* view); BSplitLayoutBuilder& Add(BView* view, float weight); BSplitLayoutBuilder& Add(BLayoutItem* item); BSplitLayoutBuilder& Add(BLayoutItem* item, float weight); BSplitLayoutBuilder& SetCollapsible(bool collapsible); BSplitLayoutBuilder& SetInsets(float left, float top, float right, float bottom); operator BSplitView*(); private: BSplitView* fView; }; #endif // _SPLIT_LAYOUT_BUILDER_H
c
10
0.719
69
26.027027
37
starcoderdata
void OcctJni_Viewer::initContent() { myContext->RemoveAll (Standard_False); if (myViewCube.IsNull()) { myViewCube = new AIS_ViewCube(); { // setup view cube size static const double THE_CUBE_SIZE = 60.0; myViewCube->SetSize (myDevicePixelRatio * THE_CUBE_SIZE, false); myViewCube->SetBoxFacetExtension (myViewCube->Size() * 0.15); myViewCube->SetAxesPadding (myViewCube->Size() * 0.10); myViewCube->SetFontHeight (THE_CUBE_SIZE * 0.16); } // presentation parameters myViewCube->SetTransformPersistence (new Graphic3d_TransformPers (Graphic3d_TMF_TriedronPers, Aspect_TOTP_RIGHT_LOWER, Graphic3d_Vec2i (200, 200))); myViewCube->Attributes()->SetDatumAspect (new Prs3d_DatumAspect()); myViewCube->Attributes()->DatumAspect()->SetTextAspect (myTextStyle); // animation parameters myViewCube->SetViewAnimation (myViewAnimation); myViewCube->SetFixedAnimationLoop (false); myViewCube->SetAutoStartAnimation (true); } myContext->Display (myViewCube, false); OSD_Timer aTimer; aTimer.Start(); if (!myShape.IsNull()) { Handle(AIS_Shape) aShapePrs = new AIS_Shape (myShape); myContext->Display (aShapePrs, Standard_False); } else { BRepPrimAPI_MakeBox aBuilder (1.0, 2.0, 3.0); Handle(AIS_Shape) aShapePrs = new AIS_Shape (aBuilder.Shape()); myContext->Display (aShapePrs, Standard_False); } myView->FitAll(); aTimer.Stop(); Message::SendInfo (TCollection_AsciiString() + "Presentation computed in " + aTimer.ElapsedTime() + " seconds"); }
c++
12
0.692209
152
34.613636
44
inline
describe("Filter: humanizeKind", function() { 'use strict'; var humanizeKindFilter; beforeEach(inject(function (_humanizeKindFilter_) { humanizeKindFilter = _humanizeKindFilter_; })); it('should return a lowercase display kind', function() { var result = humanizeKindFilter('DeploymentConfig'); expect(result).toEqual('deployment config'); }); it('should return a title case display kind', function() { var result = humanizeKindFilter('DeploymentConfig', true); expect(result).toEqual('Deployment Config'); }); it('should special case ServiceInstance as "provisioned service"', function() { var result = humanizeKindFilter('ServiceInstance'); expect(result).toEqual('provisioned service'); result = humanizeKindFilter('ServiceInstance', true); expect(result).toEqual('Provisioned Service'); }); it('should return the original value if null, undefined, or empty', function() { var result = humanizeKindFilter(null); expect(result).toBeNull(); result = humanizeKindFilter(); expect(result).toBeUndefined(); result = humanizeKindFilter(''); expect(result).toEqual(''); }); });
javascript
11
0.703795
82
32.666667
36
starcoderdata
void XcbWindow::selnotify(xcb_atom_t property, bool propnotify) { if (property == XCB_ATOM_NONE) { LOGGER()->debug("got no data"); return; } xcb_get_property_reply_t* reply = xcb_get_property_reply(connection, xcb_get_property(connection, 0, win, property, XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX), nullptr); if (reply) { std::size_t len = xcb_get_property_value_length(reply); if (propnotify && len == 0) { // propnotify with no data means all data has been // transferred, and we no longer need property // notify events m_eventmask &= ~XCB_EVENT_MASK_PROPERTY_CHANGE; constexpr uint32_t mask = XCB_CW_EVENT_MASK; const uint32_t values[1] = {m_eventmask}; xcb_change_window_attributes(connection, win, mask, values); } if (reply->type == m_incr) { // activate property change events so we receive // notification about the next chunk m_eventmask |= XCB_EVENT_MASK_PROPERTY_CHANGE; constexpr uint32_t mask = XCB_CW_EVENT_MASK; const uint32_t values[1] = {m_eventmask}; xcb_change_window_attributes(connection, win, mask, values); // deleting the property is transfer start signal xcb_delete_property(connection, win, property); } else if (len > 0) { char* data = (char*) xcb_get_property_value(reply); // fix line endings (\n -> \r) char* repl = data; char* last = data + len; while ((repl = (char*) memchr(repl, '\n', last - repl))) *repl++ = '\r'; // todo: move to a Term::paste function bool brcktpaste = m_term->mode()[term::MODE_BRCKTPASTE]; if (brcktpaste) m_tty->write({"\033[200~", 6}); m_tty->write({data, len}); if (brcktpaste) m_tty->write({"\033[201~", 6}); } std::free(reply); } else LOGGER()->error("unable to get clip property!"); }
c++
15
0.543262
109
37.472727
55
inline
/* global tw */ import React from 'react' import { ThemeProvider } from 'emotion-theming' import { css, injectGlobal } from 'emotion' import styled from 'react-emotion' import { connect } from 'react-redux' import { graphql } from 'gatsby' import { toggleContact } from '../../actions' import { Header } from '../blocks' import { Back, DownButton, Image, Main, ScrollContainer, RightImage, SEO, UpButton, } from '../elements' import { unless, isNil, pick } from '../../helpers' import { theme as EmotionTheme } from '../theme' import '../../fonts/open-sans/stylesheet.css' import '../../fonts/plex/stylesheet.css' injectGlobal` body { ${tw(['relative', 'm-0'])}; } ` const ImageWrapper = styled('div')` ${tw(['hidden', 'fixed', 'pin'])}; ${({ appear }) => appear && tw(['block'])}; ${tw(['screen:block'])}; ` const TemplateWrapper = ({ allSite, backSlider, children, color, hasBackImage, notDown, image, location, meta, rightImage, seo, sicgrid, storedTheme, title, }) => { const { lang } = seo async function loadPolyfills() { if (window !== undefined && typeof window.IntersectionObserver === 'undefined') { await import('intersection-observer') } } React.useEffect(() => { loadPolyfills(); }, []) return ( <ThemeProvider theme={EmotionTheme[storedTheme]}> <SEO {...{ seo }} /> <Header {...{ allSite }} {...{ color }} {...{ lang }} {...{ location }} {...{ meta }} {...{ title }} /> {unless(isNil, () => ( <ImageWrapper appear={backSlider || hasBackImage}> <Image {...{ image }} /> ))(image)} <Back {...{ color }} /> {unless(isNil, () => ( <div className={css` ${tw('absolute md:block hidden pin')}; `} > <RightImage {...{ rightImage }} {...{ sicgrid }} /> ))(rightImage)} <DownButton {...{ notDown }} /> <UpButton /> ) } export default connect( pick([ 'backSlider', 'contactForm', 'hasBackImage', 'rightImage', 'sicgrid', 'storedTheme', ]), { toggleContact } )(TemplateWrapper) export const query = graphql` fragment MetaFragment on PrismicMeta { data { title description { html text } addressesru { html text } addressesfr { html text } email { url } links { linktype link { url } } development acciolink { url } headerlinks { linktitle link { url } } query { inputtype question { html } } } } `
javascript
25
0.505104
85
17.746914
162
starcoderdata
// ColorButtonTest.cpp // Copyright (C) 2019 // This file is public domain software. #include #include #include #include "color_button.hpp" #include "color_value/color_value.h" #include static BOOL s_bDialogInit = FALSE; static COLOR_BUTTON s_color_button_1; static COLOR_BUTTON s_color_button_2; static void DoSetColorText(HWND hwnd, INT nItemID, COLORREF value) { char buf[64]; value = color_value_fix(value); color_value_store(buf, 64, value); SetDlgItemText(hwnd, nItemID, buf); } static BOOL OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) { s_color_button_1.SetHWND(GetDlgItem(hwnd, psh1)); s_color_button_2.SetHWND(GetDlgItem(hwnd, psh2)); s_color_button_1.SetColor(RGB(255, 0, 255)); s_color_button_2.SetColor(RGB(0, 255, 0)); DoSetColorText(hwnd, edt1, s_color_button_1.GetColor()); DoSetColorText(hwnd, edt2, s_color_button_2.GetColor()); s_bDialogInit = TRUE; return TRUE; } static void OnOK(HWND hwnd) { char buf[64]; GetDlgItemTextA(hwnd, edt1, buf, 64); uint32_t value1 = color_value_parse(buf); if (value1 == uint32_t(-1)) { SendDlgItemMessage(hwnd, edt1, EM_SETSEL, 0, -1); SetFocus(GetDlgItem(hwnd, edt1)); MessageBox(hwnd, TEXT("Invalid color value"), NULL, MB_ICONERROR); return; } GetDlgItemTextA(hwnd, edt2, buf, 64); uint32_t value2 = color_value_parse(buf); if (value2 == uint32_t(-1)) { SendDlgItemMessage(hwnd, edt2, EM_SETSEL, 0, -1); SetFocus(GetDlgItem(hwnd, edt2)); MessageBox(hwnd, TEXT("Invalid color value"), NULL, MB_ICONERROR); return; } TCHAR szText[128]; StringCbPrintf(szText, sizeof(szText), TEXT("#%06X, #%06X"), value1, value2); MessageBox(hwnd, szText, TEXT("Color Values"), MB_ICONINFORMATION); value1 = color_value_fix(value1); value2 = color_value_fix(value2); EndDialog(hwnd, IDOK); } static void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { if (!s_bDialogInit) return; switch (id) { case IDOK: OnOK(hwnd); break; case IDCANCEL: EndDialog(hwnd, id); break; case psh1: if (codeNotify == BN_CLICKED) { if (s_color_button_1.DoChooseColor()) { s_bDialogInit = FALSE; DoSetColorText(hwnd, edt1, s_color_button_1.GetColor()); s_bDialogInit = TRUE; } } break; case psh2: if (codeNotify == BN_CLICKED) { if (s_color_button_2.DoChooseColor()) { s_bDialogInit = FALSE; DoSetColorText(hwnd, edt2, s_color_button_2.GetColor()); s_bDialogInit = TRUE; } } break; case edt1: if (codeNotify == EN_CHANGE || codeNotify == EN_KILLFOCUS) { char buf[64]; GetDlgItemTextA(hwnd, edt1, buf, 64); uint32_t value = color_value_parse(buf); if (value != uint32_t(-1)) { value = color_value_fix(value); s_color_button_1.SetColor(value); if (codeNotify == EN_KILLFOCUS) { s_bDialogInit = FALSE; DoSetColorText(hwnd, edt1, value); s_bDialogInit = TRUE; } } } break; case edt2: if (codeNotify == EN_CHANGE || codeNotify == EN_KILLFOCUS) { char buf[64]; GetDlgItemTextA(hwnd, edt2, buf, 64); uint32_t value = color_value_parse(buf); if (value != uint32_t(-1)) { value = color_value_fix(value); s_color_button_2.SetColor(value); if (codeNotify == EN_KILLFOCUS) { s_bDialogInit = FALSE; DoSetColorText(hwnd, edt2, value); s_bDialogInit = TRUE; } } } break; } } static void OnDrawItem(HWND hwnd, const DRAWITEMSTRUCT * lpDrawItem) { if (!s_color_button_1.OnParentDrawItem(hwnd, lpDrawItem)) { s_color_button_2.OnParentDrawItem(hwnd, lpDrawItem); } } static void OnDestroy(HWND hwnd) { s_bDialogInit = FALSE; } INT_PTR CALLBACK DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_INITDIALOG, OnInitDialog); HANDLE_MSG(hwnd, WM_COMMAND, OnCommand); HANDLE_MSG(hwnd, WM_DRAWITEM, OnDrawItem); HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy); } return 0; } INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow) { InitCommonControls(); DialogBox(hInstance, MAKEINTRESOURCE(1), NULL, DialogProc); return 0; }
c++
15
0.545472
81
26.297297
185
starcoderdata
using System.Collections.Generic; using AtEase.Extensions; using Xunit; namespace AtEase.Test { public class EnumExtensionsTests { public enum TestEnum { Enum1 = 1, Enum2 = 2, Enum3 = 3 } public static IEnumerable EnumToInt => new List { new object[] {TestEnum.Enum1, 1}, new object[] {TestEnum.Enum2, 2}, new object[] {TestEnum.Enum3, 3} }; [Theory] [MemberData(nameof(EnumToInt))] public void enum_to_int(TestEnum @enum, int expectedValue) { var enumValue = @enum.ToInt(); Assert.Equal(expectedValue, enumValue); } public static IEnumerable IntToEnum => new List { new object[] {1,TestEnum.Enum1}, new object[] {2,TestEnum.Enum2}, new object[] {3,TestEnum.Enum3} }; [Theory] [MemberData(nameof(IntToEnum))] public void int_to_enum(int value, TestEnum expectedValue) { var @enum = value.AsEnum Assert.Equal(expectedValue, @enum); } } }
c#
15
0.5279
79
25.211538
52
starcoderdata
public NodeReference determineReplicationSourceNode(SystemMetadata sysMeta) { NodeReference source = null; NodeReference authNode = sysMeta.getAuthoritativeMemberNode(); for (Replica replica : sysMeta.getReplicaList()) { if (replica.getReplicaMemberNode().equals(authNode) && replica.getReplicationStatus().equals(ReplicationStatus.COMPLETED)) { source = authNode; break; } else if (source == null && replica.getReplicationStatus().equals(ReplicationStatus.COMPLETED)) { // set the source to the first completed replica but keep iterating to find // the authoritative MN and give preference to its 'replica' as source. source = replica.getReplicaMemberNode(); } } return source; }
java
12
0.614773
92
50.823529
17
inline
bool Lexer::readComment() { if (peek() != '/' && peek() != '*') return false; //Read single line comments if (peek() == '/') { while (peek() != '\n') advance(); lineNumber++; advance(); } //Read multiline comments if (peek() == '*') { advance(2); while (*forward != '*' || peek() != '/') { if (*forward == '\0') throw "[ERROR] Comment at line: " + std::to_string(lineNumber) + " was not closed"; if (*forward == '\n') lineNumber++; advance(); } advance(2); } return true; }
c++
13
0.436573
117
26.636364
22
inline
package com.wjx.android.wanandroidmvp.contract.setting; import com.wjx.android.wanandroidmvp.base.interfaces.IBaseView; import com.wjx.android.wanandroidmvp.bean.me.LogoutData; import io.reactivex.Observable; /** * Created with Android Studio. * Description: * * @author: Wangjianxian * @date: 2020/01/16 * Time: 13:54 */ public class Contract { public interface ILogoutModel { /** * 退出登录 * @return */ Observable logout(); } public interface ILogoutView extends IBaseView { void onLogout(LogoutData logoutData); } public interface ILogoutPresenter { void logout(); } }
java
8
0.661743
63
19.515152
33
starcoderdata
#include #include #include #include #include #include #include #include #include // This is a wrapper to tweedledum that exposes to C a very small // subset of tweedledum's functionality. This can be compiled to a // shared library and then used via CFFI. extern "C" { extern char* tweedledum_synthesis_dbs(uint32_t* perm, uint32_t size) { using namespace tweedledum; std::vector permutation(perm, perm+size); auto network = dbs stg_from_spectrum()); std::stringstream ss; write_quil(network, ss); const std::string resultstr = ss.str(); char* str = (char*) malloc( (resultstr.length()+1) * sizeof(char) ); strcpy(str, resultstr.c_str()); return str; } }
c
15
0.715526
77
32.451613
31
starcoderdata
package nl.miwgroningen.se6.heartcoded.CaTo.service; import nl.miwgroningen.se6.heartcoded.CaTo.dto.UserDTO; import nl.miwgroningen.se6.heartcoded.CaTo.dto.UserEditPasswordDTO; import nl.miwgroningen.se6.heartcoded.CaTo.dto.UserRegistrationDTO; import nl.miwgroningen.se6.heartcoded.CaTo.mappers.*; import nl.miwgroningen.se6.heartcoded.CaTo.model.User; import nl.miwgroningen.se6.heartcoded.CaTo.repository.UserRepository; import org.apache.commons.io.IOUtils; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Optional; import static org.aspectj.bridge.MessageUtil.fail; /** * @author * * Gets data from the user repository and gives it to the controllers. */ @Service public class UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final UserRegistrationMapper userRegistrationMapper; private final UserEditPasswordMapper userEditPasswordMapper; private PasswordEncoder passwordEncoder; public UserService(UserRepository userRepository, UserMapper userMapper, UserRegistrationMapper userRegistrationMapper, UserEditPasswordMapper userEditPasswordMapper, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.userMapper = userMapper; this.userRegistrationMapper = userRegistrationMapper; this.userEditPasswordMapper = userEditPasswordMapper; this.passwordEncoder = passwordEncoder; } public List findAllUsers() { return userMapper.toDTO(userRepository.findAll()); } public Integer totalNumberOfUsers() { return userRepository.countAllByUserRoleIsNot("ROLE_ADMIN"); } public UserDTO getById(Integer userId) { return userMapper.toDTO(userRepository.getById(userId)); } public void deleteUserById(Integer userId) { userRepository.deleteById(userId); } public UserEditPasswordDTO getUserEditDTOById(Integer userId) { return userEditPasswordMapper.toDTO(userRepository.getById(userId)); } public void editUserInfo(UserDTO user) { User result = userRepository.getById(user.getUserId()); result.setName(user.getName()); result.setEmail(user.getEmail()); if (user.getProfilePicture().length != 0) { result.setProfilePicture(user.getProfilePicture()); } userRepository.save(result); } public void editPassword(UserEditPasswordDTO user) { User result = userRepository.getById(user.getUserId()); result.setPassword(passwordEncoder.encode(user.getNewPassword())); userRepository.save(result); } public void saveNewUser(UserRegistrationDTO userDTO) { if(userDTO.getPassword().equals(userDTO.getPasswordCheck())) { userDTO.setPassword(passwordEncoder.encode(userDTO.getPassword())); User user = userRegistrationMapper.toUser(userDTO); user.setUserRole("ROLE_USER"); userRepository.save(user); } } private void setProfilePictureFromPath(User user, String s) { try { InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream(s); if (inputStream == null) { fail("Unable to find resource"); } else { user.setProfilePicture(IOUtils.toByteArray(inputStream)); } } catch (IOException ioException) { System.out.println(ioException.getMessage()); } } public void deleteProfilePicture(Integer userId) { User user = userRepository.getById(userId); user.setProfilePicture(null); userRepository.save(user); } public void saveSeederUser(User user, String profilePictureFileName) { user.setUserRole("ROLE_USER"); user.setPassword(passwordEncoder.encode(user. String inputStreamString; if (!profilePictureFileName.equals("")) { inputStreamString = "static/seederProfilePictures/" + profilePictureFileName; setProfilePictureFromPath(user, inputStreamString); } userRepository.save(user); } public void saveAdmin() { User adminUser = new User(); adminUser.setUserRole("ROLE_ADMIN"); adminUser.setName("Admin"); adminUser.setEmail(" adminUser.setPassword( userRepository.save(adminUser); } public Optional findUserByEmail(String email) { return userRegistrationMapper.toDTO(userRepository.findByEmail(email)); } public Optional findUserIdByEmail(String email) { Optional userId = Optional.empty(); Optional user = userRepository.findByEmail(email); if (user.isPresent()) { userId = Optional.of(user.get().getUserId()); } return userId; } public boolean emailInUse(String email) { return findUserByEmail(email).isPresent(); } public UserDTO getCurrentUser() { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return getById(user.getUserId()); } public boolean currentUserIsSiteAdmin() { return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream() .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); } public boolean userIsSiteAdmin(Integer userId) { Optional user = userRepository.findById(userId); if (user.isPresent()) { return user.get().getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); } return false; } public Integer getCircleOne(Integer userId) { return userRepository.getById(userId).getCircleOne(); } public Integer getCircleTwo(Integer userId) { return userRepository.getById(userId).getCircleTwo(); } public Integer getCircleThree(Integer userId) { return userRepository.getById(userId).getCircleThree(); } public List findWithNameContains(String keyword) { List userList = userRepository.findByNameContains(keyword); removeSiteAdminFromList(userList); return userMapper.toDTONoProfilePicture(userList); } private void removeSiteAdminFromList(List userList) { userList.removeIf(user -> user.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ROLE_ADMIN"))); } public boolean passwordMatches(String oldPassword, Integer userId) { return passwordEncoder.matches(oldPassword, userRepository.getById(userId).getPassword()); } public Integer getAdminId(String role) { Optional admin = userRepository.findByUserRole(role); Integer adminId = 0; if (admin.isPresent()) { adminId = admin.get().getUserId(); } return adminId; } }
java
15
0.683317
116
32.949309
217
starcoderdata
#pragma once #include "LevelBackupManager.hpp" #include #include class BackupScheduleLayer : public BrownAlertDelegate, TextInputDelegate { protected: GJGameLevel* m_pLevel; LevelBackupSettings* m_pBackup; InputNode* m_pInput; CCLabelBMFont* m_pLabel1; CCLabelBMFont* m_pLabel2; void setup() override; void onToggleAutoBackup(CCObject*); void textChanged(CCTextInputNode*) override; public: static BackupScheduleLayer* create(GJGameLevel* level); };
c++
9
0.695652
74
26.380952
21
starcoderdata
var searchData= [ ['namemap',['nameMap',['../classEnum.html#a16ed815780971f879c93e87fa938aade',1,'Enum::nameMap()'],['../classPreference.html#ae5d9ddf37fb9be4c39ceb4ca576e9877',1,'Preference::nameMap()']]], ['names',['names',['../classEnum.html#aca253f52f9b953d20bdda04538fe3fc8',1,'Enum']]], ['newobject',['newObject',['../classAbstractFactory.html#a27751ded3346e5587ca727497467ead2',1,'AbstractFactory::newObject()'],['../classObjectFactory.html#ad5625cc42f868ac270e539a03f27d6da',1,'ObjectFactory::newObject()']]], ['numproperties',['numProperties',['../classDataObject.html#aae027f7771477b27ea623d4c15c43b35',1,'DataObject']]] ];
javascript
8
0.752336
226
90.714286
7
starcoderdata
package ca.cmfly.controller; public class LightId { public byte strandNum; public byte lightNum; public LightId(byte strandNum, byte lightNum) { this.strandNum = strandNum; this.lightNum = lightNum; } public LightId(int strandNum, int lightNum) { this.strandNum = (byte) strandNum; this.lightNum = (byte) lightNum; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + lightNum; result = prime * result + strandNum; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LightId other = (LightId) obj; if (lightNum != other.lightNum) return false; if (strandNum != other.strandNum) return false; return true; } }
java
10
0.639955
48
18.651163
43
starcoderdata
public APIProduct getAPIProduct(APIProductIdentifier identifier) throws APIManagementException { String apiProductPath = APIUtil.getAPIProductPath(identifier); Registry registry; try { String productTenantDomain = MultitenantUtils.getTenantDomain( APIUtil.replaceEmailDomainBack(identifier.getProviderName())); int productTenantId = getTenantManager() .getTenantId(productTenantDomain); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(productTenantDomain)) { APIUtil.loadTenantRegistry(productTenantId); } if (this.tenantDomain == null || !this.tenantDomain.equals(productTenantDomain)) { //cross tenant scenario registry = getRegistryService().getGovernanceUserRegistry( getTenantAwareUsername(APIUtil.replaceEmailDomainBack(identifier.getProviderName())), productTenantId); } else { registry = this.registry; } GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY); Resource productResource = registry.get(apiProductPath); String artifactId = productResource.getUUID(); if (artifactId == null) { throw new APIManagementException("artifact id is null for : " + apiProductPath); } GenericArtifact productArtifact = artifactManager.getGenericArtifact(artifactId); APIProduct apiProduct = APIUtil.getAPIProduct(productArtifact, registry); //todo : implement visibility return apiProduct; } catch (RegistryException e) { String msg = "Failed to get API Product from : " + apiProductPath; throw new APIManagementException(msg, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { String msg = "Failed to get API Product from : " + apiProductPath; throw new APIManagementException(msg, e); } }
java
17
0.645161
127
50.439024
41
inline
func TestEncodeIntegers(t *testing.T) { test := func(item Item) { t.Helper() val, err := EncodeItem(item) if err != nil { t.Error(err) return } if val != "123" { t.Errorf("want %q, got %q", "123", val) } } test(Item{ Value: int(123), }) test(Item{ Value: uint(123), }) test(Item{ Value: int8(123), }) test(Item{ Value: uint8(123), }) test(Item{ Value: int16(123), }) test(Item{ Value: uint16(123), }) test(Item{ Value: int32(123), }) test(Item{ Value: uint32(123), }) test(Item{ Value: int64(123), }) test(Item{ Value: uint64(123), }) // Boundary value check val, err := EncodeItem(Item{ Value: int64(MaxInteger), }) if err != nil { t.Error(err) } if val != "999999999999999" { t.Errorf("want 999999999999999, got %q", val) } _, err = EncodeItem(Item{ Value: int64(MaxInteger + 1), }) if err == nil { t.Error("want error, not not") } val, err = EncodeItem(Item{ Value: int64(MinInteger), }) if err != nil { t.Error(err) } if val != "-999999999999999" { t.Errorf("want -999999999999999, got %q", val) } _, err = EncodeItem(Item{ Value: int64(MinInteger - 1), }) if err == nil { t.Error("want error, not not") } }
go
14
0.580328
48
14.455696
79
inline
bool readInBitmap(Bitmap *bitmap, const char *filePath) { FILE *inFile = fopen(filePath, "rb"); if(inFile) { // Read bitmap header fread(&bitmap->header, 1, sizeof(BitmapHeader), inFile); // Allocate space for pixel data bitmap->data = (IntColor *) malloc(bitmap->header.dataSize); // Move to start of pixel data and read fseek(inFile, bitmap->header.dataOffset, SEEK_SET); fread(bitmap->data, 1, bitmap->header.dataSize, inFile); fclose(inFile); return true; } else { printf("Failed to read bitmap file, could not open file."); return false; } }
c
12
0.607034
68
30.190476
21
inline
def cell2str(obj, **kwargs): """find a method to convert obj to string, considering kwargs such as precision""" for method in [_none2str, _str2str, _int2str, _float2str, _np2str, _ta2str, _misc2str]: rval = method(obj, **kwargs) if rval is not None: return rval raise TypeError('method for "%s" type %s not found' % (obj, type(obj)))
python
10
0.59596
75
43.111111
9
inline
# Generated by Django 2.0.1 on 2018-08-14 12:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('JuHPLC', '0019_calibration_jsonjuhplcchromatogram'), ] operations = [ migrations.AddField( model_name='calibration', name='Channel', field=models.TextField(default=''), preserve_default=False, ), migrations.AddField( model_name='calibration', name='Column', field=models.TextField(default=''), preserve_default=False, ), migrations.AddField( model_name='calibration', name='Eluent', field=models.TextField(default=''), preserve_default=False, ), migrations.AddField( model_name='calibration', name='Flow', field=models.FloatField(default=1), preserve_default=False, ), migrations.AddField( model_name='calibration', name='Name', field=models.TextField(default=''), preserve_default=False, ), migrations.AddField( model_name='calibration', name='RetentionFactor', field=models.FloatField(default=0), preserve_default=False, ), migrations.AddField( model_name='calibration', name='RetentionFactorError', field=models.FloatField(default=0), preserve_default=False, ), migrations.AddField( model_name='calibration', name='Slope', field=models.FloatField(default=1), preserve_default=False, ), migrations.AddField( model_name='calibration', name='UVWaveLength', field=models.FloatField(default=254), preserve_default=False, ), migrations.AddField( model_name='calibration', name='Unit', field=models.TextField(default='g'), preserve_default=False, ), migrations.AddField( model_name='calibration', name='YAxisIntercept', field=models.FloatField(default=0), preserve_default=False, ), ]
python
13
0.532402
62
28.886076
79
starcoderdata
package main import ( "errors" "flag" "fmt" "html" "io" "os" "path/filepath" "regexp" "strings" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" "github.com/mattn/go-zglob" "github.com/zetamatta/seek/argf" ) const ( UTF8BOM = "\xEF\xBB\xBF" MAGENTA = "\x1B[35;1m" GREEN = "\x1B[32;1m" AQUA = "\x1B[36;1m" WHITE = "\x1B[37;1m" RED = "\x1B[31;1m" RESET = "\x1B[0m" ) type FlagStrings []string func (f *FlagStrings) String() string { return strings.Join([]string(*f), ",") } func (f *FlagStrings) Set(value string) error { *f = append(*f, value) return nil } var multiPatterns FlagStrings var ignoreCase = flag.Bool("i", false, "ignore case") var recursive = flag.Bool("r", false, "recursive") var outputHtml = flag.Bool("html", false, "output html") var flagBefore = flag.Int("B", 0, "print N lines before matching lines") var flagAfter = flag.Int("A", 0, "print N lines after matching lines") var flagNoColor = flag.Bool("no-color", false, "no color") func makeRegularExpression(pattern string) (*regexp.Regexp, error) { if *ignoreCase { pattern = "(?i)" + pattern } pattern = strings.Replace(pattern, `\<`, `\b`, -1) pattern = strings.Replace(pattern, `\>`, `\b`, -1) return regexp.Compile(pattern) } func main1() error { flag.Var(&multiPatterns, "m", "multi regular expression") flag.Parse() args := flag.Args() if len(args) < 1 { fmt.Fprintf(os.Stderr, "Usage: %s [flags...] REGEXP Files...\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, " Files: **/*.go ... find *.go files recursively.\n") return nil } var rxs []*regexp.Regexp if multiPatterns == nil || len(multiPatterns) <= 0 { rx, err := makeRegularExpression(args[0]) if err != nil { return err } rxs = []*regexp.Regexp{rx} args = args[1:] } else { for _, pattern := range multiPatterns { rx, err := makeRegularExpression(pattern) if err != nil { return err } rxs = append(rxs, rx) } } var output func(fname string, line int, text string, m [][]int) if *outputHtml { fmt.Println(" style=\"background-color:lightgray\">") output = func(fname string, line int, text string, m [][]int) { fmt.Printf(` style="color:magenta">%s style="color:green">%d style="color:aqua">: html.EscapeString(fname), line) last := 0 for i := 0; i < len(m); i++ { fmt.Printf(`%s<span style="color:red">%s html.EscapeString(text[last:m[i][0]]), html.EscapeString(text[m[i][0]:m[i][1]])) last = m[i][1] } fmt.Printf("%s html.EscapeString(text[last:])) } defer func() { fmt.Println(" }() } else { var out io.Writer if *flagNoColor { out = colorable.NewNonColorable(os.Stdout) } else if isatty.IsTerminal(os.Stdout.Fd()) { out = colorable.NewColorableStdout() } else { out = colorable.NewNonColorable(os.Stdout) } needReset := false output = func(fname string, line int, text string, m [][]int) { fmt.Fprintf(out, MAGENTA+"%s"+WHITE+":"+GREEN+"%d"+AQUA+":"+WHITE, fname, line) last := 0 for i := 0; i < len(m); i++ { fmt.Fprintf(out, "%s"+RED+"%s"+WHITE, text[last:m[i][0]], text[m[i][0]:m[i][1]]) last = m[i][1] } fmt.Fprintln(out, text[last:]) needReset = true } defer func() { if needReset { fmt.Fprint(out, RESET) } }() } var files []string if *recursive { for _, arg1 := range args { stat1, err := os.Stat(arg1) if err == nil && stat1.IsDir() { filepath.Walk(arg1, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { files = append(files, path) } return nil }) } else { files = append(files, arg1) } } } else { for _, arg1 := range args { if addfiles, err := zglob.Glob(arg1); err == nil && addfiles != nil && len(addfiles) > 0 { for _, file1 := range addfiles { stat, err := os.Stat(file1) if err == nil && !stat.IsDir() { files = append(files, file1) } } } else if stat1, err := os.Stat(arg1); err == nil && stat1.IsDir() { fmt.Fprintf(os.Stderr, "%s is directory\n", arg1) } else { files = append(files, arg1) } } } r := argf.NewFiles(files) r.OnError = func(err error) error { fmt.Fprintln(os.Stderr, err.Error()) return nil } found := false beforeBuffer := make([]string, 0, *flagBefore) afterCount := 0 for r.Scan() { text := r.Text() text = strings.Replace(text, UTF8BOM, "", 1) m := (func() [][]int { for _, rx1 := range rxs { m1 := rx1.FindAllStringIndex(text, -1) if m1 != nil { return m1 } } return nil })() if m != nil { found = true // for `-B n` for i, s := range beforeBuffer { output(r.Filename(), r.FNR()-len(beforeBuffer)+i, s, [][]int{}) } beforeBuffer = beforeBuffer[:0] output(r.Filename(), r.FNR(), text, m) afterCount = *flagAfter } else if afterCount > 0 { afterCount-- output(r.Filename(), r.FNR(), text, [][]int{}) } else if *flagBefore > 0 { beforeBuffer = append(beforeBuffer, text) if len(beforeBuffer) > *flagBefore { beforeBuffer = beforeBuffer[1:] } } } if r.Err() != nil { return r.Err() } if found { return nil } else { return errors.New("Not found") } } func main() { if err := main1(); err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } }
go
21
0.597045
128
22.834783
230
starcoderdata